diff --git a/.env.example b/.env.example index a3e2b48167..12f8a08257 100644 --- a/.env.example +++ b/.env.example @@ -138,6 +138,14 @@ OPENSKY_CLIENT_SECRET= # Optional paid Patreon tokens raise request limits; there is no free API key. LL2_API_TOKEN= +# Optional: NASA's public ISS telemetry (the ISSLive feed, served by +# Lightstreamer). Off by default: the feed publishes no terms of use, so the +# server contacts it only when this is 1. It then holds one connection, open +# only while a browser has the ISS model on screen, and the model's solar +# arrays, radiators and Ku-band dish take their real angles from it. No key. +# See DATA_SOURCES.md. +# ISS_TELEMETRY_ENABLED= + # Optional: OpenSky credentials JSON file path, used when the two values above # are empty: the credentials.json your OpenSky account page downloads when you # create an API client. Use an absolute path for compatibility with launchers. diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index d4023986af..0133c41125 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -1,13 +1,13 @@ # Data Sources & Attribution -God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources. The bundled 3D models are the project's own procedural fleet models, MIT-licensed with the code ([`public/models/README.md`](public/models/README.md)). +God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources. The bundled 3D models are the project's own procedural fleet models, MIT-licensed with the code, except NASA's ISS model (`public/models/iss.glb`) ([`public/models/README.md`](public/models/README.md)). How to read this: - **The non-permissive datasets are carved out, not omitted.** Some bundled data (e.g. TeleGeography, CC BY-NC-SA) isn't MIT-compatible. Rather than hide it, we **bundle it with a clear license carve-out** so the app works out of the box — but it stays under the provider's terms. - **If your use doesn't fit a dataset's license, remove that dataset.** Most importantly: TeleGeography is **NonCommercial** — commercial users must delete it (or license it from TeleGeography). It's one self-contained folder. - **Attribution is shown in-app** and listed here. Keep it intact. The required Google/Cesium credit renders on the on-globe credit line (bottom-left, `#cesium-credits`), and every per-layer credit below is registered into the expandable **"Data attribution"** lightbox on that line (`src/data/dataCredits.js` → `viewer.creditDisplay.addStaticCredit`). Both stay visible in clean-view and recording modes. -- **The bundled 3D models are the project's own.** Every model under `public/models/` is a procedural fleet model generated by the project maintainers and covered by the repository's MIT license; [`public/models/README.md`](public/models/README.md) describes the set. +- **The bundled 3D models are the project's own, but one.** Every model under `public/models/` except `iss.glb` is a procedural model generated by the project maintainers (the fleet, and Tiangong from `scripts/build-tiangong-model.py`) and covered by the repository's MIT license; `iss.glb` is NASA's public-domain model of the ISS (see NASA 3D Resources below); [`public/models/README.md`](public/models/README.md) describes the set. --- @@ -34,6 +34,10 @@ How to read this: | **Open Vessel Photos** (`openvesselphotos.org/v1/mmsi/{mmsi}`) | One photo of the selected vessel, by MMSI, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI | Free, keyless public API ([README](https://github.com/louptheron/openvesselphotos)); each photo keeps the open licence its author chose (CC BY, CC BY-SA, CC0, or public domain), given with it in the API | "Photo: {photographer} · {licence}" beside every photo, linked to the vessel's Open Vessel Photos page; "Open Vessel Photos" in Data attribution | | **AISStream.io** | Live vessels (AIS) | Free, beta, no formal ToS; AIS is a public broadcast | "AISStream.io" (courtesy) | | **CelesTrak** | Satellite TLEs (SGP4) and SATCAT records (object type, operational status, owner) that file each satellite under a class | US-government-origin data, no license; citation requested | "CelesTrak (celestrak.org), Dr. T.S. Kelso" | +| **NASA 3D Resources** (`public/models/iss.glb`) | The ISS drawn as a 3D model when the camera is near it (satellites layer): NASA/JSC IGOAL's "International Space Station (ISS) (D)" (https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/), reduced and re-rigged as `public/models/README.md` records. Its moving parts are computed by the app unless the telemetry relay in the next row is switched on: arrays and radiators from the Sun's position, the Ku-band dishes toward the TDRS fleet's nominal slots (41°W, 171°W, 85°E), the robotic arms as an illustrative sway | NASA media, not subject to copyright in the United States; NASA's Images and Media Usage Guidelines (https://www.nasa.gov/nasa-brand-center/images-and-media) ask that use not imply endorsement and that the insignia not be used; the model's textures carry the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks as flown on the station, kept to show it as it is, implying no endorsement by NASA or any partner | "ISS model: NASA 3D Resources" | +| **Project model** (`public/models/tiangong.glb`) | Tiangong drawn as a 3D model when the camera is near it (satellites layer): an original model of the station's T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward and nadir, a Tianzhou aft) made for God's Eye View from primitives with procedurally generated textures; dimensions from Wang, Zhang & Wang 2023, "Design and Application Prospect of China's Tiangong Space Station", Space: Science & Technology (https://doi.org/10.34133/space.0035, CC BY 4.0) and eoPortal's Tiangong page, the approximate parts listed in `public/models/README.md`. Its moving parts are computed by the app: the wings from the Sun's position, the high-gain antenna toward the Tianlian II nominal slots (79.9°E, 171.04°E, 10.5°E), the two arms as an illustrative sway; China publishes no live telemetry for the station | MIT, with the rest of the project's own work (`LICENSE`): an original asset with no third-party geometry, textures or images; the published dimensions are facts taken from a CC BY 4.0 paper and eoPortal | "Tiangong model: made for God's Eye View; dimensions from Wang, Zhang & Wang 2023 (CC BY 4.0) and eoPortal" | +| **NASA ISSLive telemetry** (`push.lightstreamer.com`, adapter set `ISSLIVE`) | **Off by default.** With `ISS_TELEMETRY_ENABLED=1` the server holds one connection to NASA's public ISS telemetry stream, open only while a browser has the ISS model on screen, and relays the latest joint angles at `/api/iss-telemetry`: the two alpha joints, the eight array beta joints, the two radiator joints and the Ku-band dish (Canadarm2's joints are relayed but not used yet). While the station has signal the ISS model takes those angles in place of the computed ones. The app stores nothing from it | The public subset of ISS telemetry NASA released as the ISSLive project, served for NASA by Lightstreamer. No terms of use are published for the feed, so it is opt-in and no request is made by default | "ISS joint telemetry: NASA ISSLive, via Lightstreamer" | +| **NASA ISS live streams on YouTube** (`youtube-nocookie.com/embed/ROboUHfPUrU`, `.../M3HKLzjvKPc`) | NASA's official live video from the ISS, two broadcasts ("Live High-Definition Views from the International Space Station" from the exterior cameras, and the live video with space-to-ground audio), offered in a LIVE section of Context, and on the Cockpit briefing's LIVE page, while the ISS is selected on the map, and played, muted, in YouTube's own embedded player only after the viewer presses Play; collapsing the section, closing Context or leaving the Cockpit page removes the player; the app stores nothing from it (`src/data/liveStreams.js`) | NASA video, not subject to copyright in the United States, distributed through YouTube under YouTube's Terms of Service, which permit embedding with the public embeddable player; the player API script loads from `www.youtube.com` and the video from the privacy-enhanced host `www.youtube-nocookie.com`, and the viewer's IP address reaches YouTube only once they press Play, under a line that says so | "NASA video, via YouTube", with a link to the stream's own page | | **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) | | **Esri World Imagery** (ArcGIS Online tile service) | The keyless satellite basemap — the default landing when no Google/ion credential is configured, and the "Esri Satellite" map stack | [Esri Master Agreement](https://www.esri.com/en-us/legal/terms/full-master-agreement): the public World Imagery service is usable in public-facing apps with attribution; no key is required for this classic endpoint, but Esri governs and can change access — an app at scale should review current ArcGIS Location Platform terms | "Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community" (provider carries the service's own credit line) | | **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" | diff --git a/SECURITY.md b/SECURITY.md index 4f55f80cdd..e1b7b7aeb7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -72,6 +72,8 @@ The data proxies under `server/providers/` are written so the browser cannot tur - **Live HLS is bounded and origin-pinned.** Registered HTTP(S) HLS sources use a Node puller that rejects redirects and off-origin playlist references, bounds playlists to 256 KiB and segment bodies to 8 MiB while streaming, and aborts timed-out or released sessions. At most two sessions retain 12 segments/24 MiB each, plus bounded download buffers. Stores are memory-only and idle sessions expire after 15 seconds. RTMP/ffmpeg execution is not enabled. Locally configured source URLs remain an operator trust boundary. - **Radio is not an audio relay.** `/api/radio/stations` contacts only allowlisted Radio Browser HTTPS hosts and paths, rejects redirects, rejects any hostname with a loopback/private/link-local/metadata/non-public A or AAAA result, and pins each TLS connection to a validated address. It returns normalized public HTTPS stream URLs; `/api/radio/click/:uuid` applies the same destination policy and accepts only station IDs from the current bounded catalog. The browser then connects directly to the broadcaster after an explicit playback action, so the broadcaster sees the listener's IP address. GEV never proxies, caches, records, or redistributes audio. - **Québec 511 video plays in the browser, opt-in and after Play.** With `CCTV_QUEBEC_VIDEO_ENABLED=1`, `/api/cctv/sources` lists, for each MTQ camera, one URL built server-side from its numeric id on `https://www.quebec511.info/Carte/Fenetres/camera.ashx`; the overlay accepts no other host, path or format. The browser loads that clip only after the viewer presses Play for the selected camera, so Québec 511 sees the viewer's IP address, and the panel says so before Play. Selecting a camera by click, auto-hop, a scene or voice never loads it, and switching cameras stops playback. GEV never proxies, caches or reads the video's pixels. With the flag unset (the default) the browser makes no request to Québec 511. +- **Station live video plays only after Play.** The LIVE section of Context and the Cockpit briefing's LIVE page load YouTube's player (the IFrame API from `www.youtube.com`, the video on `www.youtube-nocookie.com`) only after the viewer presses Play, under a line saying that YouTube sees their IP address. Selecting a station by click, a share link that follows it, a scene or voice shows the poster and loads nothing. The player goes when the section is collapsed, Context is closed or collapsed, the Cockpit leaves its LIVE page, the Cockpit is entered or left, or the selection moves to an object without that stream. GEV never proxies, caches or reads the video's pixels. +- **The ISS telemetry relay is opt-in, keyless and read-only.** With `ISS_TELEMETRY_ENABLED=1`, `/api/iss-telemetry` answers from one shared WebSocket the server opens to NASA's public ISSLive feed (`wss://push.lightstreamer.com`), only while a browser has asked in the last two minutes; every byte from the feed is parsed as untrusted text, a frame over 64 KB closes the socket (retried on the backoff ladder), and only the listed joint and clock items are kept. The route uses the keyless same-site checks and a per-client rate limit; with the flag unset (the default) it answers `{ configured: false }` and the server opens no socket. - **No verbatim client headers upstream.** The CCTV media route is the one route that relays a request header (`Range`, for video seeking). It is parsed and canonicalized before it is forwarded: one `bytes=` range only, with every accepted form — explicit span, open-ended and suffix — bounded to the same 64 MiB ceiling the relay applies to a declared response body. Multi-range, malformed, inverted and non-`bytes` values are dropped and the request proceeds without a `Range`, as RFC 7233 §3.1 prescribes. Bounding the request bounds what is asked for: a response that declares no length — live streamed media, or a chunked body from an upstream that ignores the `Range` — has no ceiling. An upstream request the browser has stopped waiting for is cancelled rather than left running, whether the viewer leaves before the headers arrive or during the body. - **The Data Library proxy fetches manifest upstreams only.** `/api/library/data/`, `/api/library/tile////` and `/api/library/index/` (a partitioned GeoParquet entry's file index, built from an S3 ListObjectsV2 listing and one ranged footer read per file, cached in memory for the entry's `cacheSeconds`) resolve the id against the validated manifests in `src/library/entries/`; the browser never supplies a URL, and every derived request must stay on the manifest's https host. Redirects are refused, dataset bodies are capped while streaming at the manifest's `maxBytes` (at most 32 MiB) and tiles at 2 MiB of `image/png`, `image/jpeg` or `image/webp`, responses are cached in memory only (at most 512 tiles), requests are rate-limited per client, and upstream error text is never returned. A keyed entry must be proxied; its key is read from this server's environment through the key registry and its routes refuse cross-site and forwarded requests like the other cost-bearing routes. Browser-direct entries are fetched by the browser with no cookies or referrer. - **Transit fetches registered feeds only.** `/api/transit/vehicles/` resolves the id against `src/data/transitFeeds.js`; the browser never supplies a URL, and a feed that is registered but disabled does not resolve at all. Redirects are followed manually and each hop is validated against the feed's own https origin before it is requested, so an off-origin or downgraded hop is refused rather than contacted. Bodies are capped at 8 MB, the protobuf is decoded server-side under entity-count and string-length ceilings, a differential feed is refused, and snapshots live 15 s in memory with no disk cache. A per-feed admission limiter and a failure cooldown ladder bound what this process can ask of any operator. diff --git a/build/vite.js b/build/vite.js index 883c0db62f..f0b06de3a0 100644 --- a/build/vite.js +++ b/build/vite.js @@ -55,7 +55,8 @@ function photonEndpointSetting(value) { * Content-Security-Policy for every document the dev/preview server serves. * No inline script is permitted, and the only foreign script origins are the * three that the Bhote Koshi event's embedded media needs (YouTube, Facebook - * and X), which frame-src matches for their players and posts. 'unsafe-eval' is + * and X), which frame-src matches for their players and posts; the stations' + * LIVE video uses the same YouTube player, after the viewer presses Play. 'unsafe-eval' is * required: Knockout (bundled inside @cesium/widgets) resolves the global * object with `(0, eval)("this")` at module load, and without it the Cesium * widget never initializes (verified in headless Chrome). It also covers @@ -66,9 +67,10 @@ function photonEndpointSetting(value) { */ export const BROWSER_CSP = [ "default-src 'self'", - // The Bhote Koshi event's embedded media: the YouTube player API, the - // Facebook video SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js); - // and the Maps JavaScript API that Street Level's Google Street View runs on. + // The Bhote Koshi event's embedded media: the YouTube player API (also the + // stations' LIVE video, src/data/youtubeLivePlayer.js), the Facebook video + // SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js); and the + // Maps JavaScript API that Street Level's Google Street View runs on. "script-src 'self' 'unsafe-eval' blob: https://www.youtube.com https://connect.facebook.net https://platform.twitter.com https://maps.googleapis.com", "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com", "font-src 'self' data: https://fonts.gstatic.com", diff --git a/changelog.d/1767-space-stations.md b/changelog.d/1767-space-stations.md new file mode 100644 index 0000000000..3a06aec2f7 --- /dev/null +++ b/changelog.d/1767-space-stations.md @@ -0,0 +1,42 @@ +- Draw the ISS as NASA's 3D model of the current station when the camera is + near it, its moving parts following computed rules: the solar arrays and + radiators by the Sun, the Ku-band dishes toward the relay satellites, the + robotic arms in an illustrative sway. The model draws through the renderer + contract, whose model items gain `nodes` for a model's moving joints + (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767). +- Draw China's Tiangong station as a 3D model up close, the second station + after the ISS: an original model of the T configuration with a Shenzhou + forward and nadir and a Tianzhou aft, its wings following the Sun, its + antenna aimed at the Tianlian relay satellites and its two arms swaying for + illustration (computed values; China publishes no telemetry). The model + stands in for the dots of the entries docked to it (Denis Groshev, @ZloyS, + #1767). +- Add a STATION section to Context while a space station is selected on the + map: Automatic says where the moving parts' angles come from, Manual offers + Sun positions, array and radiator folding as a labelled demonstration, dish + aim and the arms joint by joint, and Zoom brings the camera to the station. + Selecting a module or a docked vehicle offers it as selecting the station + does (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767). +- Let the ISS model's solar arrays, radiators and Ku-band dish take their + real angles from NASA's public ISSLive telemetry. Off by default: set + `ISS_TELEMETRY_ENABLED=1` and the server relays the feed over one + connection, open only while the model is on screen; without signal the + joints keep their computed rules (Denis Groshev, @ZloyS; Kevin Rajan, + @kvnloo, #1767). +- Add a LIVE section to Context while the ISS is selected: NASA's two live + streams (exterior cameras; live video with space-to-ground audio), stepped + with arrows, in YouTube's embedded player. Nothing loads until you press + Play, under a line saying YouTube sees your IP address, and collapsing the + section stops it. In the Cockpit the same stream is the briefing's fourth + page, LIVE (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767). +- Ride a space station in the Cockpit from views on its model instead of + the straight-down picture: Nauka, Zarya, Poisk, the Cupola, Kibo and a + docked vehicle on the ISS; Tianhe, Wentian, Mengtian and a docked vehicle + on Tiangong. Two arrows step through them, the readout describes the module + each view is from, and leaving selects the station (Denis Groshev, @ZloyS, + #1767). +- Let a click on a mapped installation's label box select the site, as a + click on its 7 px dot does: from orbit the label is what a click lands on. + The label takes a click only where nothing else is drawn under it, so an + aircraft or vessel under a base's label stays selectable (Denis Groshev, + @ZloyS, #1767). diff --git a/dev/conformance/main.js b/dev/conformance/main.js index a1fb6c48a2..c2762dddd8 100644 --- a/dev/conformance/main.js +++ b/dev/conformance/main.js @@ -31,6 +31,8 @@ const ctx = { toEcef, assets: { model: '/models/fleet/aircraft/c172.glb', + // Its one node, which the `nodes` check moves. + modelNode: 'c172', // Not served: the model failure check loads it. missingModel: '/models/conformance-missing.glb', }, @@ -47,6 +49,7 @@ const HARNESSES = { cesium: () => [ createCesiumHarness({ model: ctx.assets.model, + modelNode: ctx.assets.modelNode, missingModel: ctx.assets.missingModel, }), { only: (id) => CESIUM_CHECKS.has(id) }, diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f3e9317952..ce83af7497 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2111,6 +2111,213 @@ tracked satellite's dot a set of its own drawn where the follow camera framed it, and the orbit rings a line set dimmed behind the globe and turned with the Earth each second. A caller handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. + +The ISS (NORAD 25544, by number, not name) is drawn as NASA's 3D model within +1,500 km of the camera and as its dot beyond; the two split the distance range, +so exactly one draws (the tracked dot too). The model is at its real 109 m span +with a 72 px floor, flies the station's usual attitude (modules along the +velocity, the same side to the Earth) from its own per-frame SGP4 sample, sits +on the follow camera's sample while tracked, loads only once the ISS is shown, +and hides with the dot's own rules. A click on it tracks the ISS. +The station has several catalog entries that are one body: the ISS itself +(listed as ISS (ZARYA)), ISS (NAUKA) and whatever vehicle is docked, each with +a dot of its own, so a click on the station's dot can land on any of them. +`issTrackedOnStation` (`policy.js`) treats a tracked entry as the station when +it is the ISS or the ISS shares its position (`_dockedCompanions`). For such +an entry the model sits on the tracked entry's own per-frame sample, as it +does for the ISS (drawn from a later sample it stood a frame of orbital +motion, over 100 m, off the camera's centre); its tracked dot and orbit ring +leave the near range to the model, its card keeps clear of the model, and the +command panel and the live video show as they do for the ISS. Such an entry +draws no orbit ring of its own (its elements would put a second line beside +the ISS's through the same station): when tracking judges it docked (both +orbits at one instant within 5 km) the ISS's ring shows for it, even with the +Stations class hidden. +In the Cockpit, a station entry is ridden from the station itself instead of +the straight-down picture: the camera sits at a point on the model +(`issMounts.js`), with the model drawn, and looks out, away from the station. +There are six views, the same whichever entry was selected: from Nauka (the +one it opens on; its lower end, out ahead to port), from Zarya (its port +side, out across the track), from Poisk (its top, out behind to starboard), +from the Cupola (just below it, out aft past the Russian segment), from Kibo +(outside the two windows on its port end, out over the Exposed Facility; +the port solar arrays turn through it as they follow the Sun, as they do past +the real windows) +and, while a vehicle is docked, from that vehicle (behind Zvezda's aft port, +out behind the station; the catalog does not say which port a vehicle is +on). The Cupola and Kibo have no catalog entries: their views ride the ISS's +and show cards of their own (`ISS_MOUNT_CARDS`: the Cupola as ESA's +observation module with 7 windows, launched 8 Feb 2010 on STS-130, on +Tranquility's Earth-facing port; Kibo as JAXA's laboratory module with 2 +windows, launched 31 May 2008 on STS-124, on Harmony's port side) in place of +the entry's NORAD number, owner and TLE; altitude, velocity and the +sub-satellite point stay the station's. +Each looks 20° to 30° below level, which keeps the Earth's limb in the frame. +The points were chosen by casting rays across the view against the model at +rest: over a meter clear of every surface, at most a tenth of the frame +meeting the station and none of it nearer than 12 m. The satellites layer's +`getCockpitMount(key)` gives the eye point, the view frame, the view shown, +the catalog entry it belongs to (ISS (NAUKA), the ISS itself for Zarya, +POISK, the docked vehicle) and the views on offer, worked out from the same +sample the model is then placed on, so the camera stays on the model. The +Cockpit rides the view's own entry (`switchOrbitalSatellite`, as riding +another satellite from Live Signals), so the readout, the TLE and the signals +describe the module the view is from; a view whose entry is missing or cannot +be tracked keeps the entry ridden, and is not retried until the view changes. +Leaving the Cockpit from a station view selects Nauka (when the catalog has +it) and puts the follow camera on it, whichever view it ended on; leaving +any other satellite's view refocuses that satellite as before. `cockpitOrbitalView.js` puts the +camera there, turns the arrow-key look about the view's own frame, keeps the +chosen view for the session (also while the model is away) and publishes its +name (`mount`) and the number on offer (`mountViews`). The HUD shows STATION +VIEW with the view's name between two arrows that step back and forth +through them, wrapping round, +and leaves out the nadir reticle, north pointer, swath and sensor strip. A +ground focus (a click on a mapped installation, or its Live Signals row) +works from a station view as from the nadir picture: it aims from the +view's camera point and turns about the view's own frame, with the same +±45° reach, so the sites listed and focusable are those within reach of +where the view looks; their rows still give the angle from straight down. +Switching views ends a focus. +Until the model has loaded, or with the model not shown, the entry keeps the +nadir picture, and the TRACK ACQUIRED line follows the change. Zoom, the +place line and the identity readouts are unchanged. +While the station is selected on the map, Context gains a LIVE section +(`src/ui/liveControls.js`, `LivePanel.vue`, the `gev-live` store): the live +streams attached to the selected object. The list is fixed +(`src/data/liveStreams.js`: NASA's exterior cameras, and its live video with +space-to-ground audio, both on YouTube) and each stream names the subject +keys it belongs to; a layer names its selected subject's keys with +`getLiveSubjectKeys` (the satellites layer answers `station:iss` for the ISS, +Nauka and a docked vehicle, and `station:tiangong` for Tiangong's entries, +which no stream is listed for yet), and the keys are read again every 2 s while +something is selected, since a docked entry is judged so only once both +orbits have been compared. The section shows the subject, the stream's name +with two arrows when there are several, a screen and a status line. It +starts collapsed, and nothing loads on selection: the screen is a poster +with Play, under the line "Video plays from YouTube, which sees your IP +address." Play is the one thing that loads the player: +`youtubeLivePlayer.js` builds YouTube's player (the IFrame API from +`www.youtube.com`, the video on `www.youtube-nocookie.com`), muted, and reads +its state back. Collapsing the section, collapsing or closing Context, or the +section leaving the page removes the player, so nothing plays unseen. ON AIR +with a blinking red dot while it plays; LOADING with an amber dot while it +starts; an offline card ("Stream is offline", with Try again) when +the player reports the video ended, errored or did not start within 25 s, +which is how an off-air broadcast shows, or when YouTube's player API does not +load (Try again loads it afresh); "This stream cannot play here" when the +owner refuses embedding. Stepping to another +stream hands a playing one over; a selection that moves to an object +without that stream, clearing it or turning the layer off removes the +player, while another entry of the same station (a module, a docked vehicle, +the Cockpit stepping between views) keeps it. In the Cockpit the rail is hidden, so the +briefing card gains a fourth page, LIVE (SIG / NEWS / LOCAL / LIVE, +`CockpitLivePage.vue`), with the same subject line, arrows, screen, states +and credit, and the same poster with Play under the IP line; it is offered +only while the ridden subject has a stream, and with none the briefing keeps +its three pages. There is one player: entering or leaving the Cockpit +removes it (an embedded player cannot change parents without reloading, and +the view it was in is hidden), and so does leaving the LIVE page; the view +now shown offers Play again. Previous, Next and the tabs reach the LIVE page; +the automatic 9-second cycle never turns to it and waits while it is shown. +The credit links the owner and the stream's own page. +The model is NASA/JSC IGOAL's current-configuration station, reduced to 3 MB +with its joints kept as nodes (`public/models/README.md`), fetched only once +the camera nears its range, and drawn as an item of a `models` set of the +renderer's draw port, its joints posed through the item's `nodes`. +`issArticulation.js` turns them every frame, by default from computation: the two alpha joints and eight beta joints face +the arrays to the Sun (feathered along the flight direction in the Earth's +shadow, taken as a cylinder), the two radiator joints keep the radiators +edge-on to it, the two Ku-band dishes aim at the highest TDRS nominal slots +(41°W, 171°W, 85°E) above the station's horizon plane, and Canadarm2, Dextre's +arms and the Japanese arm sway a few degrees about NASA's filed pose, which is +illustrative only (no public source gives their real pose; the European arm has +no joints in the file). Joints turn at most 12°/s of wall time. Docked objects +are found by comparing both orbits at one instant, since dots are moved at +different moments. Selecting the station on the map also gives Context a +STATION section (`stationPanel.js` presents it through the `gev-station` +store; `StationPanel.vue` renders it; `issStation.js` describes the ISS, and +another station plugs in with a description of its own): the station's badge +and the selected entry's name, **Automatic** / **Manual**, a status line, and +**Zoom to the ISS** (offered beyond 1 km while the viewer's follow camera is +on the station's entity; it shortens the camera's offset from the station, +a step per frame, to 260 m, and never moves along the view direction, which +ran away when the camera was not looking at the station). +Automatic (the default) leaves the joints to their rules and says where the +angles come from: "Telemetry · updated 4 s ago" with a green dot while the +relay's answer is fresh, "No signal since 12:04 · computed values" when the +feed lost the station, "Telemetry unavailable · last update 3 min ago · +computed values" when the relay cannot be reached, "Telemetry not enabled on +this server · computed values" when it is switched off, and a lit/shadow +line. Manual pauses telemetry ("Manual · telemetry paused") and offers the +controls: replace the Sun with a chosen position or a 40 s orbit, fold the +arrays and radiators as a labelled demonstration, aim the dishes and pose +Canadarm2 by joint. Automatic, a new selection, the Cockpit (the rail is +hidden there, and the section with it) or turning the layer off hand every +joint back. `issCommand.js` keeps the rules these share (the zoom's range and +step, the fast orbit, the status wording). +With `ISS_TELEMETRY_ENABLED=1` (off by default: the feed publishes no terms) +`server/providers/space/issTelemetry.js` relays NASA's public ISSLive telemetry +at `/api/iss-telemetry`. It speaks Lightstreamer's text protocol over `ws`, +holds one connection for the whole server, opens it on the first request, +closes it after two minutes without one, retries on a 5 s to 5 min ladder and +recycles a socket that is silent for 30 s. The body is +`{ configured, status, generatedAt, items }`: `status` is `live` only while the +station clock ticked with signal in the last 20 s, and each item is +`[value, epoch ms it was true at]`. On a socket loss the relay discards that +connection's joint samples and station-clock credit, so fresh signal after +reconnection cannot present old angles as live telemetry. Unset, the route answers +`{ configured: false }` without contacting the feed, and the browser asks once. +`issTelemetry.js` in the satellites layer polls it every 5 s while the model is +drawn and, in Automatic, replaces the computed targets with the feed's: each +alpha joint its own angle (port `+`, starboard `-`), each beta joint +`±angle + 90°`, each radiator joint its angle, and the first dish the direction +its elevation and cross-elevation give (the second holds still: the feed +reports one dish and not which). The mapping was fitted on a recording of the +feed: the dish direction stayed within 0.3° of a TDRS satellite across a +hand-over, and the arrays sat 5° to 9° off the Sun; the radiator joints did not +move in the recording, so their sign is not fitted. With no relay, no signal, +an answer older than 20 s, Manual, or a Sun chosen by hand, the joints keep the +computed rules, and the STATION section's status line and note say which +holds. The arms still sway for illustration. +Tiangong is the second station, drawn the same way: `stationModel.js` is the +station-independent model part (load on approach, placement from its own SGP4 +sample or the tracked entry's, dot and companion hand-over, ring hidden up +close, card anchor and clearance), driven by a spec; `issModel.js` gives the +ISS's and `tiangongModel.js` Tiangong's (`CSS (TIANHE)`, NORAD 48274, with +`CSS (WENTIAN)`, `CSS (MENGTIAN)` and the Shenzhou and Tianzhou ships as its +docked entries). `policy.js` lists both stations (`STATIONS`) and +`stationModels.js` says which station a tracked entry belongs to, so the card, +the detection marks, the LIVE keys, the Cockpit's mounts and the STATION +section work per station rather than for the ISS alone (tracking records +`_trackedDockedToStation`; the ISS's ring keeps its own rules). The model +(`public/models/tiangong.glb`, 382 KB, 26 k triangles) is the project's own, +built from primitives with procedural textures, in meters and in the ISS +file's frame, so it takes the ISS's flight-axes mapping: the station is +assumed to fly with Tianhe along the velocity, the node forward, the labs +across the orbit and nadir to the Earth. `tiangongJoints.js` carries the +file's 37 joint and dock nodes (pivot, axis, kind) and +`tiangongArticulation.js` drives them, all computed, since China publishes no +telemetry: Tianhe's and the ships' one-axis wings turn about their booms to +face the Sun, the lab wings turn about the lab's axis then their own (the +SARJ/BGA pair), in the Earth's shadow every wing turns flat to the Earth +(edge into the flight direction), the high-gain antenna aims at the highest +Tianlian II nominal slot (79.9°E, 171.04°E, 10.5°E) above the horizon plane, +and the two arms sway a few degrees on one side of their folded pose (so they +lift off the hull), at the ISS's 12°/s cap. The STATION section for Tiangong +(`tiangongStation.js`) says "No public telemetry · computed values", offers +the Sun positions and the fast orbit, every wing on a slider of its own +(Tianhe's two; the labs' four, alpha and beta each: a wing set by hand holds +its angle, reached at the joint rate, while the rest keep following the Sun, +and "Follow the Sun" frees them), and the Tianhe and Wentian arms by joint; +**Zoom to Tiangong** uses the ISS's zoom range. In the Cockpit, Tiangong is +ridden from views on its model (`tiangongMounts.js`), as the ISS is: from +Tianhe (the one it opens on; its port side, out across the track), from the +outer end of Wentian and of Mengtian (out past their wings, which turn through +the view as they follow the Sun) and from the docked vehicle (standing in on +the aft port, looking behind the station); each rides its own catalog entry, +so no cards are needed, and leaving selects Tianhe. The visiting ships are +always drawn; they are not yet toggled by what the catalog shows docked. The mission factory separates paths, replay, camera, panel, overlays and placement. Its markers, lines, live rings and pad zone are renderer draw sets, and it follows a mission through the camera port, so a caller handing it a Cesium @@ -2834,9 +3041,16 @@ frame the arrows tilt, so the site stays at the centre as the satellite moves. The turn onto it (and between sites) eases what is left of the swing with the arrows' easing on a slower clock (250 ms time constant, about 0.75 s to 95%), then holds the site exactly, and cuts under -`prefers-reduced-motion`. A single click on a site's marker focuses it too: -the pick is resolved through the layer's own pick ids (`findByPick`: a named -marker's `{ installationId }` or a site entity). A click anywhere else +`prefers-reduced-motion`. A single click on a site's marker, or on the label +box the overlay paints for it, focuses it too: the click is resolved through +the layer's own lookup (`findAt`: `scene.pick` for a named marker's +`{ installationId }` or a site entity, else the box the overlay painted for +the label; from orbit the dot is 7 px, so the label is what a click lands +on). The map's own click selection reads the label the same way, through a +click claim (`registerClickClaim`) rather than as an interactive card: the +label takes a click only where nothing another layer draws is under it, so +an aircraft or vessel drawn under a base's label stays selectable, and +another layer's card painted over the label keeps its click. A click anywhere else (a site beyond the reach included), the focused site's row, NADIR, Home or `0` ends the focus and the view eases back to nadir on the same clock; an arrow ends it (or the ease back) and @@ -8861,7 +9075,7 @@ apply to `public/` assets or built-preview serving. The ship bridge and the orbital view have their own own-layer gates (`bridgeEntryAllowed`, `orbitEntryAllowed`; see [Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)). -- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered with nothing recent; and `REGIONAL NEWS UNAVAILABLE` when there is no place or no source answered, which clears the list only when there was nothing to keep. The footer follows that state across page changes. These are compact text states rather than an empty media frame; partial local data remains explicit. Article links open their original publisher, and no headline is treated as verified risk intelligence. On desktop both cockpit rails use the same width and share a bottom-aligned safe baseline in opposite corners above the peripheral MGRS/GSD/time telemetry, leaving both that text and the lower-center instrument cluster readable. They collapse independently to slim tabs without stopping live data updates. Narrow screens use separated top/bottom fallbacks. Empty-space globe clicks are inert while cockpit owns the camera; `Escape` or `EXIT COCKPIT` explicitly exits and restores the same tracked entity and standard follow camera. Unknown feeds remain unknown, selection loss still exits safely without inventing a replacement track, and the cockpit never presents the summary as threat scoring or an all-clear. This is a desktop first-person presentation, not a WebXR session. +- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a **cockpit briefing carousel** of three pages: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo; a fourth page, LIVE, is offered while the ridden subject has a live stream (the ISS; see the LIVE section) and shows the same muted player. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus, never turns to the LIVE page and waits while it is shown, and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered with nothing recent; and `REGIONAL NEWS UNAVAILABLE` when there is no place or no source answered, which clears the list only when there was nothing to keep. The footer follows that state across page changes. These are compact text states rather than an empty media frame; partial local data remains explicit. Article links open their original publisher, and no headline is treated as verified risk intelligence. On desktop both cockpit rails use the same width and share a bottom-aligned safe baseline in opposite corners above the peripheral MGRS/GSD/time telemetry, leaving both that text and the lower-center instrument cluster readable. They collapse independently to slim tabs without stopping live data updates. Narrow screens use separated top/bottom fallbacks. Empty-space globe clicks are inert while cockpit owns the camera; `Escape` or `EXIT COCKPIT` explicitly exits and restores the same tracked entity and standard follow camera. Unknown feeds remain unknown, selection loss still exits safely without inventing a replacement track, and the cockpit never presents the summary as threat scoring or an all-clear. This is a desktop first-person presentation, not a WebXR session. - **Cockpit left-panel clearance:** the Cockpit Contact card and peripheral HUD participate in the adaptive left accordion's live obstacle measurements, including live viewport-height changes. Expanding Layers or Authoring keeps the active panel in the available upper-left corridor with internal scrolling; it does not cover the Contact card, lower Cockpit controls, or Cesium credit line. Outside Cockpit the hidden card does not alter the normal corridor. - **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey. - **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged. @@ -8872,7 +9086,7 @@ apply to `public/` assets or built-preview serving. - **Cockpit weather status:** the earlier multi-canvas atmospheric compositor remains fail-closed and is not attached to the live viewer. Cockpit clouds are a separate transparent WebGL pass with a capped 520×320 framebuffer, 24 ray steps, three FBM octaves, and a 12 FPS ceiling. It defaults off and starts only when local storage explicitly contains the persisted `WX ON` opt-in (`'1'`). When opted in, observations refresh after five minutes or 25 km of aircraft movement, fail transparent when unavailable or clear, and stop on exit or disable. `WX OFF` governs atmospheric rendering only: the briefing still fetches source-backed Natural Earth region, headline, and Open-Meteo local-information data, aborting and replacing any in-flight request when the selected aircraft changes. No weather effect runs in map mode and no synthetic fallback is shown. - **Cockpit trail visibility:** entering cockpit hides the selected aircraft's trail body and head so they cannot cross the first-person view; exit restores them. This cockpit-only presentation change does not alter the normal map-mode invariant that aircraft trails render through terrain using their depth-fail material. - **Aircraft course slew:** civilian and military 3D models retain the 60°/s course limiter, but each rendered frame can consume at most 250 ms of accumulated slew time. A long tile/render stall therefore catches up over multiple visible frames instead of turning one delayed frame into a heading snap. -- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode. Live signal data continues refreshing in either state. +- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel (plus LIVE while the ridden subject has a stream) does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode, and which never turns to the LIVE page. Live signal data continues refreshing in either state. - **Photoreal horizon blend:** Cesium's sky atmosphere remains enabled behind the hidden base globe, but its light intensity, saturation, and brightness are reduced from the library defaults so the distant Google Photorealistic 3D Tiles boundary blends into the sky instead of producing a bright cyan horizon seam. - **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter. - Voice control UI (`#gev-voice-control`) shows status states OFF / CONNECTING / LISTENING / EXECUTING / ERROR. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 99f41b8c3c..7c3d08695b 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -343,6 +343,17 @@ correction turns them to, paints the mask in a custom shader per colour clipping plane through the model's origin. The checks `draw.models.bytes` and `draw.models.fleet` cover them. +An articulated model's joints are its item's `nodes`: transforms of the +model's named glTF nodes, each a column-major 4×4 matrix in the node's +parent frame that replaces the node's own (the ISS's solar arrays, +radiators, dishes and arms). They change live; a node whose name leaves the +map goes back to its authored pose, and names the model lacks are ignored. +A renderer that poses nodes lists `modelNodes`; one without it draws the +model as authored. The Cesium port lists it, and writes each node's matrix +once the model is ready, and again only when its numbers change. The check +`draw.models.nodes` moves the harness model's node off the screen's centre +and back. + The Cesium port draws timed imagery (`imageryFrames`): a layer given a timed source hides its own imagery and draws each frame its clock shows as a Cesium imagery layer just above it (in `blend` mode the later frame over the earlier diff --git a/public/models/README.md b/public/models/README.md index 3f97820d37..ce51d12f83 100644 --- a/public/models/README.md +++ b/public/models/README.md @@ -1,11 +1,13 @@ # Bundled 3D Models -Every 3D model shipped in this directory is one of the project's procedural +Every 3D model shipped in this directory but two is one of the project's procedural fleet models under [`fleet/`](fleet/): aircraft, helicopters, ships, buoys, transit and rail vehicles, and a few other airborne and ground objects. They are generated from code by the project maintainers, contain no third-party artwork, and are covered by the repository's [MIT license](../../LICENSE) -like the source code. +like the source code. The exceptions are the two space stations: NASA's model +of the ISS, described in [its own section](#the-iss-model-issglb) below, and +the project's own Tiangong model, [after it](#the-tiangong-model-tiangongglb). | Path | What it holds | |---|---| @@ -37,3 +39,78 @@ How the layers use them: `src/data/fleetModels.js` reads the set and chooses each vehicle's model; `src/data/fleetModels.test.mjs` checks that every model `types.json` names is in the catalog and on disk, and that no GLB exceeds 3 MB. + +## The ISS model (`iss.glb`) + +Two models sit outside the fleet set. The first is `iss.glb`, the International +Space Station drawn by the satellites layer up close. It is not procedural and not +covered by the MIT license. It is NASA's own model of the station, which is +not subject to copyright in the United States +([NASA Images and Media Usage Guidelines](https://www.nasa.gov/nasa-brand-center/images-and-media)); +its use does not imply endorsement by NASA. It loads only when the camera +nears the station. + +- **Original work:** “International Space Station (ISS) (D) (IGOAL)”, NASA + Johnson Space Center, Integrated Graphics, Operations and Analysis + Laboratory, on + [NASA 3D Resources](https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/). +- **Reduction:** from the 96 MB original (2.7 M triangles) to 3 MB (314 k + triangles): handrails left out; geometry simplified within 15 cm + (structure) or 40 cm (small details) of the original surface, normals + rebuilt; normal maps dropped; textures resized to 512 px WebP; + Draco-compressed. +- **Frame:** every part is baked into one frame in meters (glTF +Y zenith, + +X port, +Z forward), and the scene root moves the bounding-box centre to + the origin. +- **Corrections:** NASA's file is a mirror image of the station (port and + starboard swapped), which is undone; 15 materials NASA marks as blended + are made opaque, because blended they draw see-through. +- **Marks on the textures:** the station's textures carry the marks it flies + with: the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks on + the partners' modules. They are kept as flown, to show the station as it + is; their presence implies no endorsement by NASA or by any partner. +- **Moving parts:** parts that move stay separate nodes at the joints NASA + names (two alpha joints, eight array beta joints, two radiator joints, + Canadarm2's seven joints, two joints on each Dextre arm, three on the + Japanese arm). The two Ku-band dishes and three of the four power-module + radiators, welded into the truss in NASA's file, are cut out by position. + +## The Tiangong model (`tiangong.glb`) + +The second model outside the fleet set is `tiangong.glb`, China's Tiangong +station in its T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward +and nadir, a Tianzhou aft), drawn by the satellites layer up close. It is an +original model made for God's Eye View and, unlike the ISS model, it is the +project's own work under the repository's [MIT license](../../LICENSE): no +third-party geometry, texture or image is in it. It loads only when the camera +nears the station. + +- **Built:** in Blender 5.3 from primitives only (cylinders, cones, spheres, + tori, boxes), every texture generated procedurally by the build script, + [`scripts/build-tiangong-model.py`](../../scripts/build-tiangong-model.py) + (`blender -b --python scripts/build-tiangong-model.py -- `). + 26,460 triangles, 12 materials, 15 WebP textures (`EXT_texture_webp`), + Draco-compressed, 382 KB. +- **Dimensions, as published:** Wang, Zhang & Wang 2023, "Design and + Application Prospect of China's Tiangong Space Station", *Space: Science & + Technology*, [doi:10.34133/space.0035](https://doi.org/10.34133/space.0035) + (CC BY 4.0), and [eoPortal's Tiangong page](https://www.eoportal.org/satellite-missions/tiangong): + Tianhe 16.6 m × 4.2 m with its port layout; Wentian and Mengtian 17.9 m × + 4.2 m, one each side of the node; lab wings 27 × ~4 m, two per lab, + two-axis; Tianhe wings 12.6 m per wing (the paper's figure; eoPortal gives + a 60 m total span), one-axis; the Tianhe arm ~10 m and the Wentian arm + ~5 m, seven joints each; Shenzhou 9.25 × 2.8 m (17 m span), Tianzhou + 10.6 × 3.35 m (14.9 m span) and their docking ports. +- **Approximate (the author's estimates):** the node sphere, small-cylinder + and resource-section diameters, section lengths and cones, hatch and port + tubes; wing widths, root offsets, masts and drive housings; the airlocks, + radiators, high-gain antenna and node antennas; both arms entirely (bases, + booms, joint spacing, rest pose); the ships' module proportions and arrays. +- **Frame:** meters, glTF +X port, +Y zenith, +Z forward (the ISS file's); + the scene root `tiangong` is translated so the station's bounding-box + centre (without the ships) is at the origin. +- **Moving parts:** joints are nodes with identity rest transforms and the + pivot, axis, kind and range in their `extras` (also in + `src/layers/satellites/tiangongJoints.js`): two Tianhe wing drives, four + lab wing alpha + beta pairs, the antenna gimbal, seven joints per arm, two + drives per ship, six dock markers. diff --git a/public/models/iss.glb b/public/models/iss.glb new file mode 100644 index 0000000000..5f58223afb Binary files /dev/null and b/public/models/iss.glb differ diff --git a/public/models/tiangong.glb b/public/models/tiangong.glb new file mode 100644 index 0000000000..6a28fdb85f Binary files /dev/null and b/public/models/tiangong.glb differ diff --git a/scripts/build-tiangong-model.py b/scripts/build-tiangong-model.py new file mode 100644 index 0000000000..17c5468213 --- /dev/null +++ b/scripts/build-tiangong-model.py @@ -0,0 +1,1401 @@ +"""Build an original, articulation-ready Tiangong (T-configuration) model in Blender and export it as GLB. + +Run headless with Blender 5.3, from the repository root: + blender -b --python scripts/build-tiangong-model.py -- [out_dir] +out_dir defaults to tiangong-model/ under the system's temporary directory; copy +tiangong.glb from there to public/models/. + +Every dimension below is written in the *scene frame of the exported glTF* (metres): + +X = port (left when looking forward), +Y = zenith (away from Earth), +Z = forward (direction of flight). +Blender is Z-up; the glTF exporter (export_yup=True) maps Blender +Z -> glTF +Y and Blender +Y -> glTF -Z, +so a glTF point (x, y, z) is built in Blender at (x, -z, y). The helper B() does that conversion and +nothing else in this file thinks in Blender axes. + +All geometry is made from Blender primitives here; nothing is imported. All textures are generated +procedurally with numpy (see TEXTURES below), written as PNG to textures/ and re-encoded to WebP by the +exporter. No third-party image, model, insignia or lettering is used. +""" +import json +import math +import os +import struct +import sys +import tempfile + +import bpy +import numpy as np +from mathutils import Vector + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_ARGS = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] +HERE = os.path.abspath(_ARGS[0]) if _ARGS else os.path.join(tempfile.gettempdir(), "tiangong-model") +os.makedirs(HERE, exist_ok=True) +GLB = os.path.join(HERE, "tiangong.glb") +BLEND = os.path.join(HERE, "tiangong.blend") +JOINTS_JSON = os.path.join(HERE, "joints.json") +STATS_JSON = os.path.join(HERE, "build_stats.json") +TEX_DIR = os.path.join(HERE, "textures") +ISS_REFERENCE = os.path.join(ROOT, "public", "models", "iss.glb") # read only, for preview_iss_reference.png +PREVIEW_SAMPLES = 48 + + +def log(*a): + print("[tiangong]", *a) + sys.stdout.flush() + + +# --------------------------------------------------------------------------------------- frame helpers +def B(v): + """glTF scene coords (x port, y zenith, z forward) -> Blender coords (Z-up).""" + return Vector((v[0], -v[2], v[1])) + + +def Bsize(s): + """Box dimensions glTF (sx, sy, sz) -> Blender (sx, sz, sy).""" + return (abs(s[0]), abs(s[2]), abs(s[1])) + + +def V(*a): + return Vector(a) + + +def unit(v): + v = Vector(v) + return list(round(c, 6) for c in v.normalized()) + + +# --------------------------------------------------------------------------------------- scene reset +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.unit_settings.system = "METRIC" +scene.unit_settings.scale_length = 1.0 + +coll = bpy.data.collections.new("Tiangong") +scene.collection.children.link(coll) +layer_coll = bpy.context.view_layer.layer_collection.children[coll.name] +bpy.context.view_layer.active_layer_collection = layer_coll + +# ======================================================================================= TEXTURES +# All maps are square, tileable, and drawn in display (sRGB) values 0..1 straight into byte images. +# metallicRoughness maps follow glTF: R unused (1), G = roughness, B = metallic. +os.makedirs(TEX_DIR, exist_ok=True) +TEX_FILES = {} + + +def fbm(n, octaves=5, base=4, seed=0, persistence=0.5): + """Periodic value noise in [0,1], n x n, tileable.""" + rng = np.random.default_rng(seed) + out = np.zeros((n, n), np.float32) + amp, total, freq = 1.0, 0.0, base + for _ in range(octaves): + g = rng.random((freq, freq)).astype(np.float32) + t = np.arange(n) * freq / n + i0 = np.floor(t).astype(int) % freq + i1 = (i0 + 1) % freq + f = (t - np.floor(t)).astype(np.float32) + s = f * f * (3 - 2 * f) + a, b, c, d = g[i0][:, i0], g[i0][:, i1], g[i1][:, i0], g[i1][:, i1] + v = (a * (1 - s)[None, :] + b * s[None, :]) * (1 - s)[:, None] + (c * (1 - s)[None, :] + d * s[None, :]) * s[:, None] + out += amp * v + total += amp + amp *= persistence + freq *= 2 + return out / total + + +def wrap_idx(n, pos, w): + return (int(round(pos)) + np.arange(-(w // 2), w - w // 2)) % n + + +def hline(img, y, w, col, alpha=1.0, x0=0, x1=None): + """Horizontal line at pixel row y (wraps), width w, over columns x0..x1.""" + n = img.shape[0] + x1 = n if x1 is None else x1 + rows = wrap_idx(n, y, w) + img[rows[:, None], np.arange(x0, x1)[None, :]] = img[rows[:, None], np.arange(x0, x1)[None, :]] * (1 - alpha) + np.asarray(col, np.float32) * alpha + + +def vline(img, x, w, col, alpha=1.0, y0=0, y1=None): + n = img.shape[0] + y1 = n if y1 is None else y1 + cols = wrap_idx(n, x, w) + img[np.arange(y0, y1)[:, None], cols[None, :]] = img[np.arange(y0, y1)[:, None], cols[None, :]] * (1 - alpha) + np.asarray(col, np.float32) * alpha + + +def rect(img, x0, y0, x1, y1, col, alpha=1.0): + img[y0:y1, x0:x1] = img[y0:y1, x0:x1] * (1 - alpha) + np.asarray(col, np.float32) * alpha + + +def disc(img, cx, cy, r, col, alpha=1.0): + n = img.shape[0] + yy, xx = np.mgrid[0:n, 0:n] + m = ((xx - cx) ** 2 + (yy - cy) ** 2) <= r * r + img[m] = img[m] * (1 - alpha) + np.asarray(col, np.float32) * alpha + + +def solid(n, col): + return np.ones((n, n, 3), np.float32) * np.asarray(col, np.float32) + + +def save_tex(name, arr, noncolor=False): + """Write an (n, n, 3) float array as PNG and return the Blender image.""" + n = arr.shape[0] + rgba = np.ones((n, n, 4), np.float32) + rgba[..., :3] = np.clip(arr, 0, 1) + img = bpy.data.images.new(name, n, n, alpha=True) + if noncolor: + img.colorspace_settings.name = "Non-Color" + img.pixels.foreach_set(rgba.ravel()) + path = os.path.join(TEX_DIR, name + ".png") + img.filepath_raw = path + img.file_format = "PNG" + img.save() + TEX_FILES[name] = os.path.getsize(path) + return img + + +def tex_hull(n=512, tile=4.0, seed=1): + """Off-white thermal blankets: 1 m panel seams, quilting, patches, vents, handrail rows. tile = metres per repeat.""" + ppm = n / tile + base = np.asarray((0.82, 0.82, 0.80), np.float32) + lum = 1.0 + 0.05 * (fbm(n, 4, 4, seed) - 0.5) + 0.03 * (fbm(n, 2, 32, seed + 1) - 0.5) + d = solid(n, base) * lum[..., None] + mr = solid(n, (1.0, 0.56, 0.03)) + mr[..., 1] += 0.08 * (fbm(n, 3, 8, seed + 2) - 0.5) + q = int(ppm * 0.25) + for k in range(int(tile / 0.25)): # quilting + hline(d, k * q, 1, (0.7, 0.7, 0.68), 0.25) + vline(d, k * q, 1, (0.7, 0.7, 0.68), 0.25) + for k in range(int(tile)): # panel seams every metre + p = int(k * ppm) + hline(d, p, 2, (0.56, 0.56, 0.55), 0.9) + vline(d, p, 2, (0.56, 0.56, 0.55), 0.9) + hline(d, p + 2, 1, (0.9, 0.9, 0.88), 0.5) + vline(d, p + 2, 1, (0.9, 0.9, 0.88), 0.5) + hline(mr, p, 2, (1.0, 0.68, 0.0)) + vline(mr, p, 2, (1.0, 0.68, 0.0)) + # radiator-like dark strips, equipment plates, vents (metres within the tile; nothing crosses the border) + def m(x): + return int(x * ppm) + for (x0, y0, x1, y1) in ((0.35, 0.2, 1.75, 0.58), (2.3, 2.3, 3.7, 2.68)): + rect(d, m(x0), m(y0), m(x1), m(y1), (0.40, 0.42, 0.45)) + rect(mr, m(x0), m(y0), m(x1), m(y1), (1.0, 0.42, 0.45)) + for yy in range(m(y0) + 3, m(y1) - 2, 4): + hline(d, yy, 1, (0.52, 0.54, 0.57), 1.0, m(x0) + 2, m(x1) - 2) + for (x0, y0, x1, y1, c) in ((1.2, 3.05, 1.55, 3.35, (0.32, 0.32, 0.34)), (2.65, 0.75, 2.85, 1.15, (0.55, 0.55, 0.57)), + (0.4, 1.3, 0.7, 1.5, (0.62, 0.6, 0.55)), (3.15, 3.2, 3.55, 3.4, (0.5, 0.5, 0.52))): + rect(d, m(x0), m(y0), m(x1), m(y1), c) + rect(mr, m(x0), m(y0), m(x1), m(y1), (1.0, 0.45, 0.5)) + hline(d, m(y0), 1, (0.25, 0.25, 0.26), 1.0, m(x0), m(x1)) + hline(d, m(y1), 1, (0.25, 0.25, 0.26), 1.0, m(x0), m(x1)) + for (cx, cy, r) in ((3.2, 1.1, 0.08), (0.7, 2.6, 0.06), (1.9, 1.6, 0.05)): + disc(d, m(cx), m(cy), m(r), (0.2, 0.2, 0.21)) + disc(d, m(cx), m(cy), m(r) - 2, (0.12, 0.12, 0.13)) + disc(mr, m(cx), m(cy), m(r), (1.0, 0.4, 0.7)) + # handrails: rows along v at u = 0.9 and 3.1 m, segments 0.9 m with 0.3 m gaps; one cross rail + rail = (0.46, 0.46, 0.49) + endc = (0.26, 0.26, 0.28) + for u in (0.9, 3.1): + for k in range(int(tile / 1.2)): + y0, y1 = m(k * 1.2 + 0.15), m(k * 1.2 + 1.05) + vline(d, m(u), 4, rail, 1.0, y0, y1) + vline(mr, m(u), 4, (1.0, 0.45, 0.6), 1.0, y0, y1) + rect(d, m(u) - 4, y0, m(u) + 4, y0 + 5, endc) + rect(d, m(u) - 4, y1 - 5, m(u) + 4, y1, endc) + hline(d, m(2.0), 4, rail, 1.0, m(1.3), m(2.9)) + hline(mr, m(2.0), 4, (1.0, 0.45, 0.6), 1.0, m(1.3), m(2.9)) + rect(d, m(1.3), m(2.0) - 4, m(1.3) + 5, m(2.0) + 4, endc) + rect(d, m(2.9) - 5, m(2.0) - 4, m(2.9), m(2.0) + 4, endc) + return d, mr + + +def tex_mli(n=512, tile=2.0, seed=7): + """Gold multi-layer insulation with wrinkles, olive patches, blanket seams and tape.""" + ppm = n / tile + w = fbm(n, 6, 6, seed, 0.6) + crinkle = fbm(n, 3, 48, seed + 1, 0.5) + lum = np.clip(0.82 + 0.45 * (w - 0.5) + 0.3 * (crinkle - 0.5), 0.4, 1.15) + gold = np.asarray((0.80, 0.62, 0.30), np.float32) + olive = np.asarray((0.66, 0.62, 0.40), np.float32) + zone = 0.6 * np.clip((fbm(n, 2, 2, seed + 2) - 0.6) * 5, 0, 1) + col = gold[None, None, :] * (1 - zone[..., None]) + olive[None, None, :] * zone[..., None] + d = col * lum[..., None] + mr = solid(n, (1.0, 0.36, 0.62)) + mr[..., 1] = np.clip(0.36 + 0.22 * (w - 0.5) + 0.1 * (crinkle - 0.5), 0.22, 0.55) + for k in range(int(tile)): + p = int(k * ppm) + hline(d, p, 2, (0.35, 0.27, 0.12), 0.85) + vline(d, p, 2, (0.35, 0.27, 0.12), 0.85) + hline(mr, p, 2, (1.0, 0.6, 0.3)) + vline(mr, p, 2, (1.0, 0.6, 0.3)) + def m(x): + return int(x * ppm) + for (x0, y0, x1, y1) in ((0.3, 1.4, 0.95, 1.46), (1.2, 0.3, 1.26, 0.9), (1.5, 1.6, 1.85, 1.66), (0.55, 0.55, 0.61, 0.95)): + rect(d, m(x0), m(y0), m(x1), m(y1), (0.55, 0.43, 0.2), 0.8) + rect(mr, m(x0), m(y0), m(x1), m(y1), (1.0, 0.5, 0.4)) + return d, mr + + +def tex_solar(n=512, tile=2.0, cells=16, seed=3): + """Dark blue-black cell grid with silver gaps and busbars, a hinge/fold strip every 8 cells (1 m).""" + rng = np.random.default_rng(seed) + cp = n // cells + d = np.zeros((n, n, 3), np.float32) + mr = solid(n, (1.0, 0.28, 0.65)) + yy, xx = np.mgrid[0:n, 0:n] + fy, fx = (yy % cp) / cp, (xx % cp) / cp + cellv = rng.uniform(0.85, 1.15, (cells, cells)).astype(np.float32) + per_cell = cellv[(yy // cp) % cells, (xx // cp) % cells] + navy = np.asarray((0.06, 0.08, 0.15), np.float32) + gold = np.asarray((0.10, 0.075, 0.03), np.float32) + sheen = (0.5 * fx + 0.5 * fy)[..., None] + d[:] = navy[None, None, :] * per_cell[..., None] + gold[None, None, :] * sheen + d += 0.02 * (fbm(n, 2, 64, seed + 1)[..., None] - 0.5) + mr[..., 1] = 0.26 + 0.06 * (per_cell - 0.85) / 0.3 + gap = ((xx % cp) < 2) | ((yy % cp) < 2) + d[gap] = (0.62, 0.63, 0.66) + mr[gap] = (1.0, 0.55, 0.35) + bus = (((xx % cp) == cp // 3) | ((xx % cp) == 2 * cp // 3)) & ~gap + d[bus] = (0.44, 0.46, 0.52) + mr[bus] = (1.0, 0.38, 0.55) + for k in range(int(tile)): + p = int(k * n / tile) + hline(d, p, 5, (0.72, 0.70, 0.64)) + hline(d, p - 3, 1, (0.3, 0.3, 0.32)) + hline(d, p + 3, 1, (0.3, 0.3, 0.32)) + hline(mr, p, 5, (1.0, 0.6, 0.15)) + return d, mr + + +def tex_solar_back(n=256, tile=2.0, seed=5): + """Back of the flexible blanket: grey-gold with fold lines every metre and faint seams.""" + ppm = n / tile + lum = 0.9 + 0.2 * fbm(n, 4, 4, seed) + d = solid(n, (0.54, 0.50, 0.42)) * lum[..., None] + for k in range(int(tile / 0.25)): + hline(d, int(k * ppm * 0.25), 1, (0.42, 0.39, 0.33), 0.5) + for k in range(int(tile)): + hline(d, int(k * ppm), 3, (0.33, 0.30, 0.25), 0.9) + return d + + +def tex_radiator(n=256, tile=1.0, seed=9): + """White/light grey with fine horizontal fin lines (every ~3 cm) and a stronger line every 0.25 m.""" + lum = 0.97 + 0.06 * fbm(n, 3, 4, seed) + d = solid(n, (0.80, 0.82, 0.84)) * lum[..., None] + for y in range(0, n, 8): + hline(d, y, 1, (0.62, 0.64, 0.67), 0.9) + for y in range(0, n, 64): + hline(d, y, 2, (0.5, 0.52, 0.55), 1.0) + return d + + +def tex_metal(n=256, base=(0.30, 0.30, 0.32), rough=0.45, metal=0.9, seed=11, panel=True): + """Brushed dark metal with panel lines and rivets.""" + lum = 0.85 + 0.3 * fbm(n, 5, 4, seed) + s = fbm(n, 4, 4, seed + 1) + streak = np.mean([np.roll(s, k, axis=1) for k in range(-12, 12)], axis=0) # periodic horizontal blur + lum = lum * (0.92 + 0.16 * streak) + d = solid(n, base) * lum[..., None] + mr = solid(n, (1.0, rough, metal)) + mr[..., 1] = np.clip(rough + 0.18 * (fbm(n, 4, 6, seed + 2) - 0.5), 0.15, 0.9) + if panel: + dark = tuple(c * 0.55 for c in base) + light = tuple(min(1, c * 1.5) for c in base) + for p in (0, n // 2): + hline(d, p, 1, dark) + vline(d, p, 1, dark) + for k in range(8, n, 32): + disc(d, k, p + 5, 1.5, light) + disc(d, p + 5, k, 1.5, light) + return d, mr + + +def tex_arm(n=256, tile=1.0, seed=13): + """White arm boom: a dark ring every metre, faint seams, two small dark plates (no lettering).""" + lum = 0.98 + 0.04 * fbm(n, 3, 4, seed) + d = solid(n, (0.88, 0.88, 0.87)) * lum[..., None] + hline(d, 0, 10, (0.14, 0.14, 0.15)) + hline(d, 7, 2, (0.5, 0.5, 0.52)) + for k in range(4): + hline(d, k * n // 4, 1, (0.7, 0.7, 0.7), 0.5) + rect(d, 70, 100, 100, 125, (0.12, 0.12, 0.13)) + rect(d, 150, 160, 190, 175, (0.12, 0.12, 0.13)) + return d + + +log("generating textures") +IMG = {} +IMG["hull_d"], IMG["hull_mr"] = tex_hull() +IMG["mli_d"], IMG["mli_mr"] = tex_mli() +IMG["solar_d"], IMG["solar_mr"] = tex_solar() +IMG["solar_back_d"] = tex_solar_back() +IMG["radiator_d"] = tex_radiator() +IMG["truss_d"], IMG["truss_mr"] = tex_metal(base=(0.30, 0.30, 0.32), rough=0.5, metal=0.9, seed=11) +IMG["fitting_d"], IMG["fitting_mr"] = tex_metal(base=(0.50, 0.50, 0.52), rough=0.45, metal=0.85, seed=17) +IMG["dock_d"], IMG["dock_mr"] = tex_metal(base=(0.58, 0.58, 0.60), rough=0.32, metal=0.95, seed=23, panel=False) +IMG["arm_d"] = tex_arm() +BIMG = {} +for k, arr in IMG.items(): + BIMG[k] = save_tex(f"tiangong_{k}", arr, noncolor=k.endswith("_mr")) +log("textures written to", TEX_DIR, {k: v for k, v in TEX_FILES.items()}) + +# --------------------------------------------------------------------------------------- materials +MATS = {} +MAT_TILE = {} # material -> (metres per texture repeat in u, in v) + + +def material(name, rgb, metallic=0.0, roughness=0.6, diffuse=None, mr=None, tile=(1.0, 1.0)): + """Principled material. diffuse/mr = Blender images (metallicRoughness via the Separate Color pattern + the glTF exporter recognises: G -> Roughness, B -> Metallic).""" + m = bpy.data.materials.new(name) + m.use_nodes = True + nt = m.node_tree + bsdf = nt.nodes.get("Principled BSDF") + bsdf.inputs["Base Color"].default_value = (*rgb, 1.0) + bsdf.inputs["Metallic"].default_value = metallic + bsdf.inputs["Roughness"].default_value = roughness + if diffuse is not None: + t = nt.nodes.new("ShaderNodeTexImage") + t.image = diffuse + t.location = (-500, 300) + nt.links.new(t.outputs["Color"], bsdf.inputs["Base Color"]) + if mr is not None: + t = nt.nodes.new("ShaderNodeTexImage") + t.image = mr + t.location = (-500, -100) + sep = nt.nodes.new("ShaderNodeSeparateColor") + sep.location = (-200, -100) + nt.links.new(t.outputs["Color"], sep.inputs["Color"]) + nt.links.new(sep.outputs["Green"], bsdf.inputs["Roughness"]) + nt.links.new(sep.outputs["Blue"], bsdf.inputs["Metallic"]) + m.use_backface_culling = True # -> glTF doubleSided: false + m.diffuse_color = (*rgb, 1.0) + m.metallic = metallic + m.roughness = roughness + MATS[name] = m + MAT_TILE[name] = tile + return m + + +material("HULL", (0.82, 0.82, 0.80), 0.0, 0.55, BIMG["hull_d"], BIMG["hull_mr"], (4.0, 4.0)) # white thermal blankets +material("MLI", (0.75, 0.58, 0.28), 0.6, 0.36, BIMG["mli_d"], BIMG["mli_mr"], (2.0, 2.0)) # gold foil +material("ARRAY", (0.08, 0.10, 0.17), 0.65, 0.28, BIMG["solar_d"], BIMG["solar_mr"], (2.0, 2.0)) # cell side +material("ARRAY_BACK", (0.52, 0.48, 0.40), 0.25, 0.65, BIMG["solar_back_d"], None, (2.0, 2.0)) # blanket back +material("ARRAY_FRAME", (0.12, 0.12, 0.13), 0.5, 0.5) # masts, rails +material("TRUSS", (0.30, 0.30, 0.32), 0.9, 0.5, BIMG["truss_d"], BIMG["truss_mr"], (1.0, 1.0)) # trusses, drive housings +material("FITTING", (0.50, 0.50, 0.52), 0.85, 0.45, BIMG["fitting_d"], BIMG["fitting_mr"], (1.0, 1.0)) # grey fittings, handrails +material("DOCK", (0.58, 0.58, 0.60), 0.95, 0.32, BIMG["dock_d"], BIMG["dock_mr"], (1.0, 1.0)) # docking rings, nozzles +material("RADIATOR", (0.80, 0.82, 0.84), 0.0, 0.7, BIMG["radiator_d"], None, (1.0, 1.0)) +material("ARM_WHITE", (0.88, 0.88, 0.87), 0.0, 0.5, BIMG["arm_d"], None, (1.0, 1.0)) # arm booms +material("ARM_JOINT", (0.06, 0.06, 0.07), 0.4, 0.35) # black joint housings +material("CAPSULE", (0.36, 0.31, 0.28), 0.1, 0.75) # Shenzhou re-entry capsule + +# --------------------------------------------------------------------------------------- UV projection +# UVs are metres / MAT_TILE so every texture keeps the same texel density. Cylinders get a cylindrical +# projection with an integer number of repeats around (no seam mismatch), boxes a tri-planar one, wings a +# planar one along the wing axes. +TWO_PI = 2 * math.pi + + +def _loops_world(o): + me = o.data + loc = Vector(o.location) + vs = [v.co + loc for v in me.vertices] + if not me.uv_layers: + me.uv_layers.new(name="UVMap") + return me, vs, me.uv_layers.active.data + + +def _perp(d): + e1 = d.cross(V(0, 0, 1)) + if e1.length < 1e-3: + e1 = d.cross(V(1, 0, 0)) + e1.normalize() + return e1, d.cross(e1) + + +def uv_cyl(o, mat, center, direction): + """Cylindrical projection about the axis (center, direction) (glTF coords), v along the axis.""" + tu, tv = MAT_TILE[mat] + c = B(center) + d = B(direction).normalized() + e1, e2 = _perp(d) + me, vs, uv = _loops_world(o) + rmax = max(((p - c) - (p - c).dot(d) * d).length for p in vs) + circ = TWO_PI * rmax + wraps = max(1, round(circ / tu)) + small = circ < 0.5 * tu + for poly in me.polygons: + pts = [vs[me.loops[li].vertex_index] - c for li in poly.loop_indices] + if abs(poly.normal.dot(d)) > 0.9: # cap: planar + for li, p in zip(poly.loop_indices, pts): + uv[li].uv = (p.dot(e1) / tu, p.dot(e2) / tv) + continue + angs = [math.atan2(p.dot(e2), p.dot(e1)) for p in pts] + if max(angs) - min(angs) > math.pi: + angs = [a + TWO_PI if a < 0 else a for a in angs] + for li, p, a in zip(poly.loop_indices, pts, angs): + u = a * rmax / tu if small else a / TWO_PI * wraps + uv[li].uv = (u, p.dot(d) / tv) + + +def uv_box(o, mat): + """Tri-planar projection by dominant face normal (Blender world coords, metres / tile).""" + tu, tv = MAT_TILE[mat] + me, vs, uv = _loops_world(o) + for poly in me.polygons: + n = poly.normal + ax = max(range(3), key=lambda i: abs(n[i])) + i, j = [k for k in range(3) if k != ax] + for li in poly.loop_indices: + p = vs[me.loops[li].vertex_index] + uv[li].uv = (p[i] / tu, p[j] / tv) + + +def uv_planar(o, mat, origin, eu, ev): + """Planar projection: u along eu, v along ev (glTF coords, metres / tile).""" + tu, tv = MAT_TILE[mat] + c = B(origin) + bu = B(eu).normalized() + bv = B(ev).normalized() + me, vs, uv = _loops_world(o) + for poly in me.polygons: + for li in poly.loop_indices: + p = vs[me.loops[li].vertex_index] - c + uv[li].uv = (p.dot(bu) / tu, p.dot(bv) / tv) + + +# --------------------------------------------------------------------------------------- primitives +WORLD = {} # object name -> world translation (Blender coords) at build time (root at origin) +ALL_MESHES = [] +VEHICLE_MESHES = [] + + +def _apply_rot_scale(obj): + bpy.ops.object.select_all(action="DESELECT") + obj.select_set(True) + bpy.context.view_layer.objects.active = obj + bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) + + +def _set_mat(obj, mat): + obj.data.materials.clear() + obj.data.materials.append(MATS[mat]) + + +def _rot_for(direction): + """Euler that turns Blender +Z onto the Blender image of a glTF direction.""" + d = B(direction).normalized() + return V(0, 0, 1).rotation_difference(d).to_euler() + + +def box(center, size, mat): + bpy.ops.mesh.primitive_cube_add(size=1.0, location=B(center)) + o = bpy.context.active_object + o.scale = Bsize(size) + _apply_rot_scale(o) + _set_mat(o, mat) + uv_box(o, mat) + return o + + +def cyl(center, direction, radius, length, mat, segs=24): + bpy.ops.mesh.primitive_cylinder_add(vertices=segs, radius=radius, depth=length, + location=B(center), rotation=_rot_for(direction)) + o = bpy.context.active_object + _apply_rot_scale(o) + _set_mat(o, mat) + uv_cyl(o, mat, center, direction) + return o + + +def cyl_from(start, direction, radius, length, mat, segs=24): + """Cylinder whose base is at `start` and which extends `length` along `direction`.""" + d = Vector(direction).normalized() + c = Vector(start) + d * (length / 2) + return cyl(c, d, radius, length, mat, segs) + + +def cone_from(start, direction, r1, r2, length, mat, segs=24): + """Frustum from radius r1 at `start` to r2 at start + direction*length.""" + d = Vector(direction).normalized() + c = Vector(start) + d * (length / 2) + bpy.ops.mesh.primitive_cone_add(vertices=segs, radius1=r1, radius2=r2, depth=length, + location=B(c), rotation=_rot_for(d)) + o = bpy.context.active_object + _apply_rot_scale(o) + _set_mat(o, mat) + uv_cyl(o, mat, c, d) + return o + + +def sphere(center, radius, mat, segs=32, rings=16): + bpy.ops.mesh.primitive_uv_sphere_add(segments=segs, ring_count=rings, radius=radius, location=B(center)) + o = bpy.context.active_object + _apply_rot_scale(o) + _set_mat(o, mat) + uv_cyl(o, mat, center, (0, 1, 0)) + return o + + +def ring(center, direction, R, r, mat, segs=24, msegs=6): + """Torus (hatch ring / port collar) with its axis along `direction`.""" + bpy.ops.mesh.primitive_torus_add(major_segments=segs, minor_segments=msegs, major_radius=R, minor_radius=r, + location=B(center), rotation=_rot_for(direction)) + o = bpy.context.active_object + _apply_rot_scale(o) + _set_mat(o, mat) + uv_box(o, mat) + return o + + +def band(center, direction, R, mat, width=0.1, lip=0.035, segs=48): + """Cheap hull band: a short cylinder standing `lip` proud of a hull of radius R (replaces a torus collar).""" + return cyl(center, direction, R + lip, width, mat, segs) + + +def handrail(start, direction, length, up, mat="FITTING", r=0.02, standoff=0.08): + """Thin rail `length` long from `start` along `direction`, held `standoff` off the surface by two posts (`up` = surface normal).""" + d = Vector(direction).normalized() + u = Vector(up).normalized() + c = Vector(start) + d * (length / 2) + u * standoff + size = [2 * r] * 3 + for i in range(3): + if abs(d[i]) > 0.5: + size[i] = length + parts = [box(c, size, mat)] + for t in (0.1, length - 0.1): + pc = Vector(start) + d * t + u * (standoff / 2) + ps = [2 * r] * 3 + for i in range(3): + if abs(u[i]) > 0.5: + ps[i] = standoff + parts.append(box(pc, ps, mat)) + return parts + + +def wing_panel(center, size, length_dir, width_dir, normal_dir): + """Thin solar blanket box: cell texture on the `normal_dir` face, blanket back elsewhere, planar UVs in + metres so the 0.125 m cell grid never stretches.""" + bpy.ops.mesh.primitive_cube_add(size=1.0, location=B(center)) + o = bpy.context.active_object + o.scale = Bsize(size) + _apply_rot_scale(o) + o.data.materials.clear() + o.data.materials.append(MATS["ARRAY"]) + o.data.materials.append(MATS["ARRAY_BACK"]) + nb = B(normal_dir).normalized() + for poly in o.data.polygons: + poly.material_index = 0 if poly.normal.dot(nb) > 0.5 else 1 + uv_planar(o, "ARRAY", center, width_dir, length_dir) + return o + + +def shade_smooth(o): + bpy.ops.object.select_all(action="DESELECT") + o.select_set(True) + bpy.context.view_layer.objects.active = o + try: + bpy.ops.object.shade_smooth_by_angle(angle=math.radians(32)) + except Exception: # noqa: BLE001 + try: + bpy.ops.object.shade_smooth() + o.data.set_sharp_from_angle(angle=math.radians(32)) + except Exception as e: # noqa: BLE001 + log("smooth shading unavailable:", repr(e)) + + +def finish(parts, name, origin, parent=None, vehicle=False): + """Join `parts` into one mesh object `name`, put its origin at glTF point `origin`, parent it.""" + bpy.ops.object.select_all(action="DESELECT") + for p in parts: + p.select_set(True) + bpy.context.view_layer.objects.active = parts[0] + if len(parts) > 1: + bpy.ops.object.join() + o = bpy.context.active_object + o.name = name + o.data.name = name + shade_smooth(o) + # vehicles carry array joints: their node must stay in the root frame (identity), like the joints + scene.cursor.location = B((0, 0, 0) if vehicle else origin) + bpy.ops.object.origin_set(type="ORIGIN_CURSOR") + attach(o, parent) + ALL_MESHES.append(o) + if vehicle: + VEHICLE_MESHES.append(o) + return o + + +def attach(obj, parent): + """Parent with an identity parent-inverse so the glTF local transform is a plain translation.""" + world = Vector(obj.location) if obj.parent is None else WORLD[obj.name] + if parent is not None: + obj.parent = parent + obj.matrix_parent_inverse.identity() + obj.location = world - WORLD[parent.name] + WORLD[obj.name] = world + + +def empty(name, pos, parent=None, size=0.5): + """pos = glTF point, or None for an identity node sitting on its parent's origin.""" + e = bpy.data.objects.new(name, None) + e.empty_display_type = "PLAIN_AXES" + e.empty_display_size = size + coll.objects.link(e) + e.location = B(pos) if pos is not None else WORLD[parent.name].copy() + attach(e, parent) + return e + + +JOINTS = [] +DRIVEN_KINDS = {"alpha", "beta", "arm", "antenna"} + + +def joint(name, pivot, axis, kind, range_deg, approximate, parent): + # Driven joints follow the ISS file's convention: the node's rest transform is the identity (so its + # frame is the root frame) and the app replaces its matrix with a rotation about `pivot`, which is + # therefore given in root-frame coordinates. Dock markers are not driven; they sit at the port face. + e = empty(name, None if kind in DRIVEN_KINDS else pivot, parent) + piv = [round(float(c), 4) for c in pivot] + ax = unit(axis) + e["pivot"] = piv + e["axis"] = ax + e["kind"] = kind + e["rangeDeg"] = [float(range_deg[0]), float(range_deg[1])] if range_deg else [0.0, 0.0] + e["approximate"] = bool(approximate) + JOINTS.append({"node": name, "pivot": piv, "axis": ax, "kind": kind, + "rangeDeg": list(range_deg) if range_deg else None, "approximate": bool(approximate), + "parent": parent.name if parent else None}) + return e + + +# ======================================================================================= ROOT +root = empty("tiangong", (0, 0, 0), None, size=2.0) + +# ======================================================================================= TIANHE +# Layout along Z (forward +Z -> aft -Z); total 16.6 m: forward dock face z=+8.3, aft dock face z=-8.3. +NODE_C = V(0, 0, 6.4) # node sphere centre; the labs' axis passes through here +NODE_R = 1.45 # ~2.9 m diameter (approximate) +Z_FWD = 8.3 +Z_AFT = -8.3 + +# --- node: sphere + 5 ports +parts = [sphere(NODE_C, NODE_R, "HULL", 40, 20)] +parts.append(cyl_from(NODE_C + V(0, 0, 1.1), (0, 0, 1), 0.75, Z_FWD - (NODE_C.z + 1.1), "HULL", 32)) # forward port tube +parts.append(cyl_from((0, 0, Z_FWD - 0.15), (0, 0, 1), 0.92, 0.15, "DOCK", 32)) # forward docking ring +parts.append(cyl_from(NODE_C + V(0, -1.1, 0), (0, -1, 0), 0.75, 0.9, "HULL", 32)) # nadir port tube -> y=-2.0 +parts.append(cyl_from((0, -2.0 + 0.15, NODE_C.z), (0, -1, 0), 0.92, 0.15, "DOCK", 32)) +parts.append(cyl_from(NODE_C + V(0, 1.1, 0), (0, 1, 0), 0.75, 0.9, "HULL", 32)) # zenith hatch tube -> y=+2.0 +parts.append(cyl_from((0, 2.0 - 0.15, NODE_C.z), (0, 1, 0), 0.92, 0.15, "DOCK", 32)) +parts.append(cyl_from(NODE_C + V(1.1, 0, 0), (1, 0, 0), 0.95, 1.0, "HULL", 32)) # port berth -> x=+2.1 +parts.append(cyl_from(NODE_C + V(-1.1, 0, 0), (-1, 0, 0), 0.95, 1.0, "HULL", 32)) # starboard berth -> x=-2.1 +# detail: hatch rings on the three free ports, collars where the tubes leave the sphere, camera/equipment boxes +parts.append(ring((0, 0, Z_FWD - 0.08), (0, 0, 1), 0.78, 0.06, "DOCK")) +parts.append(ring((0, -2.0 + 0.08, NODE_C.z), (0, -1, 0), 0.78, 0.06, "DOCK")) +parts.append(ring((0, 2.0 - 0.08, NODE_C.z), (0, 1, 0), 0.78, 0.06, "DOCK")) +parts.append(band(NODE_C + V(0, 0, 1.3), (0, 0, 1), 0.75, "FITTING", 0.12, 0.04, 32)) +parts.append(band(NODE_C + V(0, 1.3, 0), (0, 1, 0), 0.75, "FITTING", 0.12, 0.04, 32)) +parts.append(band(NODE_C + V(0, -1.3, 0), (0, -1, 0), 0.75, "FITTING", 0.12, 0.04, 32)) +parts.append(box(NODE_C + V(0.75, 1.05, 0.75), (0.3, 0.25, 0.3), "FITTING")) +parts.append(box(NODE_C + V(-0.75, 1.05, 0.75), (0.3, 0.25, 0.3), "FITTING")) +parts.append(box(NODE_C + V(0.0, -1.1, 0.9), (0.35, 0.2, 0.25), "FITTING")) +finish(parts, "TIANHE_NODE", NODE_C, root) + +# --- small cylinder (life support), 2.8 m diameter, from the node sphere to the cone +SC_R = 1.4 +z_sc0 = NODE_C.z - NODE_R # 4.95 +z_sc1 = 2.1 +parts = [cyl_from((0, 0, z_sc0), (0, 0, -1), SC_R, z_sc0 - z_sc1, "HULL", 48)] +parts.append(cone_from((0, 0, z_sc1), (0, 0, -1), SC_R, 2.1, 0.6, "MLI", 48)) # transition to 4.2 m +parts.append(band((0, 0, z_sc0 - 0.06), (0, 0, 1), SC_R, "FITTING")) # collar at the node +for sx in (1, -1): + parts += handrail((sx * 0.9, math.sqrt(SC_R ** 2 - 0.81) - 0.02, 4.7), (0, 0, -1), 1.4, (0, 1, 0)) + parts += handrail((sx * (math.sqrt(SC_R ** 2 - 0.25) - 0.02), 0.5, 4.6), (0, 0, -1), 2.2, (sx, 0, 0)) +parts.append(box((-0.9, -math.sqrt(SC_R ** 2 - 0.81) - 0.1, 3.4), (0.4, 0.3, 0.6), "FITTING")) # equipment box, nadir side +finish(parts, "TIANHE_SMALL_CYLINDER", (0, 0, (z_sc0 + z_sc1) / 2), root) + +# --- large cylinder (living section), 4.2 m diameter +LC_R = 2.1 +z_lc0 = 1.5 +z_lc1 = -5.0 +parts = [cyl_from((0, 0, z_lc0), (0, 0, -1), LC_R, z_lc0 - z_lc1, "HULL", 48)] +# a few handrails along the top (cheap) +for zz in (0.0, -2.5): + parts.append(box((0.9, LC_R + 0.08, zz), (0.05, 0.05, 1.6), "FITTING")) + parts.append(box((-0.9, LC_R + 0.08, zz), (0.05, 0.05, 1.6), "FITTING")) +# detail: panel-joint bands, side handrails, equipment boxes, GNSS patches +for zz in (-0.6, -3.2): + parts.append(band((0, 0, zz), (0, 0, 1), LC_R, "FITTING")) +for sx in (1, -1): + for z0 in (1.2, -1.2, -3.6): + parts += handrail((sx * (math.sqrt(LC_R ** 2 - 0.36) - 0.02), 0.6, z0), (0, 0, -1), 1.4, (sx, 0, 0)) + parts.append(box((sx * (LC_R - 0.05), -0.8, -1.5), (0.5, 0.45, 0.9), "FITTING")) + parts.append(box((sx * 0.5, LC_R - 0.02, 0.9), (0.28, 0.08, 0.28), "FITTING")) + parts.append(box((sx * 1.6, -(LC_R - 0.05), -4.0), (0.4, 0.3, 0.6), "FITTING")) +parts.append(cyl_from((0, LC_R - 0.05, -4.3), (0, 1, 0), 0.03, 0.6, "FITTING", 6)) # whip antenna +finish(parts, "TIANHE_LARGE_CYLINDER", (0, 0, (z_lc0 + z_lc1) / 2), root) + +# --- resource / service section (approximate 2.8 m diameter) with the aft port and the HGA mast +RS_R = 1.4 +z_rs0 = -5.6 +z_rs1 = -7.9 +parts = [cone_from((0, 0, z_lc1), (0, 0, -1), LC_R, RS_R, abs(z_lc1 - z_rs0), "MLI", 48)] +parts.append(cyl_from((0, 0, z_rs0), (0, 0, -1), RS_R, z_rs0 - z_rs1, "MLI", 48)) +parts.append(cyl_from((0, 0, z_rs1), (0, 0, -1), 0.75, z_rs1 - Z_AFT, "HULL", 32)) # aft port tube +parts.append(cyl_from((0, 0, Z_AFT + 0.15), (0, 0, -1), 0.92, 0.15, "DOCK", 32)) # aft docking ring +HGA_Z = -6.0 +parts.append(cyl_from((0, RS_R - 0.1, HGA_Z), (0, 1, 0), 0.08, 1.1, "FITTING", 12)) # HGA mast (fixed) +for sx in (1, -1): # solar wing drive housings on the hull + parts.append(cyl_from((sx * (RS_R - 0.2), 0, -6.7), (sx, 0, 0), 0.3, 0.45, "FITTING", 16)) +# detail: collar rings, hatch ring, aft thruster quads, tank domes under the blankets, antennas +parts.append(band((0, 0, z_rs0 - 0.06), (0, 0, 1), RS_R, "FITTING")) +parts.append(band((0, 0, z_rs1 + 0.06), (0, 0, 1), RS_R, "FITTING")) +parts.append(ring((0, 0, Z_AFT + 0.08), (0, 0, -1), 0.78, 0.06, "DOCK")) +parts.append(band((0, 0, z_rs1 - 0.08), (0, 0, 1), 0.75, "FITTING", 0.12, 0.05, 32)) +for (dx, dy) in ((0.95, 0.95), (-0.95, 0.95), (0.95, -0.95), (-0.95, -0.95)): # aft thruster pods + parts.append(box((dx, dy, z_rs1 - 0.05), (0.26, 0.26, 0.3), "FITTING")) + parts.append(cone_from((dx, dy, z_rs1 - 0.15), (0, 0, -1), 0.06, 0.11, 0.25, "DOCK", 10)) +parts.append(cyl_from((0, -(RS_R - 0.05), -6.3), (0, -1, 0), 0.03, 0.7, "FITTING", 6)) +parts.append(cyl_from((RS_R - 0.05, 0.5, -5.9), (1, 0, 0), 0.025, 0.5, "FITTING", 6)) +finish(parts, "TIANHE_RESOURCE", (0, 0, (z_lc1 + Z_AFT) / 2), root) + +# --- Tianhe solar wings: one-axis alpha drives, 12.6 m per wing (design paper), ~2.5 m wide (approx.) +TH_WING_L = 12.6 +TH_WING_W = 2.5 +TH_WING_Z = -6.7 +for tag, sx in (("PORT", 1), ("STBD", -1)): + pivot = V(sx * RS_R, 0, TH_WING_Z) + j = joint(f"TIANHE_ARRAY_{tag}_ALPHA", pivot, (sx, 0, 0), "alpha", (-180, 180), False, root) + x0 = sx * (RS_R + 0.25) + parts = [cyl_from(pivot, (sx, 0, 0), 0.09, TH_WING_L + 0.3, "ARRAY_FRAME", 10)] # boom + pc = V(sx * (RS_R + 0.25 + TH_WING_L / 2), 0, TH_WING_Z) + parts.append(wing_panel(pc, (TH_WING_L, 0.05, TH_WING_W), (sx, 0, 0), (0, 0, 1), (0, 1, 0))) + for dz in (TH_WING_W / 2, -TH_WING_W / 2): + parts.append(box((sx * (RS_R + 0.25 + TH_WING_L / 2), 0, TH_WING_Z + dz), (TH_WING_L, 0.08, 0.08), "ARRAY_FRAME")) + # tension frame: cross bars on the back every 2.1 m, tip bar, root fitting + for k in range(7): + xx = sx * (RS_R + 0.25 + k * 2.1) + parts.append(box((xx, -0.06, TH_WING_Z), (0.06, 0.06, TH_WING_W), "ARRAY_FRAME")) + parts.append(box((sx * (RS_R + 0.25 + TH_WING_L), 0, TH_WING_Z), (0.08, 0.1, TH_WING_W + 0.08), "ARRAY_FRAME")) + parts.append(cyl_from(pivot, (sx, 0, 0), 0.14, 0.3, "ARM_JOINT", 12)) + finish(parts, f"TIANHE_ARRAY_{tag}", pivot, j) + +# --- steerable relay dish (approximate position; 2 implied gimbal axes, boresight +Y at rest) +hga_pivot = V(0, RS_R + 1.0, HGA_Z) +j = joint("TIANHE_HGA", hga_pivot, (0, 1, 0), "antenna", (-90, 90), True, root) +parts = [sphere(hga_pivot, 0.14, "ARM_JOINT", 12, 8)] +parts.append(cone_from(hga_pivot + V(0, 0.1, 0), (0, 1, 0), 0.12, 0.65, 0.32, "HULL", 32)) # dish +parts.append(cyl_from(hga_pivot + V(0, 0.42, 0), (0, 1, 0), 0.03, 0.4, "FITTING", 8)) # feed +parts.append(ring(hga_pivot + V(0, 0.42, 0), (0, 1, 0), 0.62, 0.025, "FITTING", 32, 5)) # dish rim +parts.append(cone_from(hga_pivot + V(0, 0.82, 0), (0, 1, 0), 0.03, 0.08, 0.05, "FITTING", 10)) # feed horn +finish(parts, "TIANHE_HGA_DISH", hga_pivot, j) + +# --- small antennas on the node (cheap) +parts = [] +for (x, y, z, d) in ((0.9, 0.9, 7.0, (0, 1, 0)), (-0.9, 0.9, 7.0, (0, 1, 0)), (0, -0.4, 7.9, (0, 0, 1))): + parts.append(cyl_from((x, y, z), d, 0.025, 1.0, "FITTING", 6)) + parts.append(cyl_from((x, y, z), d, 0.06, 0.12, "ARM_JOINT", 8)) # base +parts.append(cone_from((0.95, 0.95, 6.1), (0.7, 0.7, 0), 0.03, 0.2, 0.12, "HULL", 16)) # small horn/dish +finish(parts, "TIANHE_ANTENNAS", NODE_C, root) + +# ======================================================================================= DOCKING PORTS (informational empties) +joint("DOCK_FORWARD", (0, 0, Z_FWD), (0, 0, 1), "dock", None, False, root) +joint("DOCK_AFT", (0, 0, Z_AFT), (0, 0, -1), "dock", None, False, root) +joint("DOCK_NADIR", (0, -2.0, NODE_C.z), (0, -1, 0), "dock", None, True, root) +joint("DOCK_ZENITH", (0, 2.0, NODE_C.z), (0, 1, 0), "dock", None, True, root) +joint("BERTH_PORT", (2.1, 0, NODE_C.z), (1, 0, 0), "dock", None, True, root) +joint("BERTH_STBD", (-2.1, 0, NODE_C.z), (-1, 0, 0), "dock", None, True, root) + +# ======================================================================================= LABS (Wentian -X, Mengtian +X) +LAB_LEN = 17.9 +LAB_R = 2.1 +LAB_RS_R = 1.4 +LAB_Z = NODE_C.z +LAB_WING_L = 27.0 +LAB_WING_W = 4.0 + + +def lab(prefix, sx): + """sx = -1 for Wentian (starboard), +1 for Mengtian (port). Returns the truss x.""" + x_in = sx * 2.1 # berth face + x_work = sx * 11.0 # end of the working section + x_cone = sx * 11.6 + x_res = sx * 17.8 # end of the resource section + x_tip = sx * (2.1 + LAB_LEN) # 20.0: outboard end of the truss + out = (sx, 0, 0) + + # body: working section + cone + resource section + parts = [cyl_from((x_in, 0, LAB_Z), out, LAB_R, abs(x_work - x_in), "HULL", 48)] + parts.append(cone_from((x_work, 0, LAB_Z), out, LAB_R, LAB_RS_R, abs(x_cone - x_work), "MLI", 48)) + parts.append(cyl_from((x_cone, 0, LAB_Z), out, LAB_RS_R, abs(x_res - x_cone), "MLI", 48)) + parts.append(cyl_from((x_res, 0, LAB_Z), out, 0.8, 0.5, "FITTING", 16)) # resource-section end cap + for zz in (LAB_Z + 0.8, LAB_Z - 0.8): # handrails + parts.append(box((sx * 6.5, LAB_R + 0.08, zz), (6.0, 0.05, 0.05), "FITTING")) + # detail: collar rings, more handrails (nadir side and flanks), equipment boxes, thruster quads, antennas + parts.append(band((x_in + sx * 0.06, 0, LAB_Z), out, LAB_R, "FITTING")) + parts.append(band((sx * 6.6, 0, LAB_Z), out, LAB_R, "FITTING")) + parts.append(band((x_work - sx * 0.06, 0, LAB_Z), out, LAB_R, "FITTING")) + parts.append(band((x_res - sx * 0.06, 0, LAB_Z), out, LAB_RS_R, "FITTING")) + for x0 in (3.2, 5.0, 7.6): + parts += handrail((sx * x0, -(math.sqrt(LAB_R ** 2 - 0.25) - 0.02), LAB_Z + 0.5), (sx, 0, 0), 1.4, (0, -1, 0)) + parts += handrail((sx * x0, 0.4, LAB_Z + math.sqrt(LAB_R ** 2 - 0.16) - 0.02), (sx, 0, 0), 1.4, (0, 0, 1)) + parts += handrail((sx * x0, -0.4, LAB_Z - math.sqrt(LAB_R ** 2 - 0.16) + 0.02), (sx, 0, 0), 1.4, (0, 0, -1)) + parts.append(box((sx * 4.2, -0.9, LAB_Z + LAB_R - 0.05), (0.9, 0.5, 0.45), "FITTING")) + parts.append(box((sx * 9.3, 0.9, LAB_Z - LAB_R + 0.05), (0.7, 0.45, 0.4), "FITTING")) + parts.append(box((sx * 8.5, -(LAB_R - 0.05), LAB_Z - 0.9), (0.6, 0.4, 0.5), "FITTING")) + parts.append(box((sx * 3.4, LAB_R - 0.03, LAB_Z - 1.1), (0.3, 0.08, 0.3), "FITTING")) # GNSS patch + for (dy, dz) in ((0.95, 0.95), (-0.95, 0.95), (0.95, -0.95), (-0.95, -0.95)): # thruster pods + parts.append(box((x_res - sx * 0.1, dy, LAB_Z + dz), (0.3, 0.25, 0.25), "FITTING")) + parts.append(cone_from((x_res + sx * 0.05, dy, LAB_Z + dz), out, 0.05, 0.1, 0.28, "DOCK", 10)) + parts.append(cyl_from((sx * 15.0, LAB_RS_R - 0.05, LAB_Z), (0, 1, 0), 0.03, 0.7, "FITTING", 6)) + parts.append(cyl_from((sx * 13.0, -(LAB_RS_R - 0.05), LAB_Z), (0, -1, 0), 0.03, 0.6, "FITTING", 6)) + finish(parts, f"{prefix}_BODY", ((x_in + x_res) / 2, 0, LAB_Z), root) + + # truss / boom carrying the two alpha drives + parts = [box(((x_res + x_tip) / 2, 0, LAB_Z), (abs(x_tip - x_res), 0.9, 0.9), "TRUSS")] + parts.append(box(((x_res + x_tip) / 2, 0, LAB_Z), (1.2, 0.3, 2.6), "TRUSS")) # cross beam fwd/aft + # detail: longerons along the truss edges and a tip plate + for (dy, dz) in ((0.45, 0.45), (-0.45, 0.45), (0.45, -0.45), (-0.45, -0.45)): + parts.append(box(((x_res + x_tip) / 2, dy, LAB_Z + dz), (abs(x_tip - x_res) + 0.04, 0.1, 0.1), "FITTING")) + parts.append(box((x_tip - sx * 0.03, 0, LAB_Z), (0.06, 1.0, 1.0), "FITTING")) + parts.append(ring((x_res + sx * 0.05, 0, LAB_Z), out, 0.62, 0.05, "FITTING", 20, 6)) + finish(parts, f"{prefix}_TRUSS", ((x_res + x_tip) / 2, 0, LAB_Z), root) + + # radiator: flat panel aft (-Z) of the resource section + rad_c = (sx * 14.6, 0, LAB_Z - LAB_RS_R - 0.12) + parts = [box(rad_c, (4.8, 2.4, 0.05), "RADIATOR")] + parts.append(box((rad_c[0], 0, LAB_Z - LAB_RS_R + 0.02), (4.6, 0.1, 0.2), "FITTING")) + # detail: frame bars around the panel and two struts to the hull + for dy in (1.2, -1.2): + parts.append(box((rad_c[0], dy, rad_c[2]), (4.84, 0.06, 0.08), "FITTING")) + for dx in (2.4, -2.4): + parts.append(box((rad_c[0] + dx, 0, rad_c[2]), (0.06, 2.4, 0.08), "FITTING")) + for dx in (1.6, -1.6): + parts.append(box((rad_c[0] + dx, 0, LAB_Z - LAB_RS_R + 0.05), (0.08, 0.6, 0.12), "FITTING")) + finish(parts, f"{prefix}_RADIATOR", rad_c, root) + + # two large wings: alpha about X at the truss, beta about the wing's own axis Z + xt = (x_res + x_tip) / 2 + for tag, sz in (("FWD", 1), ("AFT", -1)): + a_piv = V(xt, 0, LAB_Z + sz * 0.5) + a = joint(f"{prefix}_ARRAY_{tag}_ALPHA", a_piv, (sx, 0, 0), "alpha", (-180, 180), False, root) + parts = [cyl_from(a_piv, (0, 0, sz), 0.4, 0.8, "TRUSS", 24)] # alpha drive housing + parts.append(ring(a_piv + V(0, 0, sz * 0.4), (0, 0, sz), 0.4, 0.04, "ARM_JOINT", 20, 6)) + finish(parts, f"{prefix}_ARRAY_{tag}_DRIVE", a_piv, a) + b_piv = a_piv + V(0, 0, sz * 0.8) + b = joint(f"{prefix}_ARRAY_{tag}_BETA", b_piv, (0, 0, sz), "beta", (-180, 180), False, a) + parts = [box(b_piv + V(0, 0, sz * (LAB_WING_L + 0.3) / 2), (0.35, 0.35, LAB_WING_L + 0.3), "ARRAY_FRAME")] # mast + pc = b_piv + V(0, 0, sz * (0.3 + LAB_WING_L / 2)) + parts.append(wing_panel(pc, (LAB_WING_W, 0.06, LAB_WING_L), (0, 0, sz), (1, 0, 0), (0, 1, 0))) + for dx in (LAB_WING_W / 2, -LAB_WING_W / 2): + parts.append(box(pc + V(dx, 0, 0), (0.1, 0.12, LAB_WING_L), "ARRAY_FRAME")) + # tension frame: cross bars on the back every 3 m, tip bar, beta drive collar + for k in range(9): + zz = b_piv.z + sz * (0.3 + k * 3.0) + parts.append(box((xt, -0.08, zz), (LAB_WING_W, 0.06, 0.06), "ARRAY_FRAME")) + parts.append(box((xt, 0, b_piv.z + sz * (0.3 + LAB_WING_L - 0.05)), (LAB_WING_W + 0.1, 0.12, 0.1), "ARRAY_FRAME")) + parts.append(cyl_from(b_piv, (0, 0, sz), 0.3, 0.3, "ARM_JOINT", 20)) + finish(parts, f"{prefix}_ARRAY_{tag}", b_piv, b) + return xt + + +# Wentian (starboard, -X): body + EVA airlock bulge + small arm (EMM) +lab("WENTIAN", -1) +air_c = V(-12.9, 1.8, LAB_Z) +parts = [cyl_from((-11.7, 1.8, LAB_Z), (-1, 0, 0), 1.0, 2.4, "HULL", 32)] +parts.append(cyl_from((-14.1, 1.8, LAB_Z), (-1, 0, 0), 0.6, 0.25, "DOCK", 24)) # EVA hatch +parts.append(box((-12.9, 0.9, LAB_Z), (2.0, 0.6, 1.6), "HULL")) # saddle to the hull +parts.append(ring((-14.3, 1.8, LAB_Z), (-1, 0, 0), 0.5, 0.05, "FITTING", 24, 6)) # hatch ring +parts.append(band((-11.78, 1.8, LAB_Z), (-1, 0, 0), 1.0, "FITTING", 0.1, 0.035, 32)) # collar +parts += handrail((-12.2, 2.70, LAB_Z + 0.4), (-1, 0, 0), 1.4, (0, 1, 0)) +parts += handrail((-12.2, 2.70, LAB_Z - 0.4), (-1, 0, 0), 1.4, (0, 1, 0)) +parts.append(box((-12.9, 1.9, LAB_Z + 1.0), (0.5, 0.35, 0.3), "FITTING")) # EVA light/camera box +finish(parts, "WENTIAN_AIRLOCK", air_c, root) + +# Mengtian (port, +X): body + payload airlock (cargo airlock, nadir side) +lab("MENGTIAN", 1) +pa_c = V(12.9, -1.5, LAB_Z) +parts = [box(pa_c, (2.6, 1.9, 2.4), "HULL")] +parts.append(box((12.9, -2.5, LAB_Z), (2.2, 0.1, 2.0), "DOCK")) # outer hatch +for dx in (1.15, -1.15): # hatch frame + parts.append(box((12.9 + dx, -2.46, LAB_Z), (0.12, 0.1, 2.3), "FITTING")) +for dz in (1.15, -1.15): + parts.append(box((12.9, -2.46, LAB_Z + dz), (2.4, 0.1, 0.12), "FITTING")) +for dz in (0.9, -0.9): # edge rails + parts.append(box((12.9, -0.9, LAB_Z + dz * 1.33), (2.6, 0.08, 0.08), "FITTING")) +parts += handrail((14.18, -1.2, LAB_Z - 0.7), (0, 0, 1), 1.4, (1, 0, 0)) +finish(parts, "MENGTIAN_PAYLOAD_AIRLOCK", pa_c, root) + +# ======================================================================================= ARMS +ARM_RANGE = (-270, 270) + + +def housing(center, axis, r, length): + return cyl(center, axis, r, length, "ARM_JOINT", 16) + + +def boom(start, direction, r, length, segs=12): + """White boom with black end caps.""" + d = Vector(direction).normalized() + s = Vector(start) + cap = min(0.12, length * 0.2) + return [cyl_from(s, d, r, length, "ARM_WHITE", segs), + cyl_from(s, d, r + 0.015, cap, "ARM_JOINT", segs), + cyl_from(s + d * (length - cap), d, r + 0.015, cap, "ARM_JOINT", segs)] + + +# --- CMM: Tianhe's 10 m arm, base on the small cylinder near the node (zenith side), folded back along the hull +cx, cz = 0.5, 3.6 +y_hull = math.sqrt(SC_R ** 2 - cx ** 2) +parts = [cyl_from((cx, y_hull - 0.1, cz), (0, 1, 0), 0.32, 1.9 - (y_hull - 0.1), "FITTING", 20)] +parts.append(ring((cx, 1.85, cz), (0, 1, 0), 0.3, 0.04, "ARM_JOINT", 20, 6)) +parts.append(ring((cx, y_hull + 0.05, cz), (0, 1, 0), 0.34, 0.05, "ARM_JOINT", 20, 6)) +finish(parts, "CMM_BASE", (cx, y_hull, cz), root) + +p = V(cx, 1.9, cz) +shr = joint("CMM_SHR", p, (0, 1, 0), "arm", ARM_RANGE, True, root) +finish([housing(p + V(0, 0.2, 0), (0, 1, 0), 0.28, 0.4)], "CMM_SEG_SHR", p, shr) + +p = V(cx, 2.3, cz) +shy = joint("CMM_SHY", p, (0, 0, 1), "arm", ARM_RANGE, True, shr) +finish([housing(p, (0, 0, 1), 0.28, 0.55), cyl_from(p, (0, 1, 0), 0.17, 0.4, "ARM_WHITE", 12)], "CMM_SEG_SHY", p, shy) + +p = V(cx, 2.7, cz) +shp = joint("CMM_SHP", p, (1, 0, 0), "arm", ARM_RANGE, True, shy) +parts = [housing(p, (1, 0, 0), 0.28, 0.55)] + boom(p, (0, 0, -1), 0.17, 4.5) # boom 1 (aft) +finish(parts, "CMM_BOOM_1", p, shp) + +p = V(cx, 2.7, cz - 4.5) +ep = joint("CMM_EP", p, (1, 0, 0), "arm", ARM_RANGE, True, shp) +parts = [housing(p, (1, 0, 0), 0.3, 0.6), cyl_from(p, (0, 1, 0), 0.17, 0.6, "ARM_WHITE", 12), + housing(p + V(0, 0.6, 0), (1, 0, 0), 0.3, 0.6)] + boom(p + V(0, 0.6, 0), (0, 0, 1), 0.17, 4.5) # boom 2 (fwd) +finish(parts, "CMM_BOOM_2", p, ep) + +p = V(cx, 3.3, cz) +wp = joint("CMM_WP", p, (1, 0, 0), "arm", ARM_RANGE, True, ep) +finish([housing(p, (1, 0, 0), 0.28, 0.55), cyl_from(p, (0, 0, 1), 0.15, 0.5, "ARM_WHITE", 12)], "CMM_SEG_WP", p, wp) + +p = V(cx, 3.3, cz + 0.5) +wy = joint("CMM_WY", p, (0, 1, 0), "arm", ARM_RANGE, True, wp) +finish([housing(p, (0, 1, 0), 0.28, 0.55), cyl_from(p, (0, 0, 1), 0.15, 0.5, "ARM_WHITE", 12)], "CMM_SEG_WY", p, wy) + +p = V(cx, 3.3, cz + 1.0) +wr = joint("CMM_WR", p, (0, 0, 1), "arm", ARM_RANGE, True, wy) +finish([cyl_from(p, (0, 0, 1), 0.26, 0.8, "FITTING", 20), cyl_from(p + V(0, 0, 0.8), (0, 0, 1), 0.2, 0.15, "DOCK", 20), + ring(p + V(0, 0, 0.4), (0, 0, 1), 0.26, 0.03, "ARM_JOINT", 20, 6), + box(p + V(0.3, 0, 0.35), (0.14, 0.14, 0.3), "ARM_JOINT")], # camera/light unit + "CMM_END_EFFECTOR", p, wr) + +# --- EMM: Wentian's 5 m arm, base on the working section (zenith side), folded along the lab +ex, ez = -6.0, LAB_Z +parts = [cyl_from((ex, LAB_R - 0.1, ez), (0, 1, 0), 0.2, 0.4, "FITTING", 16)] +parts.append(ring((ex, LAB_R + 0.25, ez), (0, 1, 0), 0.19, 0.03, "ARM_JOINT", 16, 6)) +finish(parts, "EMM_BASE", (ex, LAB_R, ez), root) + +p = V(ex, 2.3, ez) +eshr = joint("EMM_SHR", p, (0, 1, 0), "arm", ARM_RANGE, True, root) +finish([housing(p + V(0, 0.125, 0), (0, 1, 0), 0.17, 0.25)], "EMM_SEG_SHR", p, eshr) + +p = V(ex, 2.55, ez) +eshy = joint("EMM_SHY", p, (1, 0, 0), "arm", ARM_RANGE, True, eshr) +finish([housing(p, (1, 0, 0), 0.17, 0.35), cyl_from(p, (0, 1, 0), 0.1, 0.3, "ARM_WHITE", 10)], "EMM_SEG_SHY", p, eshy) + +p = V(ex, 2.85, ez) +eshp = joint("EMM_SHP", p, (0, 0, 1), "arm", ARM_RANGE, True, eshy) +finish([housing(p, (0, 0, 1), 0.17, 0.35)] + boom(p, (-1, 0, 0), 0.1, 2.0, 10), "EMM_BOOM_1", p, eshp) + +p = V(ex - 2.0, 2.85, ez) +eep = joint("EMM_EP", p, (0, 0, 1), "arm", ARM_RANGE, True, eshp) +parts = [housing(p, (0, 0, 1), 0.18, 0.38), cyl_from(p, (0, 1, 0), 0.1, 0.35, "ARM_WHITE", 10), + housing(p + V(0, 0.35, 0), (0, 0, 1), 0.18, 0.38)] + boom(p + V(0, 0.35, 0), (1, 0, 0), 0.1, 2.0, 10) +finish(parts, "EMM_BOOM_2", p, eep) + +p = V(ex, 3.2, ez) +ewp = joint("EMM_WP", p, (0, 0, 1), "arm", ARM_RANGE, True, eep) +finish([housing(p, (0, 0, 1), 0.17, 0.35), cyl_from(p, (1, 0, 0), 0.09, 0.3, "ARM_WHITE", 10)], "EMM_SEG_WP", p, ewp) + +p = V(ex + 0.3, 3.2, ez) +ewy = joint("EMM_WY", p, (0, 1, 0), "arm", ARM_RANGE, True, ewp) +finish([housing(p, (0, 1, 0), 0.17, 0.35), cyl_from(p, (1, 0, 0), 0.09, 0.3, "ARM_WHITE", 10)], "EMM_SEG_WY", p, ewy) + +p = V(ex + 0.6, 3.2, ez) +ewr = joint("EMM_WR", p, (1, 0, 0), "arm", ARM_RANGE, True, ewy) +finish([cyl_from(p, (1, 0, 0), 0.15, 0.5, "FITTING", 16), cyl_from(p + V(0.5, 0, 0), (1, 0, 0), 0.12, 0.1, "DOCK", 16), + ring(p + V(0.25, 0, 0), (1, 0, 0), 0.15, 0.02, "ARM_JOINT", 16, 6)], + "EMM_END_EFFECTOR", p, ewr) + +# ======================================================================================= VISITING VEHICLES +class Frame: + """Local vehicle frame: ea = vehicle axis pointing away from the station, ex = array direction (+X side), et = ex x ea.""" + + def __init__(self, origin, ea, ex=(1, 0, 0)): + self.o = Vector(origin) + self.ea = Vector(ea) + self.ex = Vector(ex) + self.et = self.ex.cross(self.ea) + + def pt(self, x, t, a): + return self.o + self.ex * x + self.et * t + self.ea * a + + def size(self, sx, st, sa): + # frames here are axis-aligned (signed permutations), so sizes just permute + v = Vector((abs(self.ex.x) * sx + abs(self.et.x) * st + abs(self.ea.x) * sa, + abs(self.ex.y) * sx + abs(self.et.y) * st + abs(self.ea.y) * sa, + abs(self.ex.z) * sx + abs(self.et.z) * st + abs(self.ea.z) * sa)) + return v + + def cell_side(self): + """Which side of a vehicle wing carries the cells: prefer zenith, then forward, then port.""" + return self.et if self.et.dot(V(0.3, 1.0, 0.6)) > 0 else -self.et + + +def vehicle_wing(f, piv, sx, wl, width, root_gap, frame_r=0.06): + """Common vehicle wing: boom, blanket (cells on f.cell_side()), rails, cross bars, root drive collar.""" + # the blanket is wl along f.ex, `width` along f.ea and 0.04 thick along f.et (its normal) + parts = [cyl_from(piv, f.ex * sx, frame_r, wl + root_gap, "ARRAY_FRAME", 8)] + pc = f.pt(sx * (1.4 + root_gap + wl / 2), 0, piv_a(f, piv)) + parts.append(wing_panel(pc, f.size(wl, 0.04, width), f.ex * sx, f.ea, f.cell_side())) + parts.append(box(pc, f.size(wl + 0.05, 0.08, 0.08), "ARRAY_FRAME")) + back = -f.cell_side() + for da in (width / 2, -width / 2): + parts.append(box(pc + f.ea * da, f.size(wl + 0.05, 0.06, 0.06), "ARRAY_FRAME")) + nbar = int(wl / 1.5) + for k in range(nbar + 1): + c = f.pt(sx * (1.4 + root_gap + k * wl / nbar), 0, piv_a(f, piv)) + back * 0.025 + parts.append(box(c, f.size(0.04, 0.03, width), "ARRAY_FRAME")) + parts.append(cyl_from(piv, f.ex * sx, 0.12, 0.2, "ARM_JOINT", 10)) + return parts + + +def piv_a(f, piv): + return (Vector(piv) - f.o).dot(f.ea) + + +def shenzhou(name, frame): + """Shenzhou: 9.25 m long, 2.8 m diameter, 17 m array span. Stack from the docking face: orbital module, + return capsule, service module (+ engine). Module proportions approximate.""" + f = frame + A = f.ea + parts = [cyl_from(f.pt(0, 0, 0), A, 0.9, 0.35, "DOCK", 32)] # docking collar + parts.append(cyl_from(f.pt(0, 0, 0.35), A, 1.12, 2.45, "HULL", 32)) # orbital module (to 2.8) + parts.append(cone_from(f.pt(0, 0, 2.8), A, 0.85, 1.25, 1.6, "CAPSULE", 32)) # return capsule (bell) + parts.append(cyl_from(f.pt(0, 0, 4.4), A, 1.25, 0.6, "FITTING", 32)) # heat shield rim + parts.append(cyl_from(f.pt(0, 0, 5.0), A, 1.4, 3.6, "HULL", 32)) # service module (to 8.6) + parts.append(cone_from(f.pt(0, 0, 8.6), A, 1.4, 1.1, 0.3, "MLI", 32)) + parts.append(cone_from(f.pt(0, 0, 8.9), A, 0.25, 0.4, 0.35, "DOCK", 16)) # main engine (to 9.25) + # detail: hatch ring on the collar, MLI collar on the orbital module, capsule band, thrusters, antennas + parts.append(ring(f.pt(0, 0, 0.08), -A, 0.78, 0.06, "DOCK")) + parts.append(cyl_from(f.pt(0, 0, 0.35), A, 1.13, 0.4, "MLI", 32)) + parts.append(band(f.pt(0, 0, 2.85), A, 0.86, "FITTING", 0.1, 0.03, 32)) + parts.append(band(f.pt(0, 0, 5.06), A, 1.4, "FITTING", 0.12, 0.035, 32)) + for (dx, dt) in ((1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)): + parts.append(box(f.pt(dx, dt, 8.3), (0.22, 0.22, 0.22), "FITTING")) + parts.append(cone_from(f.pt(dx, dt, 8.4), A, 0.04, 0.08, 0.25, "DOCK", 8)) + parts.append(cyl_from(f.pt(0, 1.1, 1.6), f.et, 0.025, 0.6, "FITTING", 6)) + parts.append(box(f.pt(0.6, -1.05, 1.8), (0.3, 0.3, 0.3), "FITTING")) + body = finish(parts, name, f.pt(0, 0, 0), root, vehicle=True) + # arrays: pivot on the service module hull, axis along the array (X), 2 wings, ~7.1 m x 1.9 m each + a_mid = 6.8 + for tag, sx in (("PORT", 1), ("STBD", -1)): + piv = f.pt(sx * 1.4, 0, a_mid) + j = joint(f"{name}_ARRAY_{tag}_ALPHA", piv, f.ex * sx, "alpha", (-180, 180), True, body) + wl = (17.0 - 2.8) / 2 + finish(vehicle_wing(f, piv, sx, wl, 1.9, 0.2), f"{name}_ARRAY_{tag}", piv, j) + return body + + +def tianzhou(name, frame): + """Tianzhou: 10.6 m long, 3.35 m diameter, 14.9 m array span. Cargo module then propulsion module. Approximate.""" + f = frame + A = f.ea + parts = [cyl_from(f.pt(0, 0, 0), A, 0.9, 0.35, "DOCK", 32)] + parts.append(cone_from(f.pt(0, 0, 0.35), A, 1.2, 1.675, 0.6, "MLI", 48)) + parts.append(cyl_from(f.pt(0, 0, 0.95), A, 1.675, 5.3, "HULL", 48)) # cargo module (to 6.25) + parts.append(cone_from(f.pt(0, 0, 6.25), A, 1.675, 1.4, 0.55, "MLI", 48)) + parts.append(cyl_from(f.pt(0, 0, 6.8), A, 1.4, 3.4, "MLI", 32)) # propulsion module (to 10.2) + parts.append(cone_from(f.pt(0, 0, 10.2), A, 1.4, 1.0, 0.2, "FITTING", 32)) + for (dx, dt) in ((0.6, 0.6), (-0.6, 0.6), (0.6, -0.6), (-0.6, -0.6)): + parts.append(cone_from(f.pt(dx, dt, 10.3), A, 0.12, 0.22, 0.3, "DOCK", 12)) # 4 engines (to 10.6) + # detail: hatch ring, collar rings, handrails on the cargo module, thruster pods, antenna + parts.append(ring(f.pt(0, 0, 0.08), -A, 0.78, 0.06, "DOCK")) + parts.append(band(f.pt(0, 0, 1.01), A, 1.675, "FITTING")) + parts.append(band(f.pt(0, 0, 6.19), A, 1.675, "FITTING")) + parts.append(band(f.pt(0, 0, 3.6), A, 1.675, "FITTING", 0.08, 0.03)) + for ang in (45, 135, 225, 315): + a = math.radians(ang) + off = f.ex * (1.66 * math.cos(a)) + f.et * (1.66 * math.sin(a)) + nrm = (f.ex * math.cos(a) + f.et * math.sin(a)) + parts += handrail(f.pt(0, 0, 2.0) + off, A, 1.4, nrm) + parts += handrail(f.pt(0, 0, 4.3) + off, A, 1.4, nrm) + for (dx, dt) in ((1.3, 1.3), (-1.3, 1.3), (1.3, -1.3), (-1.3, -1.3)): + parts.append(box(f.pt(dx, dt, 9.6), (0.26, 0.26, 0.26), "FITTING")) + parts.append(cone_from(f.pt(dx, dt, 9.75), A, 0.05, 0.09, 0.25, "DOCK", 8)) + parts.append(cyl_from(f.pt(0, 1.65, 1.5), f.et, 0.025, 0.4, "FITTING", 6)) + body = finish(parts, name, f.pt(0, 0, 0), root, vehicle=True) + a_mid = 8.3 + for tag, sx in (("PORT", 1), ("STBD", -1)): + piv = f.pt(sx * 1.4, 0, a_mid) + j = joint(f"{name}_ARRAY_{tag}_ALPHA", piv, f.ex * sx, "alpha", (-180, 180), True, body) + wl = (14.9 - 3.35) / 2 + finish(vehicle_wing(f, piv, sx, wl, 2.3, 0.3), f"{name}_ARRAY_{tag}", piv, j) + return body + + +shenzhou("SHENZHOU_FORWARD", Frame((0, 0, Z_FWD), (0, 0, 1))) +shenzhou("SHENZHOU_NADIR", Frame((0, -2.0, NODE_C.z), (0, -1, 0))) +tianzhou("TIANZHOU_AFT", Frame((0, 0, Z_AFT), (0, 0, -1))) + +# ======================================================================================= CENTRE THE STATION +def world_bbox(objs): + lo = Vector((1e9, 1e9, 1e9)) + hi = Vector((-1e9, -1e9, -1e9)) + for o in objs: + for c in o.bound_box: + w = o.matrix_world @ Vector(c) + lo = Vector(map(min, lo, w)) + hi = Vector(map(max, hi, w)) + return lo, hi + + +bpy.context.view_layer.update() + + +def _parents(o): + out = [] + while o.parent is not None: + o = o.parent + out.append(o) + return out + + +def is_vehicle_part(o): + return o in VEHICLE_MESHES or any(p in VEHICLE_MESHES for p in _parents(o)) + + +station = [o for o in ALL_MESHES if not is_vehicle_part(o)] +lo_b, hi_b = world_bbox(station) +centre_b = (lo_b + hi_b) / 2 +root.location = -centre_b +bpy.context.view_layer.update() +lo_all, hi_all = world_bbox(ALL_MESHES) + + +def g(v): # Blender -> glTF for reporting + return [round(v.x, 3), round(v.z, 3), round(-v.y, 3)] + + +def g_box(lo, hi): + a, b = g(lo), g(hi) + return {"min": [min(x, y) for x, y in zip(a, b)], "max": [max(x, y) for x, y in zip(a, b)]} + + +station_box = g_box(lo_b, hi_b) +all_box = g_box(lo_all, hi_all) +root_translation = g(root.location) +log("station bbox (glTF, before centring):", station_box) +log("root translation (glTF):", root_translation) + +# triangle count +tris = 0 +for o in ALL_MESHES: + o.data.calc_loop_triangles() + tris += len(o.data.loop_triangles) +log("meshes:", len(ALL_MESHES), "joints/empties:", len(JOINTS), "triangles:", tris) + +# ======================================================================================= EXPORT +bpy.ops.object.select_all(action="DESELECT") +export_kwargs = dict( + filepath=GLB, + export_format="GLB", + export_yup=True, + export_extras=True, + export_apply=True, + export_animations=False, + export_skins=False, + export_cameras=False, + export_lights=False, + export_materials="EXPORT", + export_normals=True, + export_tangents=False, + export_texcoords=True, + export_image_format="WEBP", + export_image_quality=82, + use_selection=False, + use_active_collection=True, + export_draco_mesh_compression_enable=True, # like iss.glb (KHR_draco_mesh_compression) + export_draco_mesh_compression_level=6, + export_draco_position_quantization=14, + export_draco_normal_quantization=10, + export_draco_texcoord_quantization=14, +) +try: + bpy.ops.export_scene.gltf(**export_kwargs) +except TypeError as e: + log("export kwargs rejected, retrying without the unknown ones:", e) + props = set(bpy.ops.export_scene.gltf.get_rna_type().properties.keys()) + bpy.ops.export_scene.gltf(**{k: v for k, v in export_kwargs.items() if k in props}) + + +def glb_fix_extras(path): + """IDProperties cannot hold null: rewrite rangeDeg to null on dock nodes, as the contract asks.""" + with open(path, "rb") as fh: + data = fh.read() + magic, version, length = struct.unpack_from("} [env] + * @returns {boolean} + */ +export function issTelemetryEnabled(env = process.env) { + return String(env.ISS_TELEMETRY_ENABLED || '').trim() === '1'; +} + +/** + * The feed's time stamp as epoch milliseconds. The feed counts hours from the + * start of the day before January 1st (day of year × 24 + hours of the day), + * with no year; the year is taken from `nowMs`, stepping back one when that + * would put the stamp in the future (a value last sent in December, read in + * January). + * @param {number} hours + * @param {number} nowMs + * @returns {number|null} + */ +export function issTelemetryTimeMs(hours, nowMs) { + if (!Number.isFinite(hours) || hours < 0) return null; + const year = new Date(nowMs).getUTCFullYear(); + const at = Date.UTC(year, 0, 0) + hours * 3_600_000; + // A day of slack for clock differences. + return at > nowMs + 86_400_000 + ? Date.UTC(year - 1, 0, 0) + hours * 3_600_000 + : at; +} + +/** + * Decode one TLCP update line, `U,,,`, against + * the item's previous field values. Fields are `|`-separated and + * percent-encoded: an empty field is unchanged, `#` is null, `$` is the empty + * string and `^n` stands for n unchanged fields. + * @param {string} line + * @param {(item: number) => Array|undefined} previousOf + * @param {number} fieldCount + * @returns {{item: number, fields: Array}|null} Null for a line + * that is not a well-formed update. + */ +export function parseTlcpUpdate(line, previousOf, fieldCount) { + if (!line.startsWith('U,')) return null; + const second = line.indexOf(',', 2); + const third = second < 0 ? -1 : line.indexOf(',', second + 1); + if (third < 0) return null; + const item = Number(line.slice(second + 1, third)); + if (!Number.isInteger(item) || item < 1) return null; + const previous = previousOf(item) ?? []; + const fields = []; + for (const raw of line.slice(third + 1).split('|')) { + if (fields.length >= fieldCount) return null; + if (raw === '') fields.push(previous[fields.length] ?? null); + else if (raw === '#') fields.push(null); + else if (raw === '$') fields.push(''); + else if (raw[0] === '^') { + const run = Number(raw.slice(1)); + if (!Number.isInteger(run) || run < 1 || fields.length + run > fieldCount) + return null; + for (let i = 0; i < run; i++) + fields.push(previous[fields.length] ?? null); + } else { + try { + fields.push(decodeURIComponent(raw)); + } catch { + return null; + } + } + } + return fields.length === fieldCount ? { item, fields } : null; +} + +/** + * The relay: the connection's lifecycle and the snapshot it serves. It owns + * no timers; the caller drives `tick()` every few seconds. + * @param {{createSocket: () => object|null, now?: () => number}} options + * `createSocket` opens the feed and returns a `ws`-style socket (`on`, + * `send`, `terminate`), or null when no socket can be made. + */ +export function createIssTelemetryRelay({ createSocket, now = Date.now }) { + /** @type {Map} */ + const values = new Map(); + /** Per item index, the raw field values the next update is decoded against. */ + const fields = new Map(); + let socket = null; + /** Bumped on every connect and dispose, so a dead socket's events are ignored. */ + let generation = 0; + let lastDemandAt = null; + let lastFrameAt = null; + let signalAt = null; + let signalClass = null; + let failures = 0; + let retryAt = 0; + let unavailable = false; + /** When the live socket was opened, or null without one. */ + let connectedAt = null; + + function drop() { + generation += 1; + const old = socket; + socket = null; + connectedAt = null; + fields.clear(); + // A replacement session must rebuild both its joint snapshot and signal + // credit; a new clock tick cannot make the old session's angles live. + values.clear(); + signalAt = null; + signalClass = null; + try { + old?.terminate?.(); + } catch { + // A socket that will not terminate is abandoned; the generation guard + // keeps its events out. + } + } + + function fail() { + drop(); + const wait = + RETRY_LADDER_MS[Math.min(failures, RETRY_LADDER_MS.length - 1)]; + failures += 1; + retryAt = now() + wait; + } + + function onLine(line) { + if (line.startsWith('CONOK,')) { + socket?.send( + `control\r\nLS_reqId=1&LS_op=add&LS_subId=1&LS_mode=MERGE&LS_group=${encodeURIComponent( + ISS_TELEMETRY_ITEMS.join(' '), + )}&LS_schema=${encodeURIComponent(FEED_FIELDS.join(' '))}&LS_snapshot=true`, + ); + return; + } + // The session was refused, ended, or asks to be re-bound: start over. + if (/^(CONERR|END|LOOP|REQERR),/.test(line)) { + fail(); + return; + } + const update = parseTlcpUpdate( + line, + (item) => fields.get(item), + FEED_FIELDS.length, + ); + if (!update) return; + const name = ISS_TELEMETRY_ITEMS[update.item - 1]; + if (!name) return; + fields.set(update.item, update.fields); + if (connectedAt !== null && now() - connectedAt >= STABLE_SESSION_MS) + failures = 0; + const [stamp, raw, statusClass] = update.fields; + const at = now(); + if (name === SIGNAL_ITEM) { + signalAt = at; + signalClass = statusClass; + return; + } + const value = raw === null || raw === '' ? Number.NaN : Number(raw); + if (!Number.isFinite(value)) return; + values.set(name, { + value, + at: + stamp === null || stamp === '' + ? null + : issTelemetryTimeMs(Number(stamp), at), + }); + } + + function connect() { + let opened; + try { + opened = createSocket(); + } catch { + opened = null; + } + if (!opened) { + unavailable = true; + return; + } + unavailable = false; + generation += 1; + const mine = generation; + socket = opened; + connectedAt = now(); + lastFrameAt = now(); + opened.on('open', () => { + if (mine !== generation) return; + opened.send( + `create_session\r\nLS_adapter_set=${FEED_ADAPTER_SET}&LS_cid=${FEED_CLIENT_ID}&LS_send_sync=false&LS_cause=api`, + ); + }); + opened.on('message', (data) => { + if (mine !== generation) return; + // Nothing the feed sends may take the server down. + try { + if (data?.length > MAX_FRAME_BYTES) return; + lastFrameAt = now(); + for (const line of String(data).split('\r\n')) { + if (mine !== generation) return; + if (line) onLine(line); + } + } catch { + fail(); + } + }); + const lost = () => { + if (mine === generation) fail(); + }; + opened.on('error', lost); + opened.on('close', lost); + } + + /** Whether anyone asked recently enough to keep the connection. */ + function wanted() { + return lastDemandAt !== null && now() - lastDemandAt < IDLE_MS; + } + + /** + * Housekeeping, every few seconds: close when idle, recycle a silent + * socket, retry a failed one. + * @returns {boolean} False once there is nothing left to watch. + */ + function tick() { + if (!wanted()) { + dispose(); + return false; + } + if (socket && now() - lastFrameAt > SILENCE_MS) fail(); + if (!socket && !unavailable && now() >= retryAt) connect(); + return true; + } + + /** Record that a browser asked, opening the connection if it is closed. */ + function demand() { + lastDemandAt = now(); + if (!socket && !unavailable && now() >= retryAt) connect(); + } + + function status() { + if (unavailable) return 'unavailable'; + if (!socket) return 'reconnecting'; + if (signalAt === null) return 'connecting'; + return signalClass === SIGNAL_CLASS && now() - signalAt < SIGNAL_STALE_MS + ? 'live' + : 'no-signal'; + } + + /** The body served to browsers: each item's `[value, epoch ms it was true at]`. */ + function snapshot() { + const items = {}; + for (const [name, { value, at }] of values) items[name] = [value, at]; + return { configured: true, status: status(), generatedAt: now(), items }; + } + + /** Close the connection and forget what it said. */ + function dispose() { + drop(); + values.clear(); + lastDemandAt = null; + signalAt = null; + signalClass = null; + failures = 0; + retryAt = 0; + unavailable = false; + } + + return { demand, tick, snapshot, dispose }; +} + +let webSocketImpl; + +/** + * Load `ws` once, lazily: the vessel feed's socket library, so a missing + * optional dependency turns this relay off instead of breaking the server. + * @returns {Function|null} + */ +function loadWebSocket() { + if (webSocketImpl !== undefined) return webSocketImpl; + try { + webSocketImpl = createRequire(import.meta.url)('ws'); + } catch { + webSocketImpl = null; + console.warn( + '[ISS telemetry] `ws` is unavailable; the telemetry relay is off.', + ); + } + return webSocketImpl; +} + +function json(res, status, body) { + res.writeHead(status, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + }); + res.end(JSON.stringify(body)); +} + +/** + * The Vite plugin that mounts the relay's route. + * @param {{env?: Record, createSocket?: () => object|null, + * now?: () => number}} [options] Test seams; the defaults read the process + * environment at request time and open the real feed. + */ +export function issTelemetryProxy({ + env, + createSocket = () => { + const WebSocket = loadWebSocket(); + // `ws` buffers a whole frame before handing it over, up to 100 MiB by + // default: the frame cap applies on the socket, not only after it. + return WebSocket + ? new WebSocket(FEED_URL, FEED_PROTOCOL, { + maxPayload: MAX_FRAME_BYTES, + handshakeTimeout: HANDSHAKE_TIMEOUT_MS, + }) + : null; + }, + now = Date.now, +} = {}) { + const relay = createIssTelemetryRelay({ createSocket, now }); + // A browser polls every few seconds; this leaves room for several tabs. + const allow = makeRateLimiter({ windowMs: 60_000, max: 60, globalMax: 1200 }); + let timer = null; + + function stop() { + if (timer) clearInterval(timer); + timer = null; + relay.dispose(); + } + + function watch() { + if (timer) return; + timer = setInterval(() => { + if (relay.tick()) return; + clearInterval(timer); + timer = null; + }, TICK_MS); + timer.unref?.(); + } + + function handle(req, res) { + if (admitSameSiteKeyless(req, res)) return; + // The route is the one path: anything under it is not found, as JSON. + const path = String(req.url ?? '/').split('?')[0]; + if (path !== '/' && path !== '') { + json(res, 404, { error: 'Not Found' }); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + json(res, 405, { error: 'Method Not Allowed' }); + return; + } + // Read per request: the environment is loaded after this module is. + if (!issTelemetryEnabled(env ?? process.env)) { + json(res, 200, { configured: false }); + return; + } + // IPv6 clients fold to their /64, so one host cannot spread across it. + if (!allow(clientNetworkKey(req))) { + json(res, 429, { error: 'Too Many Requests' }); + return; + } + relay.demand(); + watch(); + json(res, 200, relay.snapshot()); + } + + function install(server) { + server.middlewares.use(ISS_TELEMETRY_ROUTE, handle); + // Vite restarts the server in-process while this module's state lives on. + server.httpServer?.on('close', stop); + } + + return { + name: 'iss-telemetry-proxy', + configureServer: install, + configurePreviewServer: install, + // Middleware mode has no httpServer to hang 'close' on. + closeBundle: stop, + }; +} diff --git a/server/providers/space/issTelemetry.test.mjs b/server/providers/space/issTelemetry.test.mjs new file mode 100644 index 0000000000..a5a40dc8b5 --- /dev/null +++ b/server/providers/space/issTelemetry.test.mjs @@ -0,0 +1,430 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + ISS_TELEMETRY_ITEMS, + ISS_TELEMETRY_ROUTE, + createIssTelemetryRelay, + issTelemetryEnabled, + issTelemetryProxy, + issTelemetryTimeMs, + parseTlcpUpdate, +} from './issTelemetry.js'; + +/** A `ws`-shaped socket the test drives by hand. */ +function fakeSocket() { + const handlers = {}; + return { + sent: [], + terminated: false, + on(event, handler) { + handlers[event] = handler; + }, + send(text) { + this.sent.push(text); + }, + terminate() { + this.terminated = true; + }, + emit(event, payload) { + handlers[event]?.(payload); + }, + }; +} + +const index = (name) => ISS_TELEMETRY_ITEMS.indexOf(name) + 1; + +/** A relay on a hand-moved clock, with every socket it opened. */ +function relayAt(startMs) { + const clock = { ms: startMs }; + const sockets = []; + const relay = createIssTelemetryRelay({ + createSocket: () => { + const socket = fakeSocket(); + sockets.push(socket); + return socket; + }, + now: () => clock.ms, + }); + return { relay, sockets, clock }; +} + +const NOV_13 = Date.UTC(2026, 10, 13, 11, 0, 0); +/** The feed's stamp for a moment: day of year × 24 + hours of that day. */ +const stampOf = (ms) => + (ms - Date.UTC(new Date(ms).getUTCFullYear(), 0, 0)) / 3_600_000; + +test('only ISS_TELEMETRY_ENABLED=1 switches the relay on', () => { + assert.equal(issTelemetryEnabled({}), false); + assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '' }), false); + assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '0' }), false); + assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: 'true' }), false); + assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: ' 1 ' }), true); +}); + +test("the feed's stamp is hours from the day before January 1st", () => { + // 13 November 2026 is day 317: 317 × 24 + 11 hours. + assert.equal(issTelemetryTimeMs(317 * 24 + 11, NOV_13), NOV_13); + assert.equal( + issTelemetryTimeMs(stampOf(NOV_13 - 5000), NOV_13), + NOV_13 - 5000, + ); + // A value last sent on 30 December, read on 2 January, belongs to last year. + const january = Date.UTC(2027, 0, 2, 0, 0, 0); + assert.equal( + issTelemetryTimeMs(364 * 24, january), + Date.UTC(2026, 11, 30, 0, 0, 0), + ); + assert.equal(issTelemetryTimeMs(Number.NaN, NOV_13), null); + assert.equal(issTelemetryTimeMs(-1, NOV_13), null); +}); + +test('an update line decodes against the previous field values', () => { + const previous = new Map([[3, ['7000.5', '10.25', '24']]]); + const of = (item) => previous.get(item); + assert.deepEqual(parseTlcpUpdate('U,1,3,7000.6|11.5|24', of, 3), { + item: 3, + fields: ['7000.6', '11.5', '24'], + }); + // Empty = unchanged, ^n = n unchanged, # = null, $ = empty string. + assert.deepEqual(parseTlcpUpdate('U,1,3,7000.7||', of, 3).fields, [ + '7000.7', + '10.25', + '24', + ]); + assert.deepEqual(parseTlcpUpdate('U,1,3,7000.8|^2', of, 3).fields, [ + '7000.8', + '10.25', + '24', + ]); + assert.deepEqual(parseTlcpUpdate('U,1,3,#|$|24', of, 3).fields, [ + null, + '', + '24', + ]); + assert.deepEqual(parseTlcpUpdate('U,1,3,a%7Cb|1|24', of, 3).fields[0], 'a|b'); + // Not updates, or malformed ones. + for (const line of [ + 'PROBE', + 'SUBOK,1,23,3', + 'U,1', + 'U,1,x,1|2|3', + 'U,1,0,1|2|3', + 'U,1,3,1|2', + 'U,1,3,1|2|3|4', + 'U,1,3,^9', + 'U,1,3,%E0%A4%A|1|24', + ]) + assert.equal(parseTlcpUpdate(line, of, 3), null, line); +}); + +test('the relay opens on the first request, subscribes, and reports live values', () => { + const { relay, sockets, clock } = relayAt(NOV_13); + assert.equal(sockets.length, 0, 'nothing is contacted before a request'); + relay.demand(); + assert.equal(sockets.length, 1); + assert.equal(relay.snapshot().status, 'connecting'); + const socket = sockets[0]; + socket.emit('open'); + assert.match(socket.sent[0], /^create_session\r\nLS_adapter_set=ISSLIVE&/); + socket.emit( + 'message', + 'CONOK,S1,50000,5000,*\r\nSERVNAME,x\r\nCLIENTIP,192.0.2.1', + ); + assert.match( + socket.sent[1], + /^control\r\n.*LS_mode=MERGE.*LS_schema=TimeStamp%20Value%20Status\.Class/, + ); + assert.ok(socket.sent[1].includes('S0000004%20S0000003')); + + const stamp = stampOf(NOV_13 - 2000); + socket.emit( + 'message', + `U,1,${index('S0000004')},${stamp}|346.12|24\r\nU,1,${index('TIME_000001')},${stamp}|123|24`, + ); + let body = relay.snapshot(); + assert.equal(body.configured, true); + assert.equal(body.status, 'live'); + assert.deepEqual(body.items.S0000004, [346.12, NOV_13 - 2000]); + assert.equal(body.items.TIME_000001, undefined, 'the clock is not a joint'); + assert.equal(JSON.stringify(body).includes('192.0.2.1'), false); + + // A later update with an unchanged stamp field keeps the old stamp. + clock.ms += 1000; + socket.emit('message', `U,1,${index('S0000004')},|346.5|`); + body = relay.snapshot(); + assert.deepEqual(body.items.S0000004, [346.5, NOV_13 - 2000]); +}); + +test('no station clock tick for 20 s, or a clock without signal, is no-signal', () => { + const { relay, sockets, clock } = relayAt(NOV_13); + relay.demand(); + const socket = sockets[0]; + socket.emit('open'); + socket.emit('message', 'CONOK,S1,50000,5000,*'); + const clockLine = (cls) => + `U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|${cls}`; + socket.emit('message', clockLine('24')); + assert.equal(relay.snapshot().status, 'live'); + clock.ms += 19_000; + socket.emit('message', 'PROBE'); + assert.equal(relay.snapshot().status, 'live'); + clock.ms += 2_000; + assert.equal(relay.snapshot().status, 'no-signal'); + socket.emit('message', clockLine('1')); + assert.equal(relay.snapshot().status, 'no-signal'); + socket.emit('message', clockLine('24')); + assert.equal(relay.snapshot().status, 'live'); +}); + +test('a lost or silent connection is retried on a ladder, and stale events are ignored', () => { + const { relay, sockets, clock } = relayAt(NOV_13); + relay.demand(); + const first = sockets[0]; + first.emit('open'); + first.emit('close'); + assert.equal(first.terminated, true); + assert.equal(relay.snapshot().status, 'reconnecting'); + // Not before 5 s. + clock.ms += 4_000; + relay.demand(); + relay.tick(); + assert.equal(sockets.length, 1); + clock.ms += 1_000; + relay.demand(); + assert.equal(sockets.length, 2); + // The dead socket's late events change nothing. + first.emit('message', `U,1,${index('S0000004')},1|999|24`); + assert.equal(relay.snapshot().items.S0000004, undefined); + + // A second failure waits 15 s. + sockets[1].emit('error', new Error('x')); + clock.ms += 14_000; + relay.demand(); + assert.equal(sockets.length, 2); + clock.ms += 1_000; + relay.demand(); + assert.equal(sockets.length, 3); + + // A socket that goes silent for 30 s is recycled by the tick. + const third = sockets[2]; + third.emit('open'); + third.emit('message', 'CONOK,S1,50000,5000,*'); + clock.ms += 29_000; + relay.demand(); + relay.tick(); + assert.equal(third.terminated, false); + clock.ms += 2_000; + relay.demand(); + relay.tick(); + assert.equal(third.terminated, true); +}); + +test("a reconnect cannot mark the previous socket's joint samples live", () => { + const { relay, sockets, clock } = relayAt(NOV_13); + relay.demand(); + const first = sockets[0]; + first.emit('open'); + first.emit('message', 'CONOK,S1,50000,5000,*'); + const stamp = stampOf(clock.ms); + first.emit( + 'message', + `U,1,${index('S0000004')},${stamp}|17|24\r\n` + + `U,1,${index('TIME_000001')},${stamp}|1|24`, + ); + assert.equal(relay.snapshot().status, 'live'); + assert.deepEqual(relay.snapshot().items.S0000004, [17, clock.ms]); + + first.emit('close'); + assert.equal(relay.snapshot().status, 'reconnecting'); + clock.ms += 5_000; + relay.demand(); + assert.equal(sockets.length, 2); + assert.equal(relay.snapshot().status, 'connecting'); + assert.deepEqual(relay.snapshot().items, {}); + + const second = sockets[1]; + second.emit('open'); + second.emit('message', 'CONOK,S2,50000,5000,*'); + // The clock can return before any new joint snapshot is delivered. + second.emit( + 'message', + `U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|24`, + ); + assert.equal(relay.snapshot().status, 'live'); + assert.deepEqual( + relay.snapshot().items, + {}, + 'the new clock must not revive old joint angles', + ); + second.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|23|24`); + assert.deepEqual(relay.snapshot().items.S0000004, [23, clock.ms]); +}); +test('a refused or ended session starts over', () => { + for (const line of ['CONERR,2,x', 'END,31,x', 'LOOP,0', 'REQERR,1,17,x']) { + const { relay, sockets } = relayAt(NOV_13); + relay.demand(); + sockets[0].emit('open'); + sockets[0].emit('message', line); + assert.equal(sockets[0].terminated, true, line); + assert.equal(relay.snapshot().status, 'reconnecting', line); + } +}); + +test('with nobody asking for two minutes the connection closes and the values go', () => { + const { relay, sockets, clock } = relayAt(NOV_13); + relay.demand(); + const socket = sockets[0]; + socket.emit('open'); + socket.emit('message', 'CONOK,S1,50000,5000,*'); + socket.emit('message', `U,1,${index('S0000003')},${stampOf(clock.ms)}|14|24`); + clock.ms += 119_000; + socket.emit('message', 'PROBE'); + assert.equal(relay.tick(), true); + assert.equal(socket.terminated, false); + clock.ms += 2_000; + assert.equal(relay.tick(), false); + assert.equal(socket.terminated, true); + assert.deepEqual(relay.snapshot().items, {}); + // The next request opens a fresh connection. + relay.demand(); + assert.equal(sockets.length, 2); +}); + +test('an oversized or malformed frame is dropped without taking the relay down', () => { + const { relay, sockets } = relayAt(NOV_13); + relay.demand(); + const socket = sockets[0]; + socket.emit('open'); + socket.emit('message', 'CONOK,S1,50000,5000,*'); + socket.emit('message', { length: 10_000_000 }); + socket.emit('message', `U,1,${index('S0000004')},1|not-a-number|24`); + socket.emit('message', 'U,1,999,1|2|24'); + assert.deepEqual(relay.snapshot().items, {}); + assert.equal(socket.terminated, false); +}); + +test('without a socket library the relay says unavailable', () => { + const relay = createIssTelemetryRelay({ createSocket: () => null }); + relay.demand(); + assert.equal(relay.snapshot().status, 'unavailable'); +}); + +/** Mount the plugin on a fake Connect stack and return a request function. */ +function install(plugin, preview = false) { + const routes = new Map(); + plugin[preview ? 'configurePreviewServer' : 'configureServer']({ + middlewares: { use: (route, handler) => routes.set(route, handler) }, + }); + return (method = 'GET', headers = {}, url = '/') => { + const res = { + headers: {}, + writeHead(status, headers) { + Object.assign(this, { status, headers }); + }, + setHeader(name, value) { + this.headers[name] = value; + }, + end(body) { + this.body = body; + this.status ??= this.statusCode; + }, + }; + routes.get(ISS_TELEMETRY_ROUTE)({ url, method, headers, socket: {} }, res); + return res; + }; +} + +test('the route is off by default and never opens the feed', () => { + let opened = 0; + const plugin = issTelemetryProxy({ + env: {}, + createSocket: () => { + opened += 1; + return fakeSocket(); + }, + }); + assert.equal(typeof plugin.configurePreviewServer, 'function'); + for (const preview of [false, true]) { + const res = install(plugin, preview)(); + assert.equal(res.status, 200); + assert.deepEqual(JSON.parse(res.body), { configured: false }); + assert.equal(res.headers['Cache-Control'], 'no-store'); + } + assert.equal(opened, 0); +}); + +test('switched on, the route opens the feed once and serves the snapshot', () => { + const sockets = []; + const plugin = issTelemetryProxy({ + env: { ISS_TELEMETRY_ENABLED: '1' }, + createSocket: () => { + const socket = fakeSocket(); + sockets.push(socket); + return socket; + }, + now: () => NOV_13, + }); + const request = install(plugin); + try { + const first = JSON.parse(request().body); + assert.equal(first.configured, true); + assert.equal(first.status, 'connecting'); + request(); + assert.equal(sockets.length, 1, 'one connection for every request'); + assert.equal(request('POST').status, 405); + const unknown = request('GET', {}, '/anything'); + assert.equal(unknown.status, 404); + assert.deepEqual(JSON.parse(unknown.body), { error: 'Not Found' }); + assert.equal(request('GET', {}, '/?t=1').status, 200, 'a query is fine'); + assert.equal( + request('GET', { 'sec-fetch-site': 'cross-site' }).status, + 403, + ); + // Sixty requests a minute from one client, then 429. + let limited = 0; + for (let i = 0; i < 70; i++) if (request().status === 429) limited += 1; + assert.ok(limited > 0); + } finally { + plugin.closeBundle(); + } + assert.equal(sockets[0].terminated, true); +}); + +test('a session that keeps ending soon after its snapshot climbs the retry ladder', () => { + const { relay, sockets, clock } = relayAt(NOV_13); + relay.demand(); + /** The current socket opens, sends a snapshot update, then ends. */ + const shortSession = () => { + const socket = sockets.at(-1); + socket.emit('open'); + socket.emit('message', 'CONOK,S1,50000,5000,*'); + socket.emit( + 'message', + `U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`, + ); + socket.emit('message', 'END,41,session closed'); + }; + // Each wait is the next step: 5 s, 15 s, 60 s, then 5 minutes. + for (const wait of [5_000, 15_000, 60_000, 300_000, 300_000]) { + shortSession(); + const before = sockets.length; + clock.ms += wait - 1_000; + relay.demand(); + assert.equal(sockets.length, before, `not before ${wait / 1000} s`); + clock.ms += 1_000; + relay.demand(); + assert.equal(sockets.length, before + 1, `again after ${wait / 1000} s`); + } + // A session that runs a minute before its updates brings the ladder down. + const socket = sockets.at(-1); + socket.emit('open'); + socket.emit('message', 'CONOK,S1,50000,5000,*'); + clock.ms += 60_000; + relay.demand(); + socket.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`); + socket.emit('message', 'END,41,session closed'); + const before = sockets.length; + clock.ms += 5_000; + relay.demand(); + assert.equal(sockets.length, before + 1, 'back to 5 s'); +}); diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.js index ed6821edda..204d5653c6 100644 --- a/src/app/constructCatalog.js +++ b/src/app/constructCatalog.js @@ -126,6 +126,7 @@ export function createApplicationCatalog({ }); const satellites = createApplicationSatellites({ source: sources.satellites, + ...(resolveAsset ? { resolveAsset } : {}), }); const catalog = createLayerCatalog( [ diff --git a/src/app/layers/overlayHost.js b/src/app/layers/overlayHost.js index fbaa428a07..cf3cfee68e 100644 --- a/src/app/layers/overlayHost.js +++ b/src/app/layers/overlayHost.js @@ -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, }); diff --git a/src/app/layers/satellites.js b/src/app/layers/satellites.js index 10eccb39f2..5312005c79 100644 --- a/src/app/layers/satellites.js +++ b/src/app/layers/satellites.js @@ -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, diff --git a/src/data/bhoteKoshiEmbeddedMedia.js b/src/data/bhoteKoshiEmbeddedMedia.js index 235c52ab30..160277bddf 100644 --- a/src/data/bhoteKoshiEmbeddedMedia.js +++ b/src/data/bhoteKoshiEmbeddedMedia.js @@ -5,6 +5,7 @@ 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'; @@ -101,59 +102,6 @@ let _xWidgetsPromise = null; let _facebookSdkPromise = null; let _facebookEmbedSequence = 0; let _cardSequence = 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; -} /** A trimmed clip follows provider time, never time spent loading its iframe. */ export function createTrimmedYouTubePlayback({ diff --git a/src/data/dataCredits.js b/src/data/dataCredits.js index 511b3bad9e..9ee9105e16 100644 --- a/src/data/dataCredits.js +++ b/src/data/dataCredits.js @@ -166,6 +166,30 @@ export const DATA_CREDITS = [ '(celestrak.org), ' + 'Dr. T.S. Kelso', }, + { + key: 'nasa-iss-model', + html: + 'ISS model: ' + + 'NASA 3D Resources (JSC IGOAL)', + }, + { + key: 'tiangong-model', + html: + "Tiangong model: made for God's Eye View; dimensions from " + + 'Wang, Zhang & Wang 2023 ' + + '(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 ' + + '(exterior cameras, ' + + 'live video and audio)', + }, { key: 'ucs-satellite-database', html: diff --git a/src/data/liveStreams.js b/src/data/liveStreams.js new file mode 100644 index 0000000000..3e530df701 --- /dev/null +++ b/src/data/liveStreams.js @@ -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|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} + */ +export function youtubeLivePlayerVars(origin) { + return { + autoplay: 1, + mute: 1, + playsinline: 1, + rel: 0, + enablejsapi: 1, + ...(origin ? { origin } : {}), + }; +} diff --git a/src/data/liveStreams.test.mjs b/src/data/liveStreams.test.mjs new file mode 100644 index 0000000000..fdb56c2b91 --- /dev/null +++ b/src/data/liveStreams.test.mjs @@ -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', + ); +}); diff --git a/src/data/youtubeApi.js b/src/data/youtubeApi.js new file mode 100644 index 0000000000..0b5f9e8740 --- /dev/null +++ b/src/data/youtubeApi.js @@ -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} 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; +} diff --git a/src/data/youtubeApi.test.mjs b/src/data/youtubeApi.test.mjs new file mode 100644 index 0000000000..6ffec7094f --- /dev/null +++ b/src/data/youtubeApi.test.mjs @@ -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); +}); diff --git a/src/data/youtubeLivePlayer.js b/src/data/youtubeLivePlayer.js new file mode 100644 index 0000000000..06adb33a2f --- /dev/null +++ b/src/data/youtubeLivePlayer.js @@ -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(); + }, + }; +} diff --git a/src/data/youtubeLivePlayer.test.mjs b/src/data/youtubeLivePlayer.test.mjs new file mode 100644 index 0000000000..eeedae1950 --- /dev/null +++ b/src/data/youtubeLivePlayer.test.mjs @@ -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 }]); +}); diff --git a/src/geo/frames.js b/src/geo/frames.js index 71aa3b84ce..20b78641e6 100644 --- a/src/geo/frames.js +++ b/src/geo/frames.js @@ -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), + }; +} diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index a21ba50c5f..247bbc8a05 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -4743,5 +4743,111 @@ "Finding it…": "جارٍ البحث عنه…", "No reading at this time": "لا توجد قراءة في هذا الوقت", "Last reading · {age}": "آخر قراءة · {age}", - "Find it": "اعثر عليه" + "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.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط." } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 19e2c44d82..c3a47bfff1 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -4319,5 +4319,111 @@ "Finding it…": "Wird gesucht…", "No reading at this time": "Zu dieser Zeit kein Messwert", "Last reading · {age}": "Letzter Stand · {age}", - "Find it": "Finden" + "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." } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index f7af0945a9..71344d6280 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -4425,5 +4425,111 @@ "Finding it…": "Buscando…", "No reading at this time": "Sin lectura a esta hora", "Last reading · {age}": "Última lectura · {age}", - "Find it": "Encontrar" + "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." } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 83371618bd..6167dcdf72 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -4425,5 +4425,111 @@ "Finding it…": "Recherche…", "No reading at this time": "Aucune donnée à cette heure", "Last reading · {age}": "Dernière donnée · {age}", - "Find it": "Retrouver" + "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." } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 8fffebdc2d..6eddcd9f5c 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -4425,5 +4425,111 @@ "Finding it…": "מחפש…", "No reading at this time": "אין קריאה בזמן הזה", "Last reading · {age}": "קריאה אחרונה · {age}", - "Find it": "מצא" + "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.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד." } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 0894a26b95..9c263d0b01 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -4425,5 +4425,111 @@ "Finding it…": "Ricerca in corso…", "No reading at this time": "Nessun dato a quest'ora", "Last reading · {age}": "Ultimo dato · {age}", - "Find it": "Trova" + "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." } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 2912466cc6..90ac90519c 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -4213,5 +4213,111 @@ "Finding it…": "検索中…", "No reading at this time": "この時刻のデータなし", "Last reading · {age}": "最終データ・{age}", - "Find it": "探す" + "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基のアンテナは動かず、アームは説明用にゆっくり動きます。" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index c67e58da14..20ba01856d 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -4425,5 +4425,111 @@ "Finding it…": "A procurar…", "No reading at this time": "Sem leitura nesta hora", "Last reading · {age}": "Última leitura · {age}", - "Find it": "Encontrar" + "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." } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index a5fff95f77..6ed7638d5d 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -4531,5 +4531,111 @@ "Finding it…": "Поиск…", "No reading at this time": "Нет данных на это время", "Last reading · {age}": "Последние данные · {age}", - "Find it": "Найти" + "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 в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации." } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 317f70d61d..565c953286 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -4319,5 +4319,111 @@ "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" + "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." } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index e57e61af76..f8eb54fd20 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -4531,5 +4531,111 @@ "Finding it…": "Пошук…", "No reading at this time": "Немає даних на цей час", "Last reading · {age}": "Останні дані · {age}", - "Find it": "Знайти" + "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 в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації." } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index f72c5e0b08..95ab6f9586 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -4213,5 +4213,111 @@ "Finding it…": "正在查找…", "No reading at this time": "此时无数据", "Last reading · {age}": "最后数据 · {age}", - "Find it": "查找" + "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 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 0e481762ed..cee8632919 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -4213,5 +4213,111 @@ "Finding it…": "正在查找…", "No reading at this time": "此時無數據", "Last reading · {age}": "最後數據 · {age}", - "Find it": "查找" + "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 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。" } diff --git a/src/i18n/same-as-english.json b/src/i18n/same-as-english.json index ec0b4b507b..0ef06b7611 100644 --- a/src/i18n/same-as-english.json +++ b/src/i18n/same-as-english.json @@ -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", diff --git a/src/layers/installations/controls.js b/src/layers/installations/controls.js index 8c8d729cbe..3bb7830d86 100644 --- a/src/layers/installations/controls.js +++ b/src/layers/installations/controls.js @@ -10,7 +10,13 @@ import { surfaceDistance } from '../../geo/geodesic.js'; import { toDegrees, toRadians } from '../../geo/vector.js'; import { cameraOf } from '../../render/rendererOf.js'; -export function createControls({ state: layerState, services, parts, source }) { +export function createControls({ + state: layerState, + services, + parts, + source, + overlayHost, +}) { const methods = { id: LAYER_ID, @@ -171,6 +177,29 @@ export function createControls({ state: layerState, services, parts, source }) { return id ? methods.getById(id) : null; }, + /** + * The mapped installation whose label box the shared overlay paints at a + * canvas position: what a click lands on from far out, where the dot is + * 7 px. Another layer's card or label that takes clicks there wins, so + * this answers null. The dot, outline and fill themselves are query port + * hits, read with {@link findByPick}. Null for anything else. + * @param {{x: number, y: number}|null|undefined} position Canvas CSS px. + * @returns {object|null} As {@link getById}. + */ + findAt(position) { + if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y)) + return null; + let top = null; + try { + top = overlayHost?.hitTest?.(position.x, position.y) ?? null; + } catch { + top = null; + } + if (top) return null; + const id = parts.namedMarkers?.labelAt?.(position) ?? null; + return id ? methods.getById(id) : null; + }, + /** * Select and frame a mapped installation from another contextual UI. * @param {string} id Source-backed installation id. diff --git a/src/layers/installations/labelBoxClick.test.mjs b/src/layers/installations/labelBoxClick.test.mjs new file mode 100644 index 0000000000..79e9153c35 --- /dev/null +++ b/src/layers/installations/labelBoxClick.test.mjs @@ -0,0 +1,83 @@ +// src/layers/installations/labelBoxClick.test.mjs — a click on a mapped +// installation's label box finds the site, read from the box the overlay +// painted for it, unless another layer's card or label that takes clicks is +// painted there. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createControls } from './controls.js'; + +const RECORD = Object.freeze({ + id: 'base', + kind: 'installation', + name: 'Base', + class: 'base', + latitude: 10, + longitude: 20, +}); + +const inside = (box, { x, y }) => + x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h; + +/** + * The installations controls over a fake overlay: `cards` are the hit rects + * of entries that take clicks (other layers'), `labels` the boxes painted + * for this layer's labels, which are not cards. + */ +function controlsWith({ cards = [], labels = {} }) { + const overlayHost = { + // As the world overlay does: the last painted card under the point wins. + hitTest(x, y) { + for (let i = cards.length - 1; i >= 0; i--) + if (inside(cards[i], { x, y })) + return { sourceId: cards[i].sourceId, entryId: cards[i].entryId }; + return null; + }, + }; + const namedMarkers = { + labelAt: (position) => + Object.keys(labels).find((id) => inside(labels[id], position)) ?? null, + }; + const controls = createControls({ + state: { + enabled: true, + records: [RECORD], + recordById: new Map([[RECORD.id, RECORD]]), + }, + services: {}, + parts: { + rendering: { installationSurfaceHeightM: () => 0 }, + namedMarkers, + }, + source: {}, + overlayHost, + }); + return controls.methods; +} + +const BASE_LABEL = { x: 100, y: 100, w: 80, h: 20 }; + +test("a click on the site's own label box finds the site", () => { + const methods = controlsWith({ labels: { base: BASE_LABEL } }); + assert.equal(methods.findAt({ x: 120, y: 110 })?.id, 'base'); + assert.equal(methods.findAt({ x: 10, y: 10 }), null, 'outside every box'); + assert.equal(methods.findAt(null), null); +}); + +test("another layer's card painted over the site's label keeps the click", () => { + const methods = controlsWith({ + labels: { base: BASE_LABEL }, + cards: [ + { sourceId: 'flights', entryId: 'abc123', x: 110, y: 105, w: 40, h: 12 }, + ], + }); + assert.equal( + methods.findAt({ x: 120, y: 110 }), + null, + 'the flight card is on top', + ); + assert.equal( + methods.findAt({ x: 170, y: 110 })?.id, + 'base', + 'past the card, the site is found', + ); +}); diff --git a/src/layers/installations/namedMarkers.js b/src/layers/installations/namedMarkers.js index 26e108ece7..e826ecf288 100644 --- a/src/layers/installations/namedMarkers.js +++ b/src/layers/installations/namedMarkers.js @@ -221,6 +221,11 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { // What `visit` hands out: the marker's id, position and whether // it is on this side of the horizon. point: { id: { installationId: record.id }, position, show: false }, + // Not an interactive overlay entry: those are cards that take every + // click from what is drawn under them, and an aircraft or vessel + // under a base's label must stay selectable. The label box still + // finds the site through its painted box (labelAt), which the + // layer's click claim reads where nothing else is drawn. entry: createInfrastructureOverlayEntry({ id: record.id, source: LAYER_ID, @@ -274,6 +279,32 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { visitor(marker.recordId, marker.point); } }, + /** + * The site whose label box the shared overlay painted at a canvas + * position in its last frame, or null: what a click lands on from far + * out, where the dot is 7 px. + * @param {{x: number, y: number}|null|undefined} position Canvas CSS px. + * @returns {string|null} The installation id. + */ + labelAt(position) { + if (!state.enabled) return null; + const x = position?.x; + const y = position?.y; + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + for (let i = ordered.length - 1; i >= 0; i--) { + const { recordId } = ordered[i]; + const box = overlayHost.paintRect?.(LAYER_ID, recordId); + if ( + box && + x >= box.x && + x <= box.x + box.w && + y >= box.y && + y <= box.y + box.h + ) + return recordId; + } + return null; + }, refresh, enable, hide, diff --git a/src/layers/installations/namedMarkers.test.mjs b/src/layers/installations/namedMarkers.test.mjs index e57b59496f..1d2361830b 100644 --- a/src/layers/installations/namedMarkers.test.mjs +++ b/src/layers/installations/namedMarkers.test.mjs @@ -9,15 +9,30 @@ import { fakeSceneFrame, fakeSceneQuery } from '../../testSupport/fakeCesiumScen import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js'; function setup(t) { - let labels = [], options, publications = 0, visible = false; + let labels = [], + options, + publications = 0, + visible = false; const overlayHost = { setEntries(id, entries, policy) { assert.equal(id, 'military-installations'); - labels = entries; options = policy; publications++; + labels = entries; + options = policy; + publications++; + }, + clearSource() { + labels = []; + }, + setVisible(_id, value) { + visible = value; + }, + // The boxes the overlay painted last frame, by entry id. + paintRect(id, entryId) { + assert.equal(id, 'military-installations'); + return boxes.get(entryId) ?? null; }, - clearSource() { labels = []; }, - setVisible(_id, value) { visible = value; }, }; + const boxes = new Map(); let x = -100; t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', () => new C.Cartesian2(x, 300)); const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), directionWC: new C.Cartesian3(0, 0, -1) }; @@ -33,14 +48,16 @@ function setup(t) { lifecycle.init(state.viewer); lifecycle.enable(); const records = [1, 2].map((n) => ({ id: `osm:military:w${n}`, name: `Site ${n}`, namedArea: true, areaM2: 100 / n, latitude: 0, longitude: 0, pointOnly: true })); const points = () => [...draw.sets.values()].find((set) => set.kind === 'points' && !set.disposed); - return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads }; + return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, boxes, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads }; } test('Contacts camera motion reprojects and declutters existing labels without source loads or primitive replacement', (t) => { const h = setup(t); h.markers.sync(h.records); assert.equal(h.markers.stats().pointsOnScreen, 0); - h.setX(600); h.camera.changed.raiseEvent(); h.camera.moveEnd.raiseEvent(); + h.setX(600); + h.camera.changed.raiseEvent(); + h.camera.moveEnd.raiseEvent(); assert.equal(h.markers.stats().pointsOnScreen, 2); assert.equal(h.labels.length, 2); assert.equal(h.options.collisionCapacity, 24); @@ -61,7 +78,8 @@ test('Contacts camera motion reprojects and declutters existing labels without s assert.equal(h.labels.length, 0); assert.equal(h.visible, false); h.state.records = h.records; - h.setX(600); h.lifecycle.enable(); + h.setX(600); + h.lifecycle.enable(); assert.equal(h.labels.length, 2); assert.equal(h.publications(), 5); h.lifecycle.destroy(h.state.viewer); @@ -73,13 +91,25 @@ test('Contacts camera motion reprojects and declutters existing labels without s test('wide named markers retain primitives until close polygons publish with the same identity', async (t) => { const { retainNamedHandoff } = await import('./ingestion.js'); const h = setup(t); - h.setX(600); h.markers.sync(h.records); + h.setX(600); + h.markers.sync(h.records); const first = h.labels[0]; const box = { west: -1, east: 1, south: -1, north: 1 }; h.markers.sync(retainNamedHandoff(h.records, [], box)); assert.equal(h.labels[0], first); assert.equal(first.title, 'Site 1'); - const polygon = { ...h.records[0], namedArea: false, name: 'Military area', pointOnly: false, footprint: [[0, 0], [0.1, 0], [0, 0.1], [0, 0]] }; + const polygon = { + ...h.records[0], + namedArea: false, + name: 'Military area', + pointOnly: false, + footprint: [ + [0, 0], + [0.1, 0], + [0, 0.1], + [0, 0], + ], + }; const handed = retainNamedHandoff(h.records, [polygon], box); assert.equal(handed.length, 2); assert.equal(handed[0].name, 'Site 1'); @@ -88,7 +118,11 @@ test('wide named markers retain primitives until close polygons publish with the assert.equal(h.labels[0], first); assert.equal(first.title, 'Site 1'); assert.equal(h.labels.length, 2, 'no duplicate title at handoff'); - assert.equal(retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 }).length, 0); + assert.equal( + retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 }) + .length, + 0, + ); h.lifecycle.destroy(h.state.viewer); }); @@ -98,7 +132,9 @@ test('canonical aliases transfer named marker ownership without replacing marker const parent = h.records[1]; h.markers.sync([parent]); let originalPoint; - h.markers.visit((_id, point) => { originalPoint = point; }); + h.markers.visit((_id, point) => { + originalPoint = point; + }); const label = h.labels[0]; for (const record of [ { ...parent, id: h.records[0].id, aliasIds: [parent.id], pointOnly: false }, @@ -120,17 +156,29 @@ test('canonical aliases transfer named marker ownership without replacing marker h.lifecycle.destroy(h.state.viewer); }); - test('the bounded host cohort ranks wide points and polygon titles by area', (t) => { const h = setup(t); - h.markers.sync(Array.from({ length: 600 }, (_, n) => ({ - ...h.records[0], id: `site:${n}`, name: `Site ${n}`, areaM2: n, - pointOnly: n % 2 === 0, - }))); + h.markers.sync( + Array.from({ length: 600 }, (_, n) => ({ + ...h.records[0], + id: `site:${n}`, + name: `Site ${n}`, + areaM2: n, + pointOnly: n % 2 === 0, + })), + ); assert.equal(h.labels.length, 512); assert.equal(h.labels[0].id, 'site:599'); assert.equal(h.labels.at(-1).id, 'site:88'); - assert.ok(h.labels.every((entry) => !entry.stateless && entry.horizonCull && entry.collisionGroup === 'ambient-card')); + assert.ok( + h.labels.every( + (entry) => + !entry.stateless && + entry.horizonCull && + entry.collisionGroup === 'ambient-card' && + entry.interactive === false, + ), + ); const first = h.labels[0]; const publications = h.publications(); for (let i = 0; i < 100; i++) { @@ -143,7 +191,6 @@ test('the bounded host cohort ranks wide points and polygon titles by area', (t) assert.equal(h.labels.length, 0); }); - test('wide and polygon titles use the Data Centers entry contract and persistent shared domain', (t) => { const h = setup(t); h.markers.sync([h.records[0], { ...h.records[1], pointOnly: false }]); @@ -151,12 +198,43 @@ test('wide and polygon titles use the Data Centers entry contract and persistent assert.equal(h.options.solveIntervalMs, undefined); assert.equal(h.options.maxVisible, 24); for (const entry of h.labels) { - const reference = createLocalInfrastructureOverlayEntry({ id: entry.id, layerId: 'military-installations', position: entry.position, properties: { name: entry.title }, priority: entry.priority, accent: entry.accent }); + const reference = createLocalInfrastructureOverlayEntry({ + id: entry.id, + layerId: 'military-installations', + position: entry.position, + properties: { name: entry.title }, + priority: entry.priority, + accent: entry.accent, + }); + // Not interactive: an interactive entry is a card that takes the click + // from an aircraft or vessel drawn under it. A click on the label box + // finds the site through its painted box (labelAt). assert.deepEqual(entry, { ...reference, selected: false }); } h.lifecycle.destroy(h.state.viewer); }); +test("labelAt finds the site whose label box was painted at a point, in CSS px", (t) => { + const h = setup(t); + h.markers.sync(h.records); + const [first, second] = h.records.map((record) => record.id); + h.boxes.set(first, { x: 100, y: 100, w: 80, h: 20 }); + h.boxes.set(second, { x: 300, y: 100, w: 60, h: 20 }); + assert.equal(h.markers.labelAt({ x: 120, y: 110 }), first); + assert.equal(h.markers.labelAt({ x: 360, y: 120 }), second, 'edges count'); + assert.equal(h.markers.labelAt({ x: 250, y: 110 }), null, 'between boxes'); + assert.equal(h.markers.labelAt(null), null); + assert.equal(h.markers.labelAt({ x: Number.NaN, y: 110 }), null); + // A site no longer marked has no label to find, even with a stale box. + h.markers.sync([h.records[1]]); + assert.equal(h.markers.labelAt({ x: 120, y: 110 }), null); + assert.equal(h.markers.labelAt({ x: 320, y: 110 }), second); + // Nor does a layer that is off. + h.state.enabled = false; + assert.equal(h.markers.labelAt({ x: 320, y: 110 }), null); + h.state.enabled = true; + h.lifecycle.destroy(h.state.viewer); +}); test('selection promotes exactly one entry and deselection restores that same label', (t) => { const h = setup(t); @@ -167,7 +245,7 @@ test('selection promotes exactly one entry and deselection restores that same la assert.equal(h.labels.length, 2); assert.equal(h.labels[0], original); assert.equal(original.variant, 'selected'); - assert.equal(h.labels.filter(e => e.selected).length, 1); + assert.equal(h.labels.filter((e) => e.selected).length, 1); assert.equal(h.options.maxVisible, 23); h.state.selectedId = null; h.markers.sync(h.records); @@ -180,14 +258,24 @@ test('selection promotes exactly one entry and deselection restores that same la test('Contacts can select a point outside the normal title cap or an unnamed polygon', (t) => { const h = setup(t); - const records = Array.from({ length: 520 }, (_, i) => ({ ...h.records[0], id: `site:${i}`, areaM2: 1000 - i })); - records.push({ ...h.records[0], id: 'unnamed', name: 'Military area', namedArea: false, pointOnly: false }); + const records = Array.from({ length: 520 }, (_, i) => ({ + ...h.records[0], + id: `site:${i}`, + areaM2: 1000 - i, + })); + records.push({ + ...h.records[0], + id: 'unnamed', + name: 'Military area', + namedArea: false, + pointOnly: false, + }); for (const id of ['site:519', 'unnamed']) { h.state.selectedId = id; h.markers.sync(records); assert.equal(h.labels[0].id, id); assert.equal(h.labels[0].variant, 'selected'); - assert.equal(h.labels.filter(e => e.selected).length, 1); + assert.equal(h.labels.filter((e) => e.selected).length, 1); assert.equal(h.labels.length, 512); } h.lifecycle.destroy(h.state.viewer); diff --git a/src/layers/installations/selection.js b/src/layers/installations/selection.js index 28a9301d0b..e8d8ad0144 100644 --- a/src/layers/installations/selection.js +++ b/src/layers/installations/selection.js @@ -1,5 +1,10 @@ import { inputFor } from '../../input/dispatcher.js'; -import { isUnderOtherCard } from '../../data/pickRegistry.js'; +import { + clickCard, + isUnderOtherCard, + registerClickClaim, + unregisterClickClaim, +} from '../../data/pickRegistry.js'; import { LAYER_ID } from './policy.js'; export function createSelection({ @@ -37,8 +42,39 @@ export function createSelection({ return layerState.selectedId === id; } + /** Whether a draw hit is one of this layer's: a dot, outline, fill or named marker. */ + function ownsHit(hit) { + return Boolean( + hit && + (hit.set === parts.namedMarkers?.setId || + parts.rendering.ownsSet(hit.set)), + ); + } + + /** + * A site's label box as the card on top of a click, for every layer's + * clickCard (the pick registry's click claim). Only where nothing another + * layer draws is under the click: an aircraft or vessel drawn under a + * base's label keeps its own click, while a label over the map, or over + * this layer's own dots and fills, takes it. Runs only where no card or + * label that takes clicks is painted on top. + * @param {object} event The shared dispatcher click. + * @returns {{sourceId: string, entryId: string}|null} + */ + function labelClickCard(event) { + if (!layerState.enabled || !event) return null; + if (event.topHit && !ownsHit(event.drawHit)) return null; + const id = + parts.namedMarkers?.labelAt?.(event.screenPosition ?? event.position) ?? + null; + return id && layerState.recordById.has(id) + ? { sourceId: LAYER_ID, entryId: id } + : null; + } + function installInteraction(viewer) { if (layerState.clickSubscription) return; + registerClickClaim(LAYER_ID, labelClickCard); const events = [ 'gev:entity-selected', 'gev:entity-selection-cleared', @@ -54,16 +90,20 @@ export function createSelection({ layerState.clickSubscription = input.onClick((event) => { if (!layerState.enabled) return; // Another layer's card or label painted on top takes the click: the item - // under it does not act, and the click is not empty space either. - if (isUnderOtherCard(event)) return; - // A site's dot, outline or fill, or a named marker: each draw item - // names its installation in its `meta`. + // under it does not act, and the click is not empty space either. A + // site's own label box is this layer's. + if (isUnderOtherCard(event, [LAYER_ID])) return; + // The site whose label box is at the click takes it where nothing + // another layer draws is under it (labelClickCard): from far out the + // click lands on the label, not the 7 px dot. Else a site's dot, + // outline or fill, or a named marker: each draw item names its + // installation in its `meta`. + const card = clickCard(event); const hit = event.drawHit; const id = - hit?.set === parts.namedMarkers?.setId || - parts.rendering.ownsSet(hit?.set) - ? hit.meta?.installationId - : null; + (card?.sourceId === LAYER_ID ? card.entryId : null) ?? + (ownsHit(hit) ? hit.meta?.installationId : null) ?? + null; if (id && layerState.recordById.has(id) && id !== layerState.selectedId) { selectRecord(id); } else if (layerState.selectedId) { @@ -82,6 +122,7 @@ export function createSelection({ destroy() { removeContextListeners?.(); removeContextListeners = null; + unregisterClickClaim(LAYER_ID); }, }; } diff --git a/src/layers/installations/selection.test.mjs b/src/layers/installations/selection.test.mjs index 7844afb3ba..a1636d2c28 100644 --- a/src/layers/installations/selection.test.mjs +++ b/src/layers/installations/selection.test.mjs @@ -7,7 +7,8 @@ import { createRendering } from './rendering.js'; import { createNamedMarkers, namedPointId } from './namedMarkers.js'; import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; import { fakeInput } from '../../input/testDoubles.mjs'; -import { setClickCardHitTest } from '../../data/pickRegistry.js'; +import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js'; +import { LAYER_ID } from './policy.js'; function harness(t) { const previousWindow = globalThis.window; @@ -60,6 +61,8 @@ function harness(t) { () => new Cesium.Cartesian2(640, 400), ); let labels = []; + // The boxes the overlay painted last frame for this layer's labels. + const boxes = new Map(); const services = { context, anchors: {}, @@ -82,6 +85,9 @@ function harness(t) { }, clearSource() {}, setVisible() {}, + paintRect(_id, entryId) { + return boxes.get(entryId) ?? null; + }, }, }; parts.rendering = createRendering(ctx); @@ -116,6 +122,7 @@ function harness(t) { draw, input, parts, + boxes, /** Click on what `pick` names, as the scene would pick it. */ click(value) { picked = value; @@ -258,3 +265,64 @@ test('a click on a site dot or its outline selects the site; another set does no h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } }); assert.equal(selectedNow(), false); }); + +test("a click on a site's label box selects it where nothing else is drawn under it", (t) => { + const h = harness(t); + h.state.selectedId = null; + context.clearSelectedEntityContextForLayer('military-installations'); + h.parts.rendering.renderRecords(); + // The card every layer reads for each click, as Context's bridge reads it. + const cards = []; + const offCards = h.input.input.onClick((event) => + cards.push(clickCard(event)), + ); + t.after(offCards); + // No label at the click and nothing picked: nothing is selected. + h.click(undefined); + h.assertSelected(false); + assert.equal(cards.at(-1), null); + // The site's label box at the click (CSS px) selects it; again releases it. + h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 }); + h.click(undefined); + h.assertSelected(true); + assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' }); + h.click(undefined); + h.assertSelected(false); + // Over the site's own named marker, the label still takes the click. + const setId = h.parts.namedMarkers.setId; + const item = h.draw.set(setId).items.get(namedPointId('base')); + h.click({ id: { set: setId, id: item.id, meta: item.meta } }); + h.assertSelected(true); + assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' }); + // An aircraft drawn under the label keeps its click: the label is no card + // there, so its own layer and Context can select it, and the site lets go. + h.click({ id: 'flight:abc123' }); + h.assertSelected(false); + assert.equal(cards.at(-1), null); + // Another layer's card painted over the label takes the click. + setClickCardHitTest(() => ({ sourceId: 'earthquake-card', entryId: 'ak1' })); + t.after(() => setClickCardHitTest(null)); + h.click(undefined); + h.assertSelected(false); + setClickCardHitTest(null); + // A layer that is off claims nothing. + h.state.enabled = false; + h.click(undefined); + assert.equal(cards.at(-1), null); + h.state.enabled = true; +}); + +test('destroy withdraws the label claim', (t) => { + const h = harness(t); + h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 }); + const cards = []; + const offCards = h.input.input.onClick((event) => + cards.push(clickCard(event)), + ); + t.after(offCards); + h.click(undefined); + assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' }); + h.selection.destroy(); + h.click(undefined); + assert.equal(cards.at(-1), null); +}); diff --git a/src/layers/satellites/cockpitSubject.js b/src/layers/satellites/cockpitSubject.js index e79e24f96e..63b1dd71da 100644 --- a/src/layers/satellites/cockpitSubject.js +++ b/src/layers/satellites/cockpitSubject.js @@ -9,6 +9,7 @@ import { tleEpochMs, } from './classes.js'; import { ISS_NORAD } from './policy.js'; +import { trackedStation } from './stationModels.js'; /** The layer id a satellite subject carries through Cockpit events and state. */ export const SATELLITE_COCKPIT_LAYER_ID = 'satellites'; @@ -261,6 +262,29 @@ export function createCockpitSubject({ state: layerState, parts }) { return out; }, + /** + * Where the Cockpit camera sits and looks when the subject is the + * station: a view from a point on the ISS model (issMounts.js) in place + * of the straight-down picture. The station offers several (from Nauka, + * from Zarya, from a docked vehicle), whichever of its entries is ridden. + * @param {string|null} [key] The view asked for; the first on offer when + * it is not given or not on offer. + * @returns {{position: object, direction: object, up: object, + * right: object, key: string, label: string, + * views: Array<{key: string, label: string}>}|null} Earth-fixed + * `{x, y, z}` vectors, the view shown and the views on offer; null for + * any other satellite, outside the Cockpit, or until the model has + * loaded. + */ + getCockpitMount(key = null) { + if (!_cockpitHeld()) return null; + // The station the subject belongs to; a station without views on its + // model (Tiangong) answers null, and the Cockpit keeps the nadir picture. + return ( + trackedStation(layerState, parts)?.model?._cockpitMount?.(key) ?? null + ); + }, + /** * Mark the satellite whose position the Cockpit camera occupies, or * release it. The hold applies while that satellite is tracked. diff --git a/src/layers/satellites/cockpitSubject.test.mjs b/src/layers/satellites/cockpitSubject.test.mjs index 43c33230e4..604b2fe309 100644 --- a/src/layers/satellites/cockpitSubject.test.mjs +++ b/src/layers/satellites/cockpitSubject.test.mjs @@ -631,3 +631,70 @@ test('the subject says whether its class may be ridden', () => { ]) assert.equal(subject(satelliteClass).enterable, true, satelliteClass); }); + +test('the station offers its mount only while the Cockpit rides it', async (t) => { + const f = await fixture(t); + const mount = { label: 'ZARYA' }; + // The ISS model part works the mount out (issModel.js, stationModel.js); + // this layer only decides when the Cockpit may have it, asking the part + // whose station the subject is (stationModels.js). + const modelPart = (offered) => ({ + key: 'iss', + norad: ISS_NORAD, + _updateStationModel() {}, + _destroyStationModel() {}, + _standsInFor: () => false, + _cockpitMount: () => offered, + }); + f.parts.stationModels = [modelPart(mount)]; + assert.equal(f.methods.getCockpitMount(), null, 'nothing tracked'); + f.track(ISS_NORAD); + f.nextFrame(); + assert.equal(f.methods.getCockpitMount(), null, 'tracked, not ridden'); + f.methods.setCockpitSubject(String(ISS_NORAD)); + assert.equal(f.methods.getCockpitMount(), mount); + // The view asked for is passed on; none asks for the first on offer. + const asked = []; + f.parts.stationModels = [ + { + ...modelPart(mount), + _cockpitMount(key) { + asked.push(key); + return mount; + }, + }, + ]; + f.methods.getCockpitMount('zarya'); + f.methods.getCockpitMount(); + assert.deepEqual(asked, ['zarya', null]); + // The model has nothing to offer: not loaded, or not the station. + f.parts.stationModels = [modelPart(null)]; + assert.equal(f.methods.getCockpitMount(), null); + delete f.parts.stationModels; + assert.equal(f.methods.getCockpitMount(), null); + // Another station's part is not asked for the ISS. + f.parts.stationModels = [{ ...modelPart(mount), norad: 48274 }]; + assert.equal(f.methods.getCockpitMount(), null); + f.parts.stationModels = [modelPart(mount)]; + f.methods.setCockpitSubject(null); + assert.equal(f.methods.getCockpitMount(), null, 'released'); +}); + +test('a satellite docked to the ISS draws no ring of its own: the ISS’s shows', async (t) => { + const f = await fixture(t); + f.track(COMPANION); + f.nextFrame(); + assert.equal(f.state._trackedDockedToIss, true); + assert.equal(f.ring(COMPANION), undefined, 'no second ring'); + assert.equal(f.ring(ISS_NORAD).show, true); + // The ISS's ring stands for it even with the stations class hidden. + f.methods.setParams({ classes: { stations: false } }); + assert.equal(f.ring(ISS_NORAD).show, true); + // Another satellite keeps its own ring; the ISS's goes with its class. + f.track(GPS); + f.nextFrame(); + assert.equal(f.state._trackedDockedToIss, false); + assert.ok(f.ring(GPS)); + assert.equal(f.ring(GPS).show, true); + assert.equal(f.ring(ISS_NORAD).show, false); +}); diff --git a/src/layers/satellites/controls.js b/src/layers/satellites/controls.js index 48e7430b3d..8959a2e662 100644 --- a/src/layers/satellites/controls.js +++ b/src/layers/satellites/controls.js @@ -9,6 +9,7 @@ import { mergeClassVisibility, } from './classes.js'; import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js'; +import { modelFor, trackedStation } from './stationModels.js'; export function createControls({ state: layerState, services, parts, source }) { const { isExplicitLayerStateOrigin } = services.layerState; @@ -64,7 +65,8 @@ export function createControls({ state: layerState, services, parts, source }) { /** * Whether the ISS's ring shows: orbits on, the layer drawing, and its - * class on or the ISS tracked (a tracked satellite keeps its ring). + * class on or the ISS tracked (a tracked satellite keeps its ring), also + * as an object docked to it, which draws no ring of its own. */ function _issOrbitVisible() { return ( @@ -72,7 +74,9 @@ export function createControls({ state: layerState, services, parts, source }) { layerState._enabled, layerState._params.showOrbits, ) && - (_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD) + (_classVisible(ISS_NORAD) || + layerState._trackedNorad === ISS_NORAD || + Boolean(layerState._trackedDockedToIss)) ); } @@ -253,6 +257,9 @@ export function createControls({ state: layerState, services, parts, source }) { // that card instead. Only members of the tracked cluster are affected — // unrelated nearby satellites are never suppressed. if (!isTracked && layerState._dockedCompanions.has(noradId)) continue; + // Up close a station is its 3D model: no mark on it, nor on what is + // docked to it. + if (modelFor(parts, noradId)?._visualPosition?.()) continue; // The Cockpit camera rides a held subject; a bracket on it would sit // on the lens. if (isTracked && parts.cockpit?._cockpitHeld()) continue; @@ -433,6 +440,18 @@ export function createControls({ state: layerState, services, parts, source }) { return result; }, + /** + * The keys the LIVE section matches streams by for the tracked + * satellite: a station is `station:` (`station:iss`, + * `station:tiangong`) whichever of its entries is tracked (the station, + * a module, a docked vehicle). + * @returns {string[]} + */ + getLiveSubjectKeys() { + const station = trackedStation(layerState, parts); + return station ? [`station:${station.key}`] : []; + }, + /** * Track a satellite by NORAD id (camera follow + orbit path + highlight), * same path as clicking its point. diff --git a/src/layers/satellites/index.js b/src/layers/satellites/index.js index e83316ead9..4191670dcd 100644 --- a/src/layers/satellites/index.js +++ b/src/layers/satellites/index.js @@ -7,13 +7,22 @@ import { createRendering } from './rendering.js'; import { createTracking } from './tracking.js'; import { createTesting } from './testing.js'; import { createInteraction } from './interaction.js'; +import { issStationDescription } from './issStation.js'; +import { createStationPanel } from './stationPanel.js'; +import { createIssModel } from './issModel.js'; +import { createTiangongModel } from './tiangongModel.js'; +import { tiangongStationDescription } from './tiangongStation.js'; import { createLifecycle } from './lifecycle.js'; import { createIngestion } from './ingestion.js'; import { createRecords } from './records.js'; import { createState } from './state.js'; /** Construct one layer with its own scene state and supplied application services. */ -export function createSatellitesLayer({ services, source }) { +export function createSatellitesLayer({ + services, + source, + resolveAsset = (url) => url, +}) { if (typeof source?.readGroup !== 'function') throw new TypeError('A satellites source is required'); const state = createState({ services }); @@ -25,6 +34,18 @@ export function createSatellitesLayer({ services, source }) { parts.orbits = createOrbits(context); parts.records = createRecords(context); parts.rendering = createRendering(context); + // The stations drawn as models up close; the other parts ask + // stationModels.js which station an entry belongs to. + parts.issModel = createIssModel({ ...context, resolveAsset }); + parts.tiangongModel = createTiangongModel({ ...context, resolveAsset }); + parts.stationModels = [parts.issModel, parts.tiangongModel]; + parts.stationPanel = createStationPanel({ + ...context, + stations: [ + issStationDescription(context), + tiangongStationDescription(context), + ], + }); parts.tracking = createTracking(context); parts.testing = createTesting(context); parts.interaction = createInteraction(context); @@ -35,6 +56,7 @@ export function createSatellitesLayer({ services, source }) { {}, parts.controls.methods, parts.cockpit.methods, + parts.stationPanel.methods, parts.lifecycle.methods, parts.ingestion.methods, { diff --git a/src/layers/satellites/interaction.js b/src/layers/satellites/interaction.js index 393fc072e7..b1f01dc85a 100644 --- a/src/layers/satellites/interaction.js +++ b/src/layers/satellites/interaction.js @@ -1,4 +1,5 @@ import { inputFor } from '../../input/dispatcher.js'; +import { modelHitNorad } from './stationModels.js'; import { onFollowChanged } from '../../data/followed.js'; export function createInteraction({ @@ -67,6 +68,18 @@ export function createInteraction({ parts.tracking._trackSatellite(noradId, { origin: 'user' }); return; } + // A station's 3D model (stationModel.js) names its station. A click + // on the tracked station's own model is already tracked; on another + // station's model it tracks that one. + const modelNorad = modelHitNorad(parts, hit); + if (modelNorad !== null) { + if (modelNorad === layerState._trackedNorad) return; + if (layerState._catalog.has(modelNorad)) { + parts.tracking._cancelPendingTrackingRestore(); + parts.tracking._trackSatellite(modelNorad, { origin: 'user' }); + return; + } + } // A pick that belongs to a sibling layer (plane, vessel, station, CCTV // camera…) is not "empty space" — leave OUR tracking (and crucially diff --git a/src/layers/satellites/issArticulation.js b/src/layers/satellites/issArticulation.js new file mode 100644 index 0000000000..e614ad2383 --- /dev/null +++ b/src/layers/satellites/issArticulation.js @@ -0,0 +1,834 @@ +import { sunPositionFixed } from '../../geo/celestial.js'; + +/** + * The ISS model's moving parts. NASA's file names its joints; the build keeps + * each one as a node of its own, with the parts it carries beneath it, all in + * the model's rest frame (glTF axes, meters: X port, Y zenith, Z forward), so + * a joint turns by rotating its node about `pivot`. + * + * By default the angles are computed from where the Sun is: the two alpha + * joints turn the outboard truss about the truss axis, each array's beta + * joint turns it about its mast, and the two radiator joints keep the + * radiators edge-on to the Sun. In the Earth's shadow the arrays feather: + * masts along the flight direction, edge into it. + * + * Where the server relays NASA's public telemetry (issTelemetry.js), the + * arrays, the radiators and one dish take their real angles from it instead, + * and fall back to the computed ones whenever it has nothing to say. + */ + +/** Alpha joints (SARJ): rotate about the truss, glTF X. */ +export const ISS_ALPHA_JOINTS = Object.freeze([ + Object.freeze({ node: 'PORT_ALPHA_ROT', pivot: [19.533, 0, 0] }), + Object.freeze({ node: 'STBD_ALPHA_ROT', pivot: [-19.533, 0, 0] }), +]); + +/** + * Beta joints (BGA): rotate about the mast, glTF Z at rest. `face` is the + * sign of the cell side's normal along X at rest (the roll-out arrays sit on + * that side). + */ +export const ISS_BETA_JOINTS = Object.freeze([ + Object.freeze({ + node: 'PORT_BETA_ROT_2A', + pivot: [36.7319, 0.7256, -3.0077], + face: -1, + }), + Object.freeze({ + node: 'PORT_BETA_ROT_4A', + pivot: [36.7319, -0.7258, 2.2332], + face: -1, + }), + Object.freeze({ + node: 'PORT_BETA_ROT_2B', + pivot: [53.223, -0.7196, 2.2335], + face: -1, + }), + Object.freeze({ + node: 'PORT_BETA_ROT_4B', + pivot: [53.2219, 0.7294, -3.0076], + face: -1, + }), + Object.freeze({ + node: 'STBD_BETA_ROT_1A', + pivot: [-36.6608, 0.7257, 3.0224], + face: 1, + }), + Object.freeze({ + node: 'STBD_BETA_ROT_3A', + pivot: [-36.6608, -0.7257, -2.2408], + face: 1, + }), + Object.freeze({ + node: 'STBD_BETA_ROT_1B', + pivot: [-53.2219, -0.7294, -2.2408], + face: 1, + }), + Object.freeze({ + node: 'STBD_BETA_ROT_3B', + pivot: [-53.2232, 0.722, 3.0223], + face: 1, + }), +]); + +/** Radiator joints (TRRJ): rotate about glTF Z; the panels face Y at rest. */ +export const ISS_RADIATOR_JOINTS = Object.freeze([ + Object.freeze({ node: 'PORT_TRRJ_GAMMA_ROT', pivot: [16.1287, 0, -7.4432] }), + Object.freeze({ node: 'STBD_TRRJ_GAMMA_ROT', pivot: [-16.1287, 0, -7.4432] }), +]); + +/** How fast a joint may turn on screen, radians per second of wall time. */ +export const ISS_JOINT_RATE = (12 * Math.PI) / 180; + +/** Below this the Sun is too close to a joint's axis to steer by it. */ +const MIN_STEER = 0.05; +const EARTH_RADIUS_M = 6_371_000; + +/** The signed difference b - a, wrapped to (-π, π]. */ +function wrap(delta) { + let d = delta % (2 * Math.PI); + if (d > Math.PI) d -= 2 * Math.PI; + if (d <= -Math.PI) d += 2 * Math.PI; + return d; +} + +/** Of `angle` and `angle + π`, the one nearer to `previous`. */ +function nearestHalfTurn(angle, previous) { + const flipped = angle + Math.PI; + return Math.abs(wrap(angle - previous)) <= Math.abs(wrap(flipped - previous)) + ? angle + : flipped; +} + +/** + * Whether a point is in the Earth's shadow, taken as a cylinder. + * @param {number[]} positionEcef Meters. + * @param {number[]} sunEcef Unit vector toward the Sun. + * @returns {boolean} + */ +export function issInShadow(positionEcef, sunEcef) { + const along = + positionEcef[0] * sunEcef[0] + + positionEcef[1] * sunEcef[1] + + positionEcef[2] * sunEcef[2]; + if (along >= 0) return false; + const off = Math.hypot( + positionEcef[0] - along * sunEcef[0], + positionEcef[1] - along * sunEcef[1], + positionEcef[2] - along * sunEcef[2], + ); + return off < EARTH_RADIUS_M; +} + +/** + * The Sun's direction on the model's glTF axes, from the flight axes the + * model is oriented by (x along-track, y orbit normal, z zenith). + * @param {number[]} sunEcef Unit vector toward the Sun, Earth-fixed. + * @param {{x:number[], y:number[], z:number[]}} axes + * @returns {number[]} [port, zenith, forward]. + */ +export function issSunInModelFrame(sunEcef, axes) { + const dot = (a) => a[0] * sunEcef[0] + a[1] * sunEcef[1] + a[2] * sunEcef[2]; + return [dot(axes.y), dot(axes.z), dot(axes.x)]; +} + +/** + * The joint angles that point the arrays at the Sun. + * @param {number[]} sun Unit vector toward the Sun on the model's glTF axes. + * @param {boolean} sunlit False in the Earth's shadow: the arrays feather. + * @param {{alpha:number, gamma:number}} [previous] The last targets, so a + * joint with two equivalent answers keeps the nearer one. + * @returns {{alpha:number, beta:number[], gamma:number}} Radians: `alpha` + * about +X for both alpha joints, `beta` about +Z per ISS_BETA_JOINTS entry, + * `gamma` about +Z for both radiator joints. + */ +export function issJointTargets( + sun, + sunlit, + previous = { alpha: 0, gamma: 0 }, +) { + const [sx, sy, sz] = sun; + // Radiators: the panel normal, Y at rest, perpendicular to the Sun. + const gamma = + Math.hypot(sx, sy) < MIN_STEER + ? previous.gamma + : nearestHalfTurn(Math.atan2(sy, sx), previous.gamma); + if (!sunlit) { + return { + alpha: nearestHalfTurn(0, previous.alpha), + beta: ISS_BETA_JOINTS.map(() => 0), + gamma, + }; + } + // Alpha: the masts, ±Z at rest, perpendicular to the Sun. + const alpha = + Math.hypot(sy, sz) < MIN_STEER + ? previous.alpha + : nearestHalfTurn(Math.atan2(sz, sy), previous.alpha); + // The Sun as the arrays see it before the alpha turn. + const c = Math.cos(alpha); + const s = Math.sin(alpha); + const lx = sx; + const ly = c * sy + s * sz; + // Beta: the cell side's normal, ±X at rest, onto the Sun. + const beta = ISS_BETA_JOINTS.map(({ face }) => + Math.atan2(face * ly, face * lx), + ); + return { alpha, beta, gamma }; +} + +/** + * Step `current` toward `target` the short way round, by at most `maxStep`. + * @returns {number} + */ +export function issStepAngle(current, target, maxStep) { + const delta = wrap(target - current); + if (Math.abs(delta) <= maxStep) return current + delta; + return current + Math.sign(delta) * maxStep; +} + +/** + * A node's matrix for a turn of `angle` about `axis` ('x' or 'z') through + * `pivot`, column-major. + * @param {'x'|'z'} axis + * @param {number[]} pivot + * @param {number} angle Radians. + * @param {ArrayLike} result Any 16-slot array, column-major. + * @returns {ArrayLike} `result`. + */ +export function issJointMatrix(axis, pivot, angle, result) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const [px, py, pz] = pivot; + // Row-major arguments. + if (axis === 'x') + return set(result, [ + 1, + 0, + 0, + 0, + 0, + c, + -s, + py - (c * py - s * pz), + 0, + s, + c, + pz - (s * py + c * pz), + 0, + 0, + 0, + 1, + ]); + return set(result, [ + c, + -s, + 0, + px - (c * px - s * py), + s, + c, + 0, + py - (s * px + c * py), + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + ]); +} + +/** + * Write a row-major 4×4 into `result`, column-major (a renderer's matrix + * layout; `result` is any 16-slot array). + * @param {ArrayLike & {[i: number]: number}} [result] A new one when not given. + * @param {number[]} rowMajor + */ +function set(result, rowMajor) { + result ??= new Float64Array(16); + for (let row = 0; row < 4; row++) + for (let column = 0; column < 4; column++) + result[column * 4 + row] = rowMajor[row * 4 + column]; + return result; +} + +/** + * Canadarm2's seven joints as NASA's file names them, base to tip: each + * node's pivot and its local Z axis on the model's axes. Where the real arm + * is at any moment is not public, so its motion here is ILLUSTRATIVE: a slow + * sway of `sway` radians about the pose in NASA's file, over `period` + * seconds. Joints with no sway stay as filed. + */ +export const ISS_ARM_JOINTS = Object.freeze( + [ + ['SHR', [0.6732, -9.3793, 8.3367], [-0.0942, -0.0136, 0.9955], 0, 0], + ['SHY', [0.6004, -9.3899, 9.105], [-0.2949, 0.9554, -0.0148], 8, 97], + ['SHP_PRIME', [0.7848, -9.9873, 9.1143], [-0.2949, 0.9554, -0.0148], 6, 71], + [ + 'ELP_PRIME', + [-2.9987, -11.8039, 2.5061], + [-0.2949, 0.9554, -0.0148], + 12, + 53, + ], + ['WRP', [-3.8898, -12.6132, 10.249], [-0.2949, 0.9554, -0.0148], 10, 41], + ['WRY', [-3.9961, -12.6341, 11.0132], [-0.2949, 0.9554, -0.0148], 0, 0], + ['WRR', [-4.2995, -12.7285, 10.9684], [0.2874, -0.5533, -0.7818], 0, 0], + ].map(([node, pivot, axis, swayDeg, period]) => + Object.freeze({ + node, + pivot, + axis, + sway: (swayDeg * Math.PI) / 180, + period, + }), + ), +); + +/** + * The station's smaller arms, swayed the same illustrative way: Dextre's two + * arms (shoulder and elbow pitch each) and the Japanese arm on Kibo + * (shoulder, elbow and wrist pitch). The European arm on Nauka has no joints + * in NASA's file, so it stays as filed. + */ +export const ISS_SMALL_ARM_JOINTS = Object.freeze( + [ + [ + 'SPDM_Arm1_SHP', + [4.3019, -8.7313, 2.9551], + [-0.5183, -0.8218, -0.2366], + 5, + 61, + ], + [ + 'SPDM_Arm1_ELP', + [4.763, -7.9839, 3.1897], + [0.2256, 0.4303, -0.874], + 7, + 43, + ], + [ + 'SPDM_Arm2_SHP', + [1.8182, -9.8753, 5.2105], + [-0.27, -0.522, -0.8091], + 5, + 67, + ], + [ + 'SPDM_Arm2_ELP', + [1.8575, -9.4898, 6.0546], + [-0.3202, -0.5495, -0.7717], + 7, + 47, + ], + ['JEM_SP_ROT', [14.2188, -3.6716, 13.394], [-0.001, 0, -1], 5, 83], + ['JEM_EP_ROT', [14.2223, 0.6479, 13.394], [-0.0011, 0, -1], 8, 59], + ['JEM_WP_ROT', [16.4495, -3.0694, 13.3917], [-0.001, 0, -1], 8, 37], + ].map(([node, pivot, axis, swayDeg, period]) => + Object.freeze({ + node, + pivot, + axis, + sway: (swayDeg * Math.PI) / 180, + period, + }), + ), +); + +/** Every joint that sways. */ +const ISS_SWAY_JOINTS = [...ISS_ARM_JOINTS, ...ISS_SMALL_ARM_JOINTS]; +/** The arm joints the sway moves; the rest hold NASA's filed pose. */ +const ISS_SWAYING_NODES = new Set( + ISS_SWAY_JOINTS.filter((joint) => joint.sway).map((joint) => joint.node), +); + +/** + * The arm's illustrative joint angles at a wall-clock time. + * @param {number} seconds + * @returns {number[]} Radians, one per ISS_ARM_JOINTS entry. + */ +export function issArmAngles(seconds, joints = ISS_ARM_JOINTS) { + return joints.map(({ sway, period }) => + sway ? sway * Math.sin((2 * Math.PI * seconds) / period) : 0, + ); +} + +/** + * The two Ku-band dishes on the Z1 truss. NASA's file has them welded into + * the truss; the build cuts out everything above each gimbal. At rest a dish + * looks along +Y (zenith). + */ +export const ISS_DISH_JOINTS = Object.freeze([ + Object.freeze({ node: 'SGANT_ROT_1', pivot: [-1.105, 4.5, -4.885] }), + Object.freeze({ node: 'SGANT_ROT_2', pivot: [4.56, 4.64, -5.235] }), +]); + +/** + * The relay satellites the dishes talk to (NASA's TDRS) sit over the equator + * at fixed longitudes, so each is a fixed point in the Earth-fixed frame. + * These are the fleet's nominal slots (Atlantic, Pacific, Indian Ocean), not + * a live roster: which satellite the station uses at a given moment is not + * public in real time. + */ +export const ISS_RELAY_LONGITUDES_DEG = Object.freeze([-41, -171, 85]); +const GEOSTATIONARY_RADIUS_M = 42_164_000; +/** A dish does not look below this much above the station's horizon plane. */ +const DISH_MIN_UP = 0.15; + +/** + * Where the relay satellites are from the station, on the model's axes, the + * highest above the station first. + * @param {number[]} positionEcef Meters. + * @param {{x:number[], y:number[], z:number[]}} axes Flight axes. + * @param {readonly number[]} [longitudes] The relays' slots, degrees east; + * NASA's for the ISS, another station passes its own. + * @returns {number[][]} Unit vectors [port, zenith, forward]. + */ +export function issRelayDirections( + positionEcef, + axes, + longitudes = ISS_RELAY_LONGITUDES_DEG, +) { + return longitudes + .map((longitude) => { + const lon = (longitude * Math.PI) / 180; + const to = [ + GEOSTATIONARY_RADIUS_M * Math.cos(lon) - positionEcef[0], + GEOSTATIONARY_RADIUS_M * Math.sin(lon) - positionEcef[1], + -positionEcef[2], + ]; + const length = Math.hypot(to[0], to[1], to[2]); + return issSunInModelFrame( + to.map((c) => c / length), + axes, + ); + }) + .sort((a, b) => b[1] - a[1]); +} + +/** + * Turn the unit vector `current` toward `target` by at most `maxStep` radians. + * @returns {number[]} + */ +export function issStepDirection(current, target, maxStep) { + const cos = Math.min( + 1, + Math.max( + -1, + current[0] * target[0] + current[1] * target[1] + current[2] * target[2], + ), + ); + const angle = Math.acos(cos); + if (angle <= maxStep || angle < 1e-6) return target; + const sin = Math.sin(angle); + // Opposite vectors have no single arc between them: nudge off the line. + if (sin < 1e-6) + return issStepDirection( + [current[2], current[0], current[1]], + target, + maxStep, + ); + const t = maxStep / angle; + const a = Math.sin((1 - t) * angle) / sin; + const b = Math.sin(t * angle) / sin; + return [0, 1, 2].map((i) => a * current[i] + b * target[i]); +} + +/** + * A node's matrix for a turn of `angle` about the unit vector `axis` through + * `pivot`. + * @param {number[]} pivot + * @param {number[]} axis Unit vector. + * @param {number} angle Radians. + * @param {ArrayLike} result Any 16-slot array, column-major. + * @returns {ArrayLike} `result`. + */ +export function issAxisMatrix(pivot, axis, angle, result) { + const [x, y, z] = axis; + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const r = [ + [t * x * x + c, t * x * y - s * z, t * x * z + s * y], + [t * x * y + s * z, t * y * y + c, t * y * z - s * x], + [t * x * z - s * y, t * y * z + s * x, t * z * z + c], + ]; + const rows = r.map((row, i) => [ + ...row, + pivot[i] - (row[0] * pivot[0] + row[1] * pivot[1] + row[2] * pivot[2]), + ]); + return set(result, [...rows[0], ...rows[1], ...rows[2], 0, 0, 0, 1]); +} + +/** + * A dish node's matrix that turns its rest boresight (+Y) onto `direction`. + * @param {number[]} pivot + * @param {number[]} direction Unit vector on the model's axes. + * @param {ArrayLike} result Any 16-slot array, column-major. + * @returns {ArrayLike} `result`. + */ +export function issAimMatrix(pivot, direction, result) { + // Y × direction + const kx = direction[2]; + const kz = -direction[0]; + const length = Math.hypot(kx, kz); + if (length < 1e-9) + return issAxisMatrix( + pivot, + [1, 0, 0], + direction[1] > 0 ? 0 : Math.PI, + result, + ); + const angle = Math.acos(Math.min(1, Math.max(-1, direction[1]))); + return issAxisMatrix(pivot, [kx / length, 0, kz / length], angle, result); +} + +/** + * Drives the loaded model's joints. Stateless about the model: `update` looks + * the nodes up once per model and only writes a node whose angle moved. + */ +export function createIssArticulation() { + let boundModel = null; + let nodes = null; + let angles = null; + let targets = { alpha: 0, gamma: 0 }; + let lastMs = 0; + let override = null; + let dishOverride = null; + /** Gives the joint angles from telemetry, or null: see setTelemetry. */ + let telemetry = null; + /** Command panel state: Manual takes the joints, so telemetry is off. */ + let telemetryAllowed = true; + /** Whether the last update took its angles from telemetry; null before one. */ + let lastLive = null; + /** Whether the last update had the station in sunlight; null before one. */ + let lastSunlit = null; + /** Command panel state: the arm is being posed by hand, so the sway is off. */ + /** The arm joints posed by hand (command panel); the rest keep swaying. */ + const manualJoints = new Set(); + let armNodes = null; + /** Command panel state: how far the arrays are rolled out, 0.05 to 1. */ + let deploy = 1; + let deployTarget = 1; + let radiatorDeploy = 1; + let radiatorTarget = 1; + /** The truss face the radiators fold back to, on the model's Z axis. */ + const RADIATOR_ROOT_Z = -1.9; + /** The power modules' radiators, cut out by the build, and their root. */ + const SMALL_RADIATOR_NODES = [ + 'PVR_FOLD_P4', + 'PVR_FOLD_P6', + 'PVR_FOLD_S4', + 'PVR_FOLD_S6', + ]; + const SMALL_RADIATOR_ROOT_Y = -1.6; + /** Where each dish looks now, on the model's axes. */ + let dishes = null; + const scratchMatrix = new Float64Array(16); + + function bind(model) { + boundModel = model; + const get = (joint) => model.getNode(joint.node) ?? null; + nodes = { + alpha: ISS_ALPHA_JOINTS.map(get), + beta: ISS_BETA_JOINTS.map(get), + gamma: ISS_RADIATOR_JOINTS.map(get), + dish: ISS_DISH_JOINTS.map(get), + }; + angles = null; + dishes = null; + armNodes = null; + } + + function sunEcef(date) { + const sun = sunPositionFixed(date.getTime()); + const length = Math.hypot(sun.x, sun.y, sun.z) || 1; + return [sun.x / length, sun.y / length, sun.z / length]; + } + + function write(node, axis, pivot, angle) { + if (!node) return; + node.matrix = issJointMatrix(axis, pivot, angle, scratchMatrix); + } + + /** + * @param {{ready: boolean, getNode: (name: string) => object|undefined}} model + * A ready model, or any holder of nodes that take a `matrix`. + * @param {Date} date The instant the model is placed at. + * @param {{x:number,y:number,z:number}} position Earth-fixed station position. + * @param {{x:number[], y:number[], z:number[]}} axes Its flight axes. + * @param {number} [nowMs] Wall clock, for the turn rate. + */ + function update(model, date, position, axes, nowMs = Date.now()) { + if (!model.ready) return; + if (model !== boundModel) bind(model); + const forced = override?.(nowMs) ?? null; + if (forced) { + lastSunlit = Boolean(forced.sunlit); + targets = issJointTargets(forced.sun, forced.sunlit, targets); + } else { + const sun = sunEcef(date); + const sunlit = !issInShadow([position.x, position.y, position.z], sun); + lastSunlit = sunlit; + targets = issJointTargets(issSunInModelFrame(sun, axes), sunlit, targets); + } + // Telemetry, when it has a pose, replaces the computed targets; a Sun + // chosen by hand in the command panel is always computed. + const pose = telemetryAllowed && !forced ? (telemetry?.() ?? null) : null; + lastLive = Boolean(pose); + const alphaTargets = pose?.alpha ?? [targets.alpha, targets.alpha]; + const betaTargets = pose?.beta ?? targets.beta; + const gammaTargets = pose?.gamma ?? [targets.gamma, targets.gamma]; + // A first frame, or one after a pause, goes straight to the pose. + const elapsed = (nowMs - lastMs) / 1000; + lastMs = nowMs; + const maxStep = + !angles || !(elapsed >= 0) || elapsed > 2 + ? Number.POSITIVE_INFINITY + : ISS_JOINT_RATE * elapsed; + const next = { + alpha: alphaTargets.map((target, i) => + issStepAngle(angles?.alpha[i] ?? 0, target, maxStep), + ), + beta: betaTargets.map((target, i) => + issStepAngle(angles?.beta[i] ?? 0, target, maxStep), + ), + gamma: gammaTargets.map((target, i) => + issStepAngle(angles?.gamma[i] ?? 0, target, maxStep), + ), + }; + ISS_ALPHA_JOINTS.forEach((joint, i) => { + if (!angles || next.alpha[i] !== angles.alpha[i]) + write(nodes.alpha[i], 'x', joint.pivot, next.alpha[i]); + }); + // Command panel: squash the arrays along their masts (see setDeploy). + const deployStep = Number.isFinite(maxStep) ? elapsed / 8 : 1; + const nextDeploy = + deploy + + Math.sign(deployTarget - deploy) * + Math.min(Math.abs(deployTarget - deploy), deployStep); + ISS_BETA_JOINTS.forEach((joint, i) => { + if ( + !angles || + next.beta[i] !== angles.beta[i] || + nextDeploy !== deploy || + nextDeploy !== 1 + ) { + const node = nodes.beta[i]; + if (!node) return; + const m = issJointMatrix('z', joint.pivot, next.beta[i], scratchMatrix); + m[10] = nextDeploy; + m[14] = joint.pivot[2] * (1 - nextDeploy); + node.matrix = m; + } + }); + deploy = nextDeploy; + // Command panel: fold the radiators toward the truss. + const nextRadiator = + radiatorDeploy + + Math.sign(radiatorTarget - radiatorDeploy) * + Math.min(Math.abs(radiatorTarget - radiatorDeploy), deployStep); + ISS_RADIATOR_JOINTS.forEach((joint, i) => { + if ( + angles && + next.gamma[i] === angles.gamma[i] && + nextRadiator === radiatorDeploy + ) + return; + const node = nodes.gamma[i]; + if (!node) return; + const m = issJointMatrix('z', joint.pivot, next.gamma[i], scratchMatrix); + m[10] = nextRadiator; + m[14] = RADIATOR_ROOT_Z * (1 - nextRadiator); + node.matrix = m; + }); + // The four small radiators fold up to the truss, along Y. + if (nextRadiator !== radiatorDeploy) + for (const name of SMALL_RADIATOR_NODES) { + const node = model.getNode(name); + if (!node) continue; + node.matrix = set(scratchMatrix, [ + 1, + 0, + 0, + 0, + 0, + nextRadiator, + 0, + SMALL_RADIATOR_ROOT_Y * (1 - nextRadiator), + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + ]); + } + radiatorDeploy = nextRadiator; + angles = next; + + // Dishes: the highest relay satellite for the first, the next for the + // second; one below the station's horizon plane keeps its last aim. + // Telemetry reports one dish (the station uses one at a time, and does + // not say which): the first takes its real aim, wherever that is, and + // the second holds still. + const liveDish = !dishOverride && pose?.dish ? pose.dish : null; + const relays = dishOverride + ? [dishOverride, dishOverride] + : liveDish + ? [liveDish, null] + : issRelayDirections([position.x, position.y, position.z], axes); + const nextDishes = ISS_DISH_JOINTS.map((joint, i) => { + const current = dishes?.[i] ?? [0, 1, 0]; + const wanted = relays[i]; + const target = + wanted && (liveDish || wanted[1] >= DISH_MIN_UP) ? wanted : current; + const stepped = issStepDirection(current, target, maxStep); + const moved = + !dishes || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9); + if (moved) + if (nodes.dish[i]) + nodes.dish[i].matrix = issAimMatrix( + joint.pivot, + stepped, + scratchMatrix, + ); + return stepped; + }); + dishes = nextDishes; + + // Arm: an illustrative sway (see ISS_ARM_JOINTS). + { + const arm = issArmAngles(nowMs / 1000, ISS_SWAY_JOINTS); + ISS_SWAY_JOINTS.forEach((joint, i) => { + if (!joint.sway || manualJoints.has(joint.node)) return; + const node = (armNodes ??= ISS_SWAY_JOINTS.map( + (entry) => model.getNode(entry.node) ?? null, + ))[i]; + if (node) + node.matrix = issAxisMatrix( + joint.pivot, + joint.axis, + arm[i], + scratchMatrix, + ); + }); + } + } + + /** + * Command panel: turn any named node about an axis through a pivot. + * @param {string} name + * @param {number[]} pivot + * @param {number[]} axis Unit vector. + * @param {number} angle Radians. + */ + function setJoint(name, pivot, axis, angle) { + manualJoints.add(name); + const node = boundModel?.getNode(name); + if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix); + } + + /** Forget the model and every manual choice: the next update starts clean. */ + function reset() { + boundModel = null; + nodes = null; + angles = null; + dishes = null; + armNodes = null; + targets = { alpha: 0, gamma: 0 }; + override = null; + dishOverride = null; + telemetryAllowed = true; + manualJoints.clear(); + } + + /** + * Command panel: a function giving the Sun on the model's axes (and whether the + * station is lit) in place of the real one, or null for the real one. + * @param {((nowMs:number)=>{sun:number[], sunlit:boolean}|null)|null} fn + */ + function setOverride(fn) { + override = fn; + } + + /** Whether the station is in sunlight, as of the last update. */ + function isSunlit() { + return lastSunlit; + } + + /** + * Where the joint angles come from when telemetry has them: a function + * giving `{alpha, beta, gamma, dish}` (issTelemetryPose) or null. + * @param {(() => {alpha:number[], beta:number[], gamma:number[], + * dish:number[]|null}|null)|null} fn + */ + function setTelemetry(fn) { + telemetry = fn; + } + + /** Command panel: Manual switches telemetry off, Automatic back on. */ + function setTelemetryAllowed(allowed) { + telemetryAllowed = Boolean(allowed); + } + + /** Whether the last update took its angles from telemetry; null before one. */ + function isLive() { + return lastLive; + } + + /** Command panel: aim both dishes along a unit vector, or null for the relays. */ + function setDishOverride(direction) { + dishOverride = direction; + } + + /** + * Command panel: squash the arrays toward their bases, or let them + * out again. The real arrays do not retract in service. + * @param {boolean} out + */ + function setDeploy(out) { + deployTarget = out ? 1 : 0.05; + } + + /** + * Command panel: fold the radiators toward the truss, or let them + * out. The real ones are accordion panels that can do this, but stay out + * in service. + * @param {boolean} out + */ + function setRadiatorDeploy(out) { + radiatorTarget = out ? 1 : 0.08; + } + + /** Command panel: hand the arm back to its sway. */ + function resumeArm() { + // A joint the sway does not move would keep its manual angle: it goes + // back to its filed pose. The swaying ones are posed again next update. + for (const name of manualJoints) { + if (ISS_SWAYING_NODES.has(name)) continue; + const node = boundModel?.getNode(name); + if (node) node.matrix = undefined; + } + manualJoints.clear(); + } + + return { + update, + reset, + setOverride, + setDishOverride, + setJoint, + resumeArm, + setDeploy, + setRadiatorDeploy, + isSunlit, + setTelemetry, + setTelemetryAllowed, + isLive, + }; +} diff --git a/src/layers/satellites/issArticulation.test.mjs b/src/layers/satellites/issArticulation.test.mjs new file mode 100644 index 0000000000..b8bfcf32e2 --- /dev/null +++ b/src/layers/satellites/issArticulation.test.mjs @@ -0,0 +1,231 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import test from 'node:test'; +import { + ISS_ALPHA_JOINTS, + ISS_BETA_JOINTS, + ISS_RADIATOR_JOINTS, + issInShadow, + issJointMatrix, + issJointTargets, + issStepAngle, + issSunInModelFrame, +} from './issArticulation.js'; + +const rotX = (a, [x, y, z]) => [ + x, + Math.cos(a) * y - Math.sin(a) * z, + Math.sin(a) * y + Math.cos(a) * z, +]; +const rotZ = (a, [x, y, z]) => [ + Math.cos(a) * x - Math.sin(a) * y, + Math.sin(a) * x + Math.cos(a) * y, + z, +]; +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const unit = (v) => v.map((c) => c / Math.hypot(...v)); + +const SUNS = [ + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [0.5, 0.5, 0.7], + [-0.6, 0.2, -0.77], + [0.3, -0.9, 0.3], + [0.9, 0.1, -0.4], +].map(unit); + +test('in sunlight every array faces the Sun, masts across it', () => { + for (const sun of SUNS) { + const { alpha, beta } = issJointTargets(sun, true); + assert.ok(Math.abs(dot(rotX(alpha, [0, 0, 1]), sun)) < 1e-9); + ISS_BETA_JOINTS.forEach(({ face }, i) => { + // The beta joint hangs from the alpha joint: beta turns first. + const normal = rotX(alpha, rotZ(beta[i], [face, 0, 0])); + assert.ok(dot(normal, sun) > 1 - 1e-9, `${sun} array ${i}`); + }); + } +}); + +test('the radiators stay edge-on to the Sun', () => { + for (const sun of SUNS) { + const { gamma } = issJointTargets(sun, true); + assert.ok(Math.abs(dot(rotZ(gamma, [0, 1, 0]), sun)) < 1e-9); + } +}); + +test('in the shadow the arrays feather along the flight direction', () => { + const { alpha, beta } = issJointTargets(unit([0.2, -0.9, 0.3]), false, { + alpha: 3, + gamma: 0, + }); + assert.ok(Math.abs(Math.sin(alpha)) < 1e-9); // masts back along ±Z + assert.ok(Math.abs(alpha - Math.PI) < 1e-9); // the nearer half turn + assert.deepEqual( + beta, + ISS_BETA_JOINTS.map(() => 0), + ); +}); + +test('a joint keeps the answer nearer its last one, and holds near its axis', () => { + const first = issJointTargets(unit([0, 1, 0.01]), true); + const next = issJointTargets(unit([0, 1, -0.01]), true, first); + assert.ok(Math.abs(next.alpha - first.alpha) < 0.05); + // Sun along the truss: nothing to steer the alpha joint by. + const held = issJointTargets([1, 0, 0], true, { alpha: 1.2, gamma: 0.4 }); + assert.equal(held.alpha, 1.2); +}); + +test('angles step the short way round, capped', () => { + assert.equal(issStepAngle(0, 1, 0.25), 0.25); + assert.ok(issStepAngle(3, -3, 0.1) > 3); // through π, not back through 0 + assert.equal(issStepAngle(0.2, 0.3, 1), 0.3); +}); + +test('a joint matrix leaves its pivot in place', () => { + for (const axis of ['x', 'z']) { + const pivot = [3, -2, 5]; + const m = issJointMatrix(axis, pivot, 0.7, undefined); + const moved = [0, 1, 2].map( + (r) => + m[r] * pivot[0] + m[4 + r] * pivot[1] + m[8 + r] * pivot[2] + m[12 + r], + ); + moved.forEach((v, i) => assert.ok(Math.abs(v - pivot[i]) < 1e-12)); + } +}); + +test('the shadow is the cylinder behind the Earth', () => { + const sun = [1, 0, 0]; + assert.equal(issInShadow([6_790_000, 0, 0], sun), false); + assert.equal(issInShadow([-6_790_000, 0, 0], sun), true); + assert.equal(issInShadow([-1_000_000, 6_700_000, 0], sun), false); +}); + +test('the Sun lands on the model axes: port, zenith, forward', () => { + const axes = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; + assert.deepEqual(issSunInModelFrame([0.1, 0.2, 0.3], axes), [0.2, 0.3, 0.1]); +}); + +test('the model file has every joint node, beta joints under their alpha', () => { + const buf = fs.readFileSync( + new URL('../../../public/models/iss.glb', import.meta.url), + ); + const json = JSON.parse( + buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'), + ); + const byName = new Map(json.nodes.map((n) => [n.name, n])); + for (const { node } of [ + ...ISS_ALPHA_JOINTS, + ...ISS_BETA_JOINTS, + ...ISS_RADIATOR_JOINTS, + ]) { + const n = byName.get(node); + assert.ok(n, node); + // Joints rest at identity: the pivots above are in the model's own frame. + assert.equal(n.rotation, undefined); + assert.equal(n.translation, undefined); + assert.equal(n.matrix, undefined); + } + for (const side of ['PORT', 'STBD']) { + const kids = byName + .get(`${side}_ALPHA_ROT`) + .children.map((i) => json.nodes[i].name); + for (const { node } of ISS_BETA_JOINTS) + if (node.startsWith(side)) assert.ok(kids.includes(node), node); + } +}); + +test('a dish aims its rest boresight (+Y) at the direction, pivot in place', async () => { + const { issAimMatrix, ISS_DISH_JOINTS } = + await import('./issArticulation.js'); + for (const direction of SUNS) { + const m = issAimMatrix(ISS_DISH_JOINTS[0].pivot, direction, undefined); + // Column 1 is where +Y goes. + [m[4], m[5], m[6]].forEach((v, i) => + assert.ok(Math.abs(v - direction[i]) < 1e-9), + ); + const p = ISS_DISH_JOINTS[0].pivot; + [0, 1, 2].forEach((r) => + assert.ok( + Math.abs( + m[r] * p[0] + m[4 + r] * p[1] + m[8 + r] * p[2] + m[12 + r] - p[r], + ) < 1e-9, + ), + ); + } +}); + +test('relay directions are unit vectors, highest above the station first', async () => { + const { issRelayDirections } = await import('./issArticulation.js'); + // Over the equator at 41°W, flying east: the Atlantic relay is overhead. + const lon = (-41 * Math.PI) / 180; + const r = 6_790_000; + const position = [r * Math.cos(lon), r * Math.sin(lon), 0]; + const zenith = [Math.cos(lon), Math.sin(lon), 0]; + const east = [-Math.sin(lon), Math.cos(lon), 0]; + const axes = { x: east, y: [0, 0, 1], z: zenith }; + const relays = issRelayDirections(position, axes); + assert.equal(relays.length, 3); + relays.forEach((d) => assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-9)); + assert.ok(relays[0][1] > 0.999); + assert.ok(relays[0][1] >= relays[1][1] && relays[1][1] >= relays[2][1]); +}); + +test('a direction steps along the arc, capped, and lands on the target', async () => { + const { issStepDirection } = await import('./issArticulation.js'); + const stepped = issStepDirection([0, 1, 0], [1, 0, 0], 0.1); + assert.ok(Math.abs(Math.hypot(...stepped) - 1) < 1e-9); + assert.ok(Math.abs(Math.acos(stepped[1]) - 0.1) < 1e-9); + assert.deepEqual(issStepDirection([0, 1, 0], [1, 0, 0], 2), [1, 0, 0]); +}); + +test('the model file has both dish nodes', async () => { + const { ISS_DISH_JOINTS } = await import('./issArticulation.js'); + const buf = fs.readFileSync( + new URL('../../../public/models/iss.glb', import.meta.url), + ); + const json = JSON.parse( + buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'), + ); + for (const { node } of ISS_DISH_JOINTS) { + const n = json.nodes.find((candidate) => candidate.name === node); + assert.ok(n?.children?.length, node); + } +}); + +test('the arm sways gently about the filed pose, and only where it is set to', async () => { + const { ISS_ARM_JOINTS, issArmAngles } = await import('./issArticulation.js'); + assert.equal(ISS_ARM_JOINTS.length, 7); + for (let seconds = 0; seconds < 400; seconds += 7) { + issArmAngles(seconds).forEach((angle, i) => { + assert.ok(Math.abs(angle) <= ISS_ARM_JOINTS[i].sway + 1e-12); + // Illustrative, so kept small. + assert.ok(Math.abs(angle) <= (12 * Math.PI) / 180 + 1e-12); + }); + } + assert.deepEqual(issArmAngles(0), [0, 0, 0, 0, 0, 0, 0]); +}); + +test('the smaller arms sway too, and their joints are in the model file', async () => { + const { ISS_SMALL_ARM_JOINTS, ISS_ARM_JOINTS, issArmAngles } = + await import('./issArticulation.js'); + const buf = fs.readFileSync( + new URL('../../../public/models/iss.glb', import.meta.url), + ); + const json = JSON.parse( + buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'), + ); + const names = new Set(json.nodes.map((n) => n.name)); + for (const { node, sway, axis } of [ + ...ISS_ARM_JOINTS, + ...ISS_SMALL_ARM_JOINTS, + ]) { + assert.ok(names.has(node), node); + assert.ok(sway <= (12 * Math.PI) / 180 + 1e-12); + assert.ok(Math.abs(Math.hypot(...axis) - 1) < 1e-3); + } + assert.equal( + issArmAngles(10, ISS_SMALL_ARM_JOINTS).length, + ISS_SMALL_ARM_JOINTS.length, + ); +}); diff --git a/src/layers/satellites/issCommand.js b/src/layers/satellites/issCommand.js new file mode 100644 index 0000000000..3cfec6b081 --- /dev/null +++ b/src/layers/satellites/issCommand.js @@ -0,0 +1,105 @@ +const unit = (v) => { + const n = Math.hypot(...v); + return v.map((c) => c / n); +}; + +/** Where "Zoom to the ISS" stops: the whole 109 m station fills the view. */ +export const ISS_COMMAND_ZOOM_RANGE_M = 260; + +/** Beyond this the camera counts as far, and the zoom button is offered. */ +export const ISS_COMMAND_FAR_M = 1000; + +/** + * Whether "Zoom to the ISS" is offered: only from far away, so it goes once + * the camera is in close (by the button or by hand) and returns on zooming + * back out. + * @param {number} distance Meters from the camera to the station. + * @returns {boolean} + */ +export function issCommandOffersZoom(distance) { + return distance > ISS_COMMAND_FAR_M; +} + +/** + * One step of the zoom: how far to move in from `distance`, easing out as + * the target range nears, never past it. + * @param {number} distance Meters from the camera to the station. + * @returns {number} Meters to move in; 0 once close enough. + */ +export function issCommandZoomStep(distance) { + const left = distance - ISS_COMMAND_ZOOM_RANGE_M; + if (!(left > ISS_COMMAND_ZOOM_RANGE_M * 0.02)) return 0; + return left * 0.14; +} + +/** + * The follow camera's range after one step of the zoom: the step nearer, + * never past the target range, and unchanged once there. The camera is moved + * by scaling its follow offset from the station (the camera port's + * `followOffset`, the eye in the follow's frame) by + * `issCommandZoomRange(range) / range`, which can only bring it in; a move + * along the view direction is not used, since it ran away when the camera + * was not looking at the station. + * @param {number} range Meters from the camera to the station. + * @returns {number} The range to set; `range` itself when there is no step. + */ +export function issCommandZoomRange(range) { + if (!(range > 0) || !Number.isFinite(range)) return range; + const step = issCommandZoomStep(range); + return step > 0 ? Math.max(ISS_COMMAND_ZOOM_RANGE_M, range - step) : range; +} + +/** + * One step of the zoom on the follow offset: the same offset, shortened to + * `issCommandZoomRange` of its length, so the eye keeps its bearing on the + * station and only comes in. + * @param {{x: number, y: number, z: number}|null|undefined} offset The + * eye's offset from the station, metres in the follow's frame. + * @returns {{x: number, y: number, z: number}|null} The offset to set; null + * when there is no step (close enough, or no offset to shorten). + */ +export function issCommandZoomOffset(offset) { + if (!offset) return null; + const range = Math.hypot(offset.x, offset.y, offset.z); + const next = issCommandZoomRange(range); + if (!(next < range)) return null; + const k = next / range; + return { x: offset.x * k, y: offset.y * k, z: offset.z * k }; +} + +/** + * Whether the zoom may run: only while the camera follows the station's + * follow target and has framed it, so that its follow offset is the eye's + * offset from the station and shortening it brings the camera in. From any + * other camera (still flying to the station, following something else, or + * a follow not yet framed) there is no such offset to shorten. + * @param {{followed?: object|null, followFramed?: boolean}|null|undefined} + * camera What the camera port reports (`cameraOf(viewer)`). + * @param {object|null|undefined} target The layer's follow target for the + * station (`layerState._followTarget`). + * @returns {boolean} + */ +export function issCommandCameraOnStation(camera, target) { + return ( + Boolean(target) && + camera?.followed === target && + camera.followFramed === true + ); +} + +/** How long one lap of the "fast orbit" takes, and its share in shadow. */ +const FAST_ORBIT_MS = 40_000; + +/** + * The Sun over one accelerated orbit: it circles the truss, a third of the + * lap in the Earth's shadow. + * @param {number} elapsedMs + * @returns {{sun: number[], sunlit: boolean}} + */ +export function issCommandFastOrbit(elapsedMs) { + const angle = (elapsedMs / FAST_ORBIT_MS) * 2 * Math.PI; + return { + sun: unit([0.35, Math.cos(angle), Math.sin(angle)]), + sunlit: Math.cos(angle) > -0.5, + }; +} diff --git a/src/layers/satellites/issCommand.test.mjs b/src/layers/satellites/issCommand.test.mjs new file mode 100644 index 0000000000..262153d514 --- /dev/null +++ b/src/layers/satellites/issCommand.test.mjs @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + issCommandCameraOnStation, + issCommandZoomOffset, + issCommandZoomRange, + ISS_COMMAND_ZOOM_RANGE_M, + issCommandFastOrbit, + issCommandZoomStep, +} from './issCommand.js'; +import { ISS_NORAD } from './policy.js'; + +test('the zoom eases in to its range and stops there, never past it', () => { + let distance = 726_000; + let steps = 0; + for (; steps < 400; steps++) { + const step = issCommandZoomStep(distance); + if (!step) break; + assert.ok(step > 0 && step < distance - ISS_COMMAND_ZOOM_RANGE_M); + distance -= step; + } + assert.ok(steps < 120); // under two seconds at 60 frames a second + assert.ok(distance >= ISS_COMMAND_ZOOM_RANGE_M); + assert.ok(distance <= ISS_COMMAND_ZOOM_RANGE_M * 1.02 + 1e-6); + // Already closer: nothing to do, and it never pushes the camera back out. + assert.equal(issCommandZoomStep(180), 0); +}); + +test('the fast orbit turns the Sun once per lap, part of it in shadow', () => { + const start = issCommandFastOrbit(0); + assert.ok(Math.abs(Math.hypot(...start.sun) - 1) < 1e-9); + assert.equal(start.sunlit, true); + assert.equal(issCommandFastOrbit(20_000).sunlit, false); // half a lap: below + const lap = issCommandFastOrbit(40_000); + lap.sun.forEach((v, i) => assert.ok(Math.abs(v - start.sun[i]) < 1e-9)); +}); + +test('the zoom is offered only from far away', async () => { + const { ISS_COMMAND_FAR_M, issCommandOffersZoom } = + await import('./issCommand.js'); + assert.equal(issCommandOffersZoom(726_000), true); + assert.equal(issCommandOffersZoom(ISS_COMMAND_FAR_M + 1), true); + // Where the zoom itself stops, and anywhere closer, it is gone. + assert.equal(issCommandOffersZoom(ISS_COMMAND_ZOOM_RANGE_M * 1.02), false); + assert.equal(issCommandOffersZoom(150), false); +}); + +test('an object docked to the ISS is the station too', async () => { + const { issTrackedOnStation } = await import('./policy.js'); + const NAUKA = 49044; + // Tracking Nauka, the ISS shares its position; tracking the ISS needs nothing. + assert.equal(issTrackedOnStation(ISS_NORAD, new Set()), true); + assert.equal(issTrackedOnStation(ISS_NORAD, null), true); + assert.equal(issTrackedOnStation(NAUKA, new Set([ISS_NORAD, 68837])), true); + // Another satellite, with or without neighbours, is not. + assert.equal(issTrackedOnStation(20580, new Set()), false); + assert.equal(issTrackedOnStation(20580, new Set([20581])), false); + assert.equal(issTrackedOnStation(null, new Set([ISS_NORAD])), false); + assert.equal(issTrackedOnStation(undefined, undefined), false); +}); + +test('the zoom range only ever shortens, settles at the target range and never runs away', () => { + let range = 1e9; + let steps = 0; + while (steps < 400) { + const next = issCommandZoomRange(range); + assert.ok(next <= range, `step ${steps} moved out: ${range} -> ${next}`); + assert.ok(next >= ISS_COMMAND_ZOOM_RANGE_M, 'never past the target'); + if (next === range) break; + range = next; + steps += 1; + } + assert.ok(steps < 400, "settles within the loop's budget"); + assert.ok(range <= ISS_COMMAND_ZOOM_RANGE_M * 1.02); + assert.equal( + issCommandZoomRange(ISS_COMMAND_ZOOM_RANGE_M), + ISS_COMMAND_ZOOM_RANGE_M, + ); + assert.equal( + issCommandZoomRange(100), + 100, + 'closer than the range: left alone', + ); + for (const bad of [0, -5, NaN, Infinity]) + assert.ok( + Object.is(issCommandZoomRange(bad), bad), + `${bad} passes through`, + ); +}); + +test('one zoom step shortens the follow offset on its own bearing, and stops at the range', () => { + const next = issCommandZoomOffset({ x: 3000, y: 4000, z: 0 }); + const range = Math.hypot(next.x, next.y, next.z); + assert.ok(Math.abs(range - issCommandZoomRange(5000)) < 1e-9); + assert.ok(Math.abs(next.x / next.y - 3 / 4) < 1e-12, 'the bearing is kept'); + assert.equal(next.z, 0); + // Already at the range, or closer: no step. + assert.equal( + issCommandZoomOffset({ x: ISS_COMMAND_ZOOM_RANGE_M, y: 0, z: 0 }), + null, + ); + assert.equal(issCommandZoomOffset({ x: 0, y: 100, z: 0 }), null); + // Nothing to shorten: no follow offset yet (the follow has not framed). + assert.equal(issCommandZoomOffset(null), null); + assert.equal(issCommandZoomOffset(undefined), null); + assert.equal(issCommandZoomOffset({ x: 0, y: 0, z: 0 }), null); +}); + +test("the zoom needs the camera following the station's target, framed", () => { + const target = { key: 'satellites:25544' }; + const on = { followed: target, followFramed: true }; + assert.equal(issCommandCameraOnStation(on, target), true); + assert.equal( + issCommandCameraOnStation( + { followed: target, followFramed: false }, + target, + ), + false, + 'not before the follow has framed the eye', + ); + assert.equal( + issCommandCameraOnStation({ followed: null, followFramed: false }, target), + false, + ); + assert.equal( + issCommandCameraOnStation( + { followed: { key: 'flights:a' }, followFramed: true }, + target, + ), + false, + 'following something else', + ); + assert.equal(issCommandCameraOnStation(null, target), false); + assert.equal(issCommandCameraOnStation(undefined, target), false); + assert.equal(issCommandCameraOnStation(on, null), false); + assert.equal( + issCommandCameraOnStation({ followed: null, followFramed: true }, null), + false, + 'nothing followed and no target is not a match', + ); +}); diff --git a/src/layers/satellites/issModel.js b/src/layers/satellites/issModel.js new file mode 100644 index 0000000000..ee43223699 --- /dev/null +++ b/src/layers/satellites/issModel.js @@ -0,0 +1,144 @@ +import { createIssArticulation } from './issArticulation.js'; +import { + ISS_MOUNTS, + ISS_NAUKA_NORAD, + ISS_POISK_NORAD, + issMountView, + issMountViews, + issMountWorld, +} from './issMounts.js'; +import { createIssTelemetryFeed } from './issTelemetry.js'; +import { + ISS_COMPANION_COARSE_M, + ISS_COMPANION_RADIUS_M, + ISS_COMPANION_SCAN_MS, + ISS_CARD_CLEAR_M, + ISS_MODEL_LOCAL_AXES, + ISS_MODEL_MAX_DISTANCE_M, + ISS_MODEL_MIN_PX, + ISS_MODEL_NATIVE_SPAN, + ISS_MODEL_URL, + ISS_NORAD, + ISS_ORBIT_HIDE_M, + ISS_SPAN_M, +} from './policy.js'; +import { + createStationModel, + stationFlightAxes, + stationModelShouldShow, + temeToEcefAxes, +} from './stationModel.js'; + +/** The model's scale for the real 109 m truss. */ +export const ISS_MODEL_SCALE = ISS_SPAN_M / ISS_MODEL_NATIVE_SPAN; + +// The station-independent rules live in stationModel.js; these names are +// kept for the code and tests written against the ISS-only model. +export { temeToEcefAxes }; +export const issFlightAxes = stationFlightAxes; + +/** + * Whether the ISS model may be drawn (stationModelShouldShow with the ISS's + * `hasIss` wording). + * @param {{enabled: boolean, showPoints: boolean, hasIss: boolean, + * classVisible: boolean, tracked: boolean, cockpitHidden: boolean}} input + * @returns {boolean} + */ +export function issModelShouldShow({ hasIss, ...rest }) { + return stationModelShouldShow({ hasStation: hasIss, ...rest }); +} + +/** + * Whether a catalog entry at the ISS is one of the station's own modules + * (Zarya, Nauka, Poisk, or any other the catalog lists as "ISS (…)") rather + * than a visiting vehicle. A missing entry counts as a module. + * @param {number} noradId + * @param {{name?: string}|undefined} entry + * @returns {boolean} + */ +export function issIsModule(noradId, entry) { + return ( + noradId === ISS_NORAD || + noradId === ISS_NAUKA_NORAD || + noradId === ISS_POISK_NORAD || + /^ISS\s*\(/i.test(entry?.name ?? 'ISS (') + ); +} + +/** + * The ISS as the station model factory describes it: NASA's model at the + * real 109 m span, its joints on the Sun or NASA's telemetry, the Cockpit's + * views from mounts on the model (so the model stays drawn in the Cockpit), + * and its orbit ring, which has rules of its own (`_syncIssOrbit`). + * @param {{parts: object}} context + * @returns {import('./stationModel.js').StationModelSpec} + */ +export function issModelSpec({ parts }) { + return { + key: 'iss', + label: 'ISS', // i18n-ignore: the station's name, for log lines + norad: ISS_NORAD, + modelUrl: ISS_MODEL_URL, + scale: ISS_MODEL_SCALE, + minPx: ISS_MODEL_MIN_PX, + maxDistanceM: ISS_MODEL_MAX_DISTANCE_M, + orbitHideM: ISS_ORBIT_HIDE_M, + cardClearM: ISS_CARD_CLEAR_M, + companionRadiusM: ISS_COMPANION_RADIUS_M, + companionCoarseM: ISS_COMPANION_COARSE_M, + companionScanMs: ISS_COMPANION_SCAN_MS, + localAxes: ISS_MODEL_LOCAL_AXES, + isModule: issIsModule, + createArticulation: createIssArticulation, + createTelemetry: createIssTelemetryFeed, + /** + * One of the views on the model (issMounts.js), in the world. + * `noradId` on the result is the catalog entry the view belongs to. + */ + cockpitMount: ({ key, centre, axes, name, entry, dockedVehicle }) => { + const views = issMountViews({ + naukaName: name(ISS_NAUKA_NORAD), + zaryaName: name(ISS_NORAD), + poiskName: name(ISS_POISK_NORAD), + dockedName: name(dockedVehicle), + naukaNorad: entry(ISS_NAUKA_NORAD), + zaryaNorad: entry(ISS_NORAD), + poiskNorad: entry(ISS_POISK_NORAD), + dockedNorad: entry(dockedVehicle), + }); + const view = issMountView(views, key); + return { + ...issMountWorld(ISS_MOUNTS[view.key], centre, axes), + key: view.key, + label: view.label, + noradId: view.noradId, + card: view.card, + views, + }; + }, + // The Cockpit rides the station from a mount on the model, so the model + // stays while it does. + hideInCockpit: false, + syncOrbit: () => parts.controls._syncIssOrbit?.(), + }; +} + +/** + * The ISS as a 3D model when the camera is close (stationModel.js), with the + * part's methods also under their former ISS-only names. + * @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context + */ +export function createIssModel(context) { + const model = createStationModel(issModelSpec(context), context); + return { + ...model, + _updateIssModel: model._updateStationModel, + _destroyIssModel: model._destroyStationModel, + _issVisualPosition: model._visualPosition, + _issCardClearPx: model._cardClearPx, + _issStandsInFor: model._standsInFor, + _issCockpitMount: model._cockpitMount, + _issTelemetryStatus: model._telemetryStatus, + _issArticulation: model._articulation, + }; +} diff --git a/src/layers/satellites/issModel.test.mjs b/src/layers/satellites/issModel.test.mjs new file mode 100644 index 0000000000..28e74d060a --- /dev/null +++ b/src/layers/satellites/issModel.test.mjs @@ -0,0 +1,153 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { gstime, propagate, twoline2satrec } from 'satellite.js'; +import { + ISS_MODEL_SCALE, + issFlightAxes, + issModelShouldShow, + temeToEcefAxes, +} from './issModel.js'; +import { + ISS_MODEL_CENTER_NATIVE, + ISS_MODEL_LOCAL_AXES, + ISS_MODEL_NATIVE_SPAN, + ISS_MODEL_URL, + ISS_NORAD, + ISS_SPAN_M, +} from './policy.js'; + +const ISS_TLE = [ + '1 25544U 98067A 24001.50000000 .00016717 00000-0 10270-3 0 9002', + '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579 1234', +]; + +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const norm = (a) => Math.hypot(a[0], a[1], a[2]); + +const shown = { + enabled: true, + showPoints: true, + hasIss: true, + classVisible: true, + tracked: false, + cockpitHidden: false, +}; + +test('the ISS model shows on the same terms as its dot', () => { + assert.equal(issModelShouldShow(shown), true); + assert.equal(issModelShouldShow({ ...shown, enabled: false }), false); + assert.equal(issModelShouldShow({ ...shown, showPoints: false }), false); + assert.equal(issModelShouldShow({ ...shown, hasIss: false }), false); + assert.equal(issModelShouldShow({ ...shown, classVisible: false }), false); +}); + +test('a tracked ISS keeps its model with its class hidden', () => { + assert.equal( + issModelShouldShow({ ...shown, classVisible: false, tracked: true }), + true, + ); +}); + +test('the Cockpit hold hides the model', () => { + assert.equal( + issModelShouldShow({ ...shown, tracked: true, cockpitHidden: true }), + false, + ); +}); + +test('the model is the ISS by NORAD number, at its real 109 m span', () => { + assert.equal(ISS_NORAD, 25544); + assert.ok( + Math.abs(ISS_MODEL_SCALE * ISS_MODEL_NATIVE_SPAN - ISS_SPAN_M) < 1e-9, + ); +}); + +test('the native span and centre match the shipped asset', () => { + const glb = readFileSync( + new URL(`../../../public${ISS_MODEL_URL}`, import.meta.url), + ); + const jsonLength = glb.readUInt32LE(12); + const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8')); + const root = gltf.nodes[gltf.scenes[0].nodes[0]]; + const min = [Infinity, Infinity, Infinity]; + const max = [-Infinity, -Infinity, -Infinity]; + // Every node below the root rests untransformed (joint nodes included), so + // each mesh's bounds are already in the root's frame. + const visit = (index) => { + const node = gltf.nodes[index]; + assert.equal(node.rotation ?? null, null); + assert.equal(node.scale ?? null, null); + assert.equal(node.translation ?? null, null); + for (const primitive of gltf.meshes[node.mesh]?.primitives ?? []) { + const accessor = gltf.accessors[primitive.attributes.POSITION]; + for (let i = 0; i < 3; i++) { + min[i] = Math.min(min[i], accessor.min[i]); + max[i] = Math.max(max[i], accessor.max[i]); + } + } + (node.children ?? []).forEach(visit); + }; + root.children.forEach(visit); + // The truss is the longest axis, glTF X. + assert.ok(Math.abs(max[0] - min[0] - ISS_MODEL_NATIVE_SPAN) < 0.01); + assert.ok(max[0] - min[0] > max[1] - min[1]); + assert.ok(max[0] - min[0] > max[2] - min[2]); + ISS_MODEL_CENTER_NATIVE.forEach((value, i) => + assert.ok(Math.abs((min[i] + max[i]) / 2 - value) < 0.01), + ); + // The scene root moves that centre to the origin: minimumPixelSize scales + // the model about its origin, so the far-range model stays centred. + assert.deepEqual( + root.translation.map((value, i) => value + ISS_MODEL_CENTER_NATIVE[i]), + [0, 0, 0], + ); + // NASA's own textures ship with it. + assert.ok(gltf.textures.length > 0); +}); + +test('the model axes are a proper rotation of the flight axes', () => { + // A cyclic order of x, y, z keeps the frame right-handed (no mirroring). + const order = ISS_MODEL_LOCAL_AXES.join(''); + assert.ok(['xyz', 'yzx', 'zxy'].includes(order)); +}); + +test('flight axes: orthonormal, z away from the Earth, x along the motion', () => { + const satrec = twoline2satrec(ISS_TLE[0], ISS_TLE[1]); + for (const minutes of [0, 17, 46, 80]) { + const date = new Date(Date.UTC(2024, 0, 1, 12, minutes)); + const { position, velocity } = propagate(satrec, date); + const gmst = gstime(date); + const r = temeToEcefAxes(position, gmst); + const v = temeToEcefAxes(velocity, gmst); + const axes = issFlightAxes(r, v); + for (const key of ['x', 'y', 'z']) + assert.ok(Math.abs(norm(axes[key]) - 1) < 1e-9); + assert.ok(Math.abs(dot(axes.x, axes.y)) < 1e-9); + assert.ok(Math.abs(dot(axes.y, axes.z)) < 1e-9); + assert.ok(Math.abs(dot(axes.x, axes.z)) < 1e-9); + const rUnit = [r.x, r.y, r.z].map((c) => c / norm([r.x, r.y, r.z])); + assert.ok(dot(axes.z, rUnit) > 0.999999); + // A near-circular orbit: the along-track axis is almost the velocity. + const vUnit = [v.x, v.y, v.z].map((c) => c / norm([v.x, v.y, v.z])); + assert.ok(dot(axes.x, vUnit) > 0.999); + // Right-handed: x × y = z. + const cross = [ + axes.x[1] * axes.y[2] - axes.x[2] * axes.y[1], + axes.x[2] * axes.y[0] - axes.x[0] * axes.y[2], + axes.x[0] * axes.y[1] - axes.x[1] * axes.y[0], + ]; + assert.ok(dot(cross, axes.z) > 0.999999); + } +}); + +test('flight axes refuse a degenerate state', () => { + assert.equal(issFlightAxes({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), null); + assert.equal(issFlightAxes({ x: 1, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }), null); +}); + +test('TEME to Earth-fixed axes keeps the position eciToGeodetic uses', () => { + const v = temeToEcefAxes({ x: 1, y: 0, z: 0 }, Math.PI / 2); + assert.ok(Math.abs(v.x) < 1e-12); + assert.ok(Math.abs(v.y + 1) < 1e-12); +}); diff --git a/src/layers/satellites/issMounts.js b/src/layers/satellites/issMounts.js new file mode 100644 index 0000000000..9d5efd6cd1 --- /dev/null +++ b/src/layers/satellites/issMounts.js @@ -0,0 +1,257 @@ +import { msg } from '../../i18n/index.js'; + +/** + * Where the Cockpit camera sits when it rides the station. The ISS has + * several catalog entries that are one body (the ISS itself, listed under + * Zarya, its first module; Nauka; whatever vehicle is docked). Riding any of + * them looks out from a point on its 3D model, away from the station, in + * place of the straight-down picture every other satellite has, and the + * Cockpit steps between the views: from Nauka, from Zarya, from Poisk, from + * the Cupola, from Kibo, from a docked vehicle. Each looks outward, in a direction of its own, and the + * arrows turn the view from there. From this height the Earth's limb is 20° + * below level: a view 30° down has it across its upper part. + * + * The points were chosen by casting rays across the view against the model + * at rest: each is over a meter clear of every surface, and at most a tenth + * of its frame meets the station, none of it nearer than 12 m. + * + * Points and directions are on the model's axes in meters (X port, Y zenith, + * Z forward), from the model's origin: the frame the file's nodes sit in. + */ + +/** + * The station's modules that have catalog entries of their own, beside the + * ISS's (ISS_NORAD in policy.js, listed as "ISS (ZARYA)"): Nauka and Poisk. + */ +export const ISS_NAUKA_NORAD = 49044; +export const ISS_POISK_NORAD = 36086; + +const mount = (eye, forward, up) => + Object.freeze({ + eye: Object.freeze(eye), + forward: Object.freeze(forward), + up: Object.freeze(up), + }); + +export const ISS_MOUNTS = Object.freeze({ + /** + * Nauka hangs below Zvezda, pointing at the Earth: from the port side of + * its lower end, looking out ahead of the station to port and down. + */ + nauka: mount([3.03, -12, -24.25], [0.75, -0.5, 0.43], [0, 1, 0]), + /** + * Zarya lies along the station's long axis, docked at both ends, so it + * looks out sideways: from its port side, out across the track and down. + */ + zarya: mount([3.38, 2.96, -22], [0.87, -0.5, 0], [0, 1, 0]), + /** + * Poisk stands on top of Zvezda, pointing away from the Earth: from the + * top of it, looking out behind the station to starboard, the limb across + * the middle of the frame. + */ + poisk: mount([-1.27, 12, -27.27], [-0.66, -0.34, -0.66], [0, 1, 0]), + /** + * A docked vehicle (a Progress, a Soyuz, a Dragon): the catalog does not + * say which port it is on, so it takes the place of one on Zvezda's aft + * port, the most used: looking out behind the station and down, the Earth + * falling away. + */ + docked: mount([0, 2.05, -41.5], [0, -0.5, -0.87], [0, 1, 0]), + /** + * The Cupola, on Tranquility's Earth-facing port: from just below it, + * looking aft along the station and down, the Russian segment (Zvezda, + * Nauka, the docked vehicles) in the corner and the Earth beyond. + */ + cupola: mount([8.3, -3.2, -4.9], [0, -0.5, -0.87], [0, 1, 0]), + /** + * Kibo, on Harmony's port side: its two windows are on its port end, above + * the airlock. From just outside them, looking out to port and down over + * the Exposed Facility, the Earth beyond it. The port solar arrays turn + * through this view as they follow the Sun, as they do past the windows. + */ + kibo: mount([15.4, 4.2, 11], [0.81, -0.5, -0.3], [0, 1, 0]), +}); + +/** + * The card a view shows in place of its catalog entry's, for a module the + * catalog has no entry for. Its texts are marked for translation; the name + * is the module's, as catalog names are. + */ +export const ISS_MOUNT_CARDS = Object.freeze({ + cupola: Object.freeze({ + name: 'CUPOLA', + classLabel: msg('OBSERVATION MODULE · ISS'), + operator: msg('European Space Agency (ESA)'), + facts: Object.freeze([ + msg('7 WINDOWS'), + msg('LAUNCHED 8 FEB 2010 · STS-130'), + msg('TRANQUILITY · EARTH-FACING PORT'), + ]), + }), + kibo: Object.freeze({ + name: 'KIBO', + classLabel: msg('LABORATORY MODULE · ISS'), + operator: msg('Japan Aerospace Exploration Agency (JAXA)'), + facts: Object.freeze([ + msg('2 WINDOWS'), + msg('LAUNCHED 31 MAY 2008 · STS-124'), + msg('HARMONY · PORT SIDE'), + ]), + }), +}); + +/** + * The views in the order the Cockpit steps through them. The first is the + * one it opens on, whichever of the station's entries was selected. + */ +export const ISS_MOUNT_ORDER = Object.freeze([ + 'nauka', + 'zarya', + 'poisk', + 'cupola', + 'kibo', + 'docked', +]); + +/** + * The views the station offers now, in ISS_MOUNT_ORDER. Nauka, Zarya and + * Poisk are part of the model, so they are always there; the docked-vehicle + * view is offered only while a vehicle is docked, under that vehicle's name. + * Each view names the catalog entry it belongs to (the ISS itself for + * Zarya), so the Cockpit can ride that entry and its card describe it; null + * when the catalog has no entry for it. The Cupola and Kibo have none: they + * ride the ISS's and carry cards of their own (ISS_MOUNT_CARDS). + * @param {{naukaName?: string|null, zaryaName?: string|null, + * poiskName?: string|null, dockedName?: string|null, + * naukaNorad?: number|null, zaryaNorad?: number|null, + * poiskNorad?: number|null, dockedNorad?: number|null}} [entries] + * Catalog names (e.g. "ISS (NAUKA)") and numbers. + * @returns {Array<{key: 'nauka'|'zarya'|'poisk'|'cupola'|'kibo'|'docked', + * label: string, noradId: number|null, card: object|null}>} + */ +export function issMountViews({ + naukaName, + zaryaName, + poiskName, + dockedName, + naukaNorad = null, + zaryaNorad = null, + poiskNorad = null, + dockedNorad = null, +} = {}) { + const labels = { + nauka: issMountLabel(naukaName) || 'NAUKA', + zarya: issMountLabel(zaryaName) || 'ZARYA', + poisk: issMountLabel(poiskName) || 'POISK', + cupola: ISS_MOUNT_CARDS.cupola.name, + kibo: ISS_MOUNT_CARDS.kibo.name, + docked: issMountLabel(dockedName), + }; + const entries = { + nauka: naukaNorad, + zarya: zaryaNorad, + poisk: poiskNorad, + cupola: zaryaNorad, + kibo: zaryaNorad, + docked: dockedNorad, + }; + return ISS_MOUNT_ORDER.filter((key) => labels[key]).map((key) => ({ + key, + label: labels[key], + noradId: Number.isFinite(entries[key]) ? entries[key] : null, + card: ISS_MOUNT_CARDS[key] ?? null, + })); +} + +/** + * The view to show: the one asked for while it is on offer, else the first. + * @param {Array<{key: string, label: string}>} views From issMountViews. + * @param {string|null|undefined} key + * @returns {{key: string, label: string}} + */ +export function issMountView(views, key) { + return views.find((view) => view.key === key) ?? views[0]; +} + +/** + * The view after the current one, wrapping round; null with fewer than two. + * @param {Array<{key: string, label: string}>} views + * @param {string|null|undefined} key The current view. + * @returns {{key: string, label: string}|null} + */ +export function issNextMountView(views, key) { + if (!Array.isArray(views) || views.length < 2) return null; + const index = views.findIndex((view) => view.key === key); + return views[(index + 1) % views.length]; +} + +/** + * The view before the current one, wrapping round; null with fewer than two. + * An unknown current view steps back to the last. + * @param {Array<{key: string, label: string}>} views + * @param {string|null|undefined} key The current view. + * @returns {{key: string, label: string}|null} + */ +export function issPreviousMountView(views, key) { + if (!Array.isArray(views) || views.length < 2) return null; + const index = views.findIndex((view) => view.key === key); + return views[(Math.max(index, 0) - 1 + views.length) % views.length]; +} + +/** + * The name the Cockpit shows for the view: the entry's own, without the + * "ISS (…)" the catalog wraps the station's modules in. + * @param {string|null|undefined} name Catalog name, e.g. "ISS (ZARYA)". + * @returns {string} + */ +export function issMountLabel(name) { + const text = String(name ?? '').trim(); + const inner = /^ISS\s*\((.+)\)$/i.exec(text); + return (inner ? inner[1] : text).trim(); +} + +const add = (a, b, k) => [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k]; +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const unit = (v) => { + const length = Math.hypot(v[0], v[1], v[2]); + return [v[0] / length, v[1] / length, v[2] / length]; +}; +const cross = (a, b) => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +const point = (v) => ({ x: v[0], y: v[1], z: v[2] }); + +/** + * A mount in the world: the eye point and the view's frame, Earth-fixed. + * The model is placed with its forward axis along the flight direction, its + * port axis along the orbit normal and its zenith axis away from the Earth + * (issFlightAxes), so a model vector [port, zenith, forward] is + * port × axes.y + zenith × axes.z + forward × axes.x. + * @param {{eye: number[], forward: number[], up: number[]}} mount + * @param {{x: number, y: number, z: number}} centre The model's origin. + * @param {{x: number[], y: number[], z: number[]}} axes Flight axes. + * @returns {{position: object, direction: object, up: object, right: object}} + * `{x, y, z}` vectors; direction, up and right are unit and perpendicular, + * right = direction × up. + */ +export function issMountWorld(mount, centre, axes) { + const toWorld = ([port, zenith, forward]) => + add(add(add([0, 0, 0], axes.y, port), axes.z, zenith), axes.x, forward); + const direction = unit(toWorld(mount.forward)); + // Up, squared to the direction: the mount's own need not be exact. + const rough = toWorld(mount.up); + const up = unit(add(rough, direction, -dot(rough, direction))); + const offset = toWorld(mount.eye); + return { + position: { + x: centre.x + offset[0], + y: centre.y + offset[1], + z: centre.z + offset[2], + }, + direction: point(direction), + up: point(up), + right: point(cross(direction, up)), + }; +} diff --git a/src/layers/satellites/issMounts.test.mjs b/src/layers/satellites/issMounts.test.mjs new file mode 100644 index 0000000000..68a6c85b19 --- /dev/null +++ b/src/layers/satellites/issMounts.test.mjs @@ -0,0 +1,183 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + ISS_MOUNTS, + ISS_MOUNT_CARDS, + ISS_MOUNT_ORDER, + ISS_NAUKA_NORAD, + ISS_POISK_NORAD, + issMountLabel, + issMountView, + issMountViews, + issMountWorld, + issNextMountView, + issPreviousMountView, +} from './issMounts.js'; +import { ISS_MODEL_NATIVE_SPAN, ISS_NORAD } from './policy.js'; + +const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z; +const length = (a) => Math.hypot(a.x, a.y, a.z); + +/** Key, label and entry of each view: what the Cockpit steps through. */ +const summary = (views) => + views.map(({ key, label, noradId }) => ({ key, label, noradId })); + +test('the station offers its views in order, Nauka first', () => { + assert.deepEqual( + [...ISS_MOUNT_ORDER], + ['nauka', 'zarya', 'poisk', 'cupola', 'kibo', 'docked'], + ); + for (const key of ISS_MOUNT_ORDER) assert.ok(ISS_MOUNTS[key]); + assert.equal(new Set([ISS_NORAD, ISS_NAUKA_NORAD, ISS_POISK_NORAD]).size, 3); + // Each view names the entry it belongs to, for the Cockpit to ride. The + // Cupola and Kibo have no entries of their own: they ride the ISS's. + const views = issMountViews({ + naukaName: 'ISS (NAUKA)', + zaryaName: 'ISS (ZARYA)', + poiskName: 'POISK', + dockedName: 'PROGRESS-MS 34', + naukaNorad: ISS_NAUKA_NORAD, + zaryaNorad: ISS_NORAD, + poiskNorad: ISS_POISK_NORAD, + dockedNorad: 68837, + }); + assert.deepEqual(summary(views), [ + { key: 'nauka', label: 'NAUKA', noradId: ISS_NAUKA_NORAD }, + { key: 'zarya', label: 'ZARYA', noradId: ISS_NORAD }, + { key: 'poisk', label: 'POISK', noradId: ISS_POISK_NORAD }, + { key: 'cupola', label: 'CUPOLA', noradId: ISS_NORAD }, + { key: 'kibo', label: 'KIBO', noradId: ISS_NORAD }, + { key: 'docked', label: 'PROGRESS-MS 34', noradId: 68837 }, + ]); + // Only the modules without an entry carry cards of their own. + assert.deepEqual( + views.filter((view) => view.card).map((view) => view.key), + ['cupola', 'kibo'], + ); + // No vehicle docked: no view from one. The modules are part of the model, + // so they are offered even when the catalog has no entry for them; such a + // view has no entry to ride. + assert.deepEqual(summary(issMountViews({ zaryaName: 'ISS (ZARYA)' })), [ + { key: 'nauka', label: 'NAUKA', noradId: null }, + { key: 'zarya', label: 'ZARYA', noradId: null }, + { key: 'poisk', label: 'POISK', noradId: null }, + { key: 'cupola', label: 'CUPOLA', noradId: null }, + { key: 'kibo', label: 'KIBO', noradId: null }, + ]); + assert.deepEqual( + issMountViews().map(({ key }) => key), + ['nauka', 'zarya', 'poisk', 'cupola', 'kibo'], + ); +}); + +test('the Cupola’s card names it and gives its facts, marked for translation', () => { + const card = ISS_MOUNT_CARDS.cupola; + assert.equal(card.name, 'CUPOLA'); + assert.equal(card.classLabel, 'OBSERVATION MODULE · ISS'); + assert.equal(card.operator, 'European Space Agency (ESA)'); + assert.deepEqual( + [...card.facts], + [ + '7 WINDOWS', + 'LAUNCHED 8 FEB 2010 · STS-130', + 'TRANQUILITY · EARTH-FACING PORT', + ], + ); +}); + +test('Kibo’s card names it and gives its facts, marked for translation', () => { + const card = ISS_MOUNT_CARDS.kibo; + assert.equal(card.name, 'KIBO'); + assert.equal(card.classLabel, 'LABORATORY MODULE · ISS'); + assert.equal(card.operator, 'Japan Aerospace Exploration Agency (JAXA)'); + assert.deepEqual( + [...card.facts], + ['2 WINDOWS', 'LAUNCHED 31 MAY 2008 · STS-124', 'HARMONY · PORT SIDE'], + ); +}); + +test('the view shown is the one asked for, else the first; the next wraps round', () => { + const views = issMountViews({ dockedName: 'SOYUZ-MS 28' }); + assert.equal(issMountView(views, null).key, 'nauka'); + assert.equal(issMountView(views, undefined).key, 'nauka'); + assert.equal(issMountView(views, 'zarya').key, 'zarya'); + assert.equal(issMountView(views, 'docked').label, 'SOYUZ-MS 28'); + // A view no longer on offer (the vehicle undocked) falls back to the first. + assert.equal(issMountView(issMountViews(), 'docked').key, 'nauka'); + + assert.equal(issNextMountView(views, 'nauka').key, 'zarya'); + assert.equal(issNextMountView(views, 'zarya').key, 'poisk'); + assert.equal(issNextMountView(views, 'poisk').key, 'cupola'); + assert.equal(issNextMountView(views, 'cupola').key, 'kibo'); + assert.equal(issNextMountView(views, 'kibo').key, 'docked'); + assert.equal(issNextMountView(views, 'docked').key, 'nauka'); + assert.equal(issNextMountView(views, 'unknown').key, 'nauka'); + assert.equal(issNextMountView(views.slice(0, 1), 'nauka'), null); + assert.equal(issNextMountView(null, 'nauka'), null); + + assert.equal(issPreviousMountView(views, 'nauka').key, 'docked'); + assert.equal(issPreviousMountView(views, 'docked').key, 'kibo'); + assert.equal(issPreviousMountView(views, 'zarya').key, 'nauka'); + assert.equal(issPreviousMountView(views, 'unknown').key, 'docked'); + assert.equal(issPreviousMountView(views.slice(0, 1), 'nauka'), null); + assert.equal(issPreviousMountView(null, 'nauka'), null); +}); + +test('the view is named after the entry, without the catalog’s "ISS (…)"', () => { + assert.equal(issMountLabel('ISS (ZARYA)'), 'ZARYA'); + assert.equal(issMountLabel(' ISS (NAUKA) '), 'NAUKA'); + assert.equal(issMountLabel('PROGRESS-MS 34'), 'PROGRESS-MS 34'); + assert.equal(issMountLabel(null), ''); +}); + +test('every mount is on or beside the model, with a usable view frame', () => { + for (const [key, { eye, forward, up }] of Object.entries(ISS_MOUNTS)) { + // Within the station's own size of its centre: on it or just off its end. + assert.ok(Math.hypot(...eye) < ISS_MODEL_NATIVE_SPAN / 2, key); + assert.ok(Math.hypot(...forward) > 0.5, key); + // Up is not along the view, so the frame can be squared. + const cos = + (forward[0] * up[0] + forward[1] * up[1] + forward[2] * up[2]) / + (Math.hypot(...forward) * Math.hypot(...up)); + assert.ok(Math.abs(cos) < 0.9, key); + } +}); + +test('a mount goes to the world on the axes the model is placed with', () => { + // Flight axes: x along-track, y the orbit normal, z zenith. + const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] }; + const centre = { x: 6_800_000, y: 0, z: 0 }; + // Model axes are [port, zenith, forward]: forward is along-track, zenith + // is away from the Earth, port is the orbit normal. + const world = issMountWorld( + { eye: [3, 5, -7], forward: [0, 0, 1], up: [0, 1, 0] }, + centre, + axes, + ); + assert.deepEqual(world.position, { x: 6_800_005, y: -7, z: 3 }); + assert.deepEqual(world.direction, { x: 0, y: 1, z: 0 }); + assert.deepEqual(world.up, { x: 1, y: 0, z: 0 }); + // right = direction × up. + assert.deepEqual(world.right, { x: 0, y: 0, z: -1 }); +}); + +test('the view frame is unit and square whatever the mount says', () => { + const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] }; + const centre = { x: 1, y: 2, z: 3 }; + for (const mount of [ + ...Object.values(ISS_MOUNTS), + // Lengths off, and an up that leans into the view. + { eye: [0, 0, 0], forward: [0, -3, 4], up: [0, 2, 1] }, + ]) { + const { direction, up, right } = issMountWorld(mount, centre, axes); + for (const v of [direction, up, right]) + assert.ok(Math.abs(length(v) - 1) < 1e-12); + assert.ok(Math.abs(dot(direction, up)) < 1e-12); + assert.ok(Math.abs(dot(direction, right)) < 1e-12); + assert.ok(Math.abs(dot(up, right)) < 1e-12); + } + // The eye is the mount's distance from the centre. + const { position } = issMountWorld(ISS_MOUNTS.docked, centre, axes); + const offset = Math.hypot(position.x - 1, position.y - 2, position.z - 3); + assert.ok(Math.abs(offset - Math.hypot(...ISS_MOUNTS.docked.eye)) < 1e-9); +}); diff --git a/src/layers/satellites/issStation.js b/src/layers/satellites/issStation.js new file mode 100644 index 0000000000..11724f4597 --- /dev/null +++ b/src/layers/satellites/issStation.js @@ -0,0 +1,227 @@ +import { msg } from '../../i18n/index.js'; +import { ISS_ARM_JOINTS } from './issArticulation.js'; +import { issCommandFastOrbit } from './issCommand.js'; +import { ISS_NORAD } from './policy.js'; +import { trackedStation } from './stationModels.js'; + +const unit = (v) => { + const n = Math.hypot(...v); + return v.map((c) => c / n); +}; + +/** + * The Sun positions Manual offers, on the model's axes (port, zenith, + * forward), and whether the station is lit there. + */ +export const ISS_SUN_POSES = Object.freeze([ + { id: 'overhead', label: msg('Overhead'), sun: [0, 1, 0], sunlit: true }, + { id: 'ahead', label: msg('Ahead'), sun: unit([0, 0.05, 1]), sunlit: true }, + { + id: 'behind', + label: msg('Behind'), + sun: unit([0, 0.05, -1]), + sunlit: true, + }, + { + id: 'below', + label: msg('Underneath'), + sun: unit([0, -1, 0.05]), + sunlit: true, + }, + { + id: 'port', + label: msg('Port side'), + sun: unit([0.8, 0.5, 0.3]), + sunlit: true, + }, + { + id: 'starboard', + label: msg('Starboard side'), + sun: unit([-0.8, 0.5, 0.3]), + sunlit: true, + }, + { id: 'night', label: msg('Night (shadow)'), sun: [0, -1, 0], sunlit: false }, +]); + +/** A seven-joint arm's slider labels, base to tip (Tiangong's arms share them). */ +export const ISS_ARM_LABELS = Object.freeze([ + msg('Shoulder roll'), + msg('Shoulder yaw'), + msg('Shoulder pitch'), + msg('Elbow'), + msg('Wrist pitch'), + msg('Wrist yaw'), + msg('Wrist roll'), +]); + +/** + * The ISS as the STATION section describes it (stationPanel.js): its joint + * driver and telemetry from the model part, and the Manual controls the + * command panel offered: the Sun's position or a fast orbit, folding the + * arrays and radiators as a demonstration, aiming the dishes, posing + * Canadarm2 by joint. + * @param {{state: object, parts: object}} context + * @returns {import('./stationPanel.js').StationDescription} + */ +export function issStationDescription({ state: layerState, parts }) { + return { + key: 'iss', + title: 'ISS', // i18n-ignore: the station's name + // stationModels.js says which station the tracked entry belongs to. + selected: () => trackedStation(layerState, parts)?.norad === ISS_NORAD, + subjectName: () => + layerState._catalog.get(layerState._trackedNorad)?.name?.trim() || + `ISS · NORAD ${ISS_NORAD}`, + articulation: () => parts.issModel?._articulation ?? null, + telemetry: () => { + // The feed is read only while the model is drawn; away from it there + // is no signal to report, and a stale answer would read as lost. + if ((parts.issModel?._visualPosition?.() ?? null) === null) + return { state: 'idle', poseAgeMs: null, liveUntilMs: null }; + return parts.issModel?._telemetryStatus?.() ?? null; + }, + // The model's centre, else this frame's tracked sample, else the dot as + // the rendering part draws it. + position: () => + parts.issModel?._visualPosition?.() ?? + layerState._trackedFrameCartesian ?? + parts.rendering?._pointPosition?.(ISS_NORAD) ?? + null, + zoomLabel: msg('Zoom to the ISS'), + notes: { + live: msg( + "Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.", + ), + computed: msg( + 'Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.', + ), + }, + groups: [ + { + id: 'sun', + label: msg('Sun position'), + kind: 'choices', + choices: [ + { + id: 'follow', + label: msg('Follow the Sun'), + isDefault: true, + apply: (a) => a.setOverride(null), + }, + ...ISS_SUN_POSES.map(({ id, label, sun, sunlit }) => ({ + id, + label, + apply: (a) => { + const fixed = { sun, sunlit }; + a.setOverride(() => fixed); + }, + })), + { + id: 'orbit', + label: msg('Fast orbit (40 s)'), + apply: (a) => { + const start = Date.now(); + a.setOverride((nowMs) => issCommandFastOrbit(nowMs - start)); + }, + }, + ], + }, + { + id: 'arrays', + label: msg('Solar arrays'), + note: msg('Demonstration: the real arrays stay extended.'), + kind: 'choices', + choices: [ + { + id: 'retract', + label: msg('Retract'), + apply: (a) => a.setDeploy(false), + }, + { + id: 'extend', + label: msg('Extend'), + isDefault: true, + apply: (a) => a.setDeploy(true), + }, + ], + }, + { + id: 'radiators', + label: msg('Radiators'), + note: msg( + 'Demonstration: the real radiators can fold but stay extended.', + ), + kind: 'choices', + choices: [ + { + id: 'retract', + label: msg('Retract'), + apply: (a) => a.setRadiatorDeploy(false), + }, + { + id: 'extend', + label: msg('Extend'), + isDefault: true, + apply: (a) => a.setRadiatorDeploy(true), + }, + ], + }, + { + id: 'dishes', + label: msg('Dishes'), + kind: 'choices', + choices: [ + { + id: 'relays', + label: msg('Relay satellites'), + isDefault: true, + apply: (a) => a.setDishOverride(null), + }, + { + id: 'up', + label: msg('Up'), + apply: (a) => a.setDishOverride([0, 1, 0]), + }, + { + id: 'forward', + label: msg('Forward'), + apply: (a) => a.setDishOverride(unit([0, 0.35, 0.94])), + }, + { + id: 'sideways', + label: msg('Sideways'), + apply: (a) => a.setDishOverride(unit([0.94, 0.35, 0])), + }, + ], + }, + { + id: 'arm', + label: msg('Canadarm2 (degrees)'), + kind: 'sliders', + resume: msg('Resume sway'), + sliders: ISS_ARM_JOINTS.map((joint, i) => ({ + id: joint.node, + label: ISS_ARM_LABELS[i], + min: -120, + max: 120, + apply: (a, value) => + a.setJoint( + joint.node, + joint.pivot, + joint.axis, + (value * Math.PI) / 180, + ), + })), + resumeApply: (a) => a.resumeArm(), + }, + ], + automatic: (a) => { + a.setTelemetryAllowed?.(true); + a.setOverride(null); + a.setDishOverride(null); + a.setDeploy(true); + a.setRadiatorDeploy(true); + a.resumeArm(); + }, + }; +} diff --git a/src/layers/satellites/issTelemetry.js b/src/layers/satellites/issTelemetry.js new file mode 100644 index 0000000000..fb9402ebc0 --- /dev/null +++ b/src/layers/satellites/issTelemetry.js @@ -0,0 +1,301 @@ +/** + * The ISS model's joints from NASA's public telemetry, when the server relays + * it (`/api/iss-telemetry`, off unless the operator sets + * `ISS_TELEMETRY_ENABLED=1`). Without it, or while the station has no signal, + * the joints keep the computed rules in issArticulation.js. + * + * How each telemetry angle maps onto a model joint was fitted against a + * recording of the feed, using the station's own attitude and position from + * the same feed: + * - the dish's two angles give a direction that stayed within 0.3° of a TDRS + * relay satellite across a hand-over between two of them; + * - the alpha joints' sign and zero put the arrays' masts square to the Sun; + * - each beta joint's sign is the one that turns its cell side toward the Sun + * (the other sign faces it about 45° away). The arrays then sat 5° to 9° + * off the Sun, which is where the real station held them. + * The radiator joints did not move during the recording, so their sign is the + * better of the two candidates on a parked joint, not a fit. + */ + +/** The route the server relays the feed at. */ +export const ISS_TELEMETRY_URL = '/api/iss-telemetry'; + +const DEG = Math.PI / 180; + +/** Alpha joints (SARJ), in ISS_ALPHA_JOINTS order: port, starboard. */ +export const ISS_TELEMETRY_ALPHA = Object.freeze([ + Object.freeze({ item: 'S0000004', sign: 1 }), + Object.freeze({ item: 'S0000003', sign: -1 }), +]); + +/** + * Beta joints (BGA), in ISS_BETA_JOINTS order: 2A, 4A, 2B, 4B, 1A, 3A, 1B, + * 3B. The model's angle is `sign × telemetry + 90°`: at 0° or 180° an array + * stands square to the truss, which is the model's ±90°. + */ +export const ISS_TELEMETRY_BETA = Object.freeze([ + Object.freeze({ item: 'P4000007', sign: 1 }), + Object.freeze({ item: 'P4000008', sign: -1 }), + Object.freeze({ item: 'P6000008', sign: -1 }), + Object.freeze({ item: 'P6000007', sign: 1 }), + Object.freeze({ item: 'S4000007', sign: -1 }), + Object.freeze({ item: 'S4000008', sign: 1 }), + Object.freeze({ item: 'S6000008', sign: 1 }), + Object.freeze({ item: 'S6000007', sign: -1 }), +]); + +/** Radiator joints (TRRJ), in ISS_RADIATOR_JOINTS order: port, starboard. */ +export const ISS_TELEMETRY_GAMMA = Object.freeze([ + Object.freeze({ item: 'S0000002', sign: 1 }), + Object.freeze({ item: 'S0000001', sign: 1 }), +]); + +/** The Ku-band dish: elevation and cross-elevation. */ +export const ISS_TELEMETRY_DISH = Object.freeze({ + elevation: 'Z1000014', + crossElevation: 'Z1000015', +}); + +/** + * Where the dish points, on the model's axes (port, zenith, forward), from + * its two gimbal angles: zenith at rest, cross-elevation leans it to port, + * elevation then tips it aft. + * @param {number} elevationDeg + * @param {number} crossElevationDeg + * @returns {number[]} Unit vector. + */ +export function issTelemetryDishDirection(elevationDeg, crossElevationDeg) { + const el = elevationDeg * DEG; + const xel = crossElevationDeg * DEG; + return [ + Math.sin(xel), + Math.cos(el) * Math.cos(xel), + -Math.sin(el) * Math.cos(xel), + ]; +} + +/** + * The joint angles a telemetry snapshot gives, as the model turns them. + * @param {Record|null|undefined} items The + * relay's `items`: each item's value and the time it was true at. + * @returns {{alpha: number[], beta: number[], gamma: number[], + * dish: number[]|null}|null} Radians, in the joint lists' order; null + * unless every array and radiator joint is present. `dish` is null when + * its angles are missing. + */ +export function issTelemetryPose(items) { + if (!items) return null; + const read = (item) => { + const value = items[item]?.[0]; + return Number.isFinite(value) ? value : null; + }; + const turn = (list, offsetDeg) => + list.map(({ item, sign }) => { + const value = read(item); + return value === null ? null : (sign * value + offsetDeg) * DEG; + }); + const alpha = turn(ISS_TELEMETRY_ALPHA, 0); + const beta = turn(ISS_TELEMETRY_BETA, 90); + const gamma = turn(ISS_TELEMETRY_GAMMA, 0); + if ([...alpha, ...beta, ...gamma].includes(null)) return null; + const el = read(ISS_TELEMETRY_DISH.elevation); + const xel = read(ISS_TELEMETRY_DISH.crossElevation); + return { + alpha, + beta, + gamma, + dish: + el === null || xel === null ? null : issTelemetryDishDirection(el, xel), + }; +} + +/** How often the relay is asked while the model is on screen. */ +export const ISS_TELEMETRY_POLL_MS = 5_000; +/** A snapshot older than this is not used: the joints go back to their rules. */ +export const ISS_TELEMETRY_FRESH_MS = 20_000; + +/** + * The newest moment any of the relay's items was true at: when the feed + * last had data, as far as this answer tells. + * @param {Record|null|undefined} items + * @returns {number|null} Epoch ms, or null without a dated item. + */ +export function issTelemetryLatestEpoch(items) { + let latest = null; + for (const entry of Object.values(items ?? {})) { + const epoch = Array.isArray(entry) ? Number(entry[1]) : NaN; + // An item with no time has 0 there, which is no date. + if ( + epoch > 0 && + Number.isFinite(epoch) && + (latest === null || epoch > latest) + ) + latest = epoch; + } + return latest; +} +/** The feed stops asking this long after the model was last drawn. */ +const WANTED_MS = 10_000; +const REQUEST_TIMEOUT_MS = 5_000; +/** After a failed request the next one waits this long. */ +const FAILURE_WAIT_MS = 30_000; + +/** + * Polls the relay while the model is drawn. `touch()` each frame the model + * shows keeps it asking; it stops by itself when the touches stop, and for + * good once the server says the relay is not switched on. + * @param {{fetchImpl?: typeof fetch, now?: () => number, + * setTimer?: (fn: () => void, ms: number) => unknown, + * clearTimer?: (id: unknown) => void}} [options] + */ +export function createIssTelemetryFeed({ + fetchImpl = (...args) => globalThis.fetch(...args), + now = Date.now, + setTimer = (fn, ms) => setTimeout(fn, ms), + clearTimer = (id) => clearTimeout(id), +} = {}) { + /** False once the server answered that the relay is off. */ + let configured = null; + let lastTouchAt = null; + let timer = null; + let requesting = false; + /** Bumped by destroy, so a request in flight cannot write after it. */ + let generation = 0; + let pose = null; + let poseAt = null; + /** What the relay last said and when, for the station panel's status line. */ + let relayStatus = null; + let answeredAt = null; + let failures = 0; + /** When the relay last reported signal; the "no signal since" time. */ + let liveUntil = null; + + async function request() { + const mine = generation; + requesting = true; + const controller = new AbortController(); + const deadline = setTimer(() => controller.abort(), REQUEST_TIMEOUT_MS); + let wait = ISS_TELEMETRY_POLL_MS; + try { + const response = await fetchImpl(ISS_TELEMETRY_URL, { + signal: controller.signal, + cache: 'no-store', + }); + if (!response.ok) throw new Error('unavailable'); + const body = await response.json(); + if (mine !== generation) return; + if (body?.configured !== true) { + configured = false; + pose = null; + return; + } + configured = true; + answeredAt = now(); + failures = 0; + relayStatus = typeof body.status === 'string' ? body.status : null; + const next = body.status === 'live' ? issTelemetryPose(body.items) : null; + pose = next; + poseAt = next ? now() : null; + if (next) liveUntil = poseAt; + // A page that opens during a loss of signal still learns when the + // feed last had data: the newest value the relay holds was true then. + else if (body.status === 'no-signal' && liveUntil === null) + liveUntil = issTelemetryLatestEpoch(body.items); + } catch { + if (mine !== generation) return; + failures += 1; + wait = FAILURE_WAIT_MS; + } finally { + clearTimer(deadline); + if (mine === generation) { + requesting = false; + schedule(wait); + } + } + } + + function wanted() { + return ( + configured !== false && + lastTouchAt !== null && + now() - lastTouchAt < WANTED_MS + ); + } + + function schedule(ms) { + if (timer !== null || requesting || !wanted()) return; + timer = setTimer(() => { + timer = null; + if (wanted()) request(); + }, ms); + } + + return { + /** The model is on screen: keep the feed asking. */ + touch() { + lastTouchAt = now(); + schedule(0); + }, + /** + * The joint angles to use now, or null: no relay, no signal, or the last + * answer is too old. + * @returns {{alpha: number[], beta: number[], gamma: number[], + * dish: number[]|null}|null} + */ + pose() { + if (!pose || poseAt === null) return null; + return now() - poseAt < ISS_TELEMETRY_FRESH_MS ? pose : null; + }, + /** Whether the server relays the feed: null until it has answered. */ + configured() { + return configured; + }, + /** + * Where the joints' angles stand, for the station panel: `live` with a + * fresh pose; `no-signal` while the relay is up but the station is out + * of contact; `unavailable` when the relay cannot be reached or is not + * connected; `disabled` when this server does not relay the feed; + * `pending` before the first answer. `poseAgeMs` is how old the last + * pose is, `liveUntilMs` when signal was last had (epoch ms), both null + * when there was none. + * @returns {{state: 'live'|'no-signal'|'unavailable'|'disabled'|'pending', + * poseAgeMs: number|null, liveUntilMs: number|null}} + */ + status() { + const at = now(); + const poseAgeMs = poseAt === null ? null : at - poseAt; + let state; + if (configured === false) state = 'disabled'; + // Never answered: still asking, or the route is not there (a 404, an + // HTML fallback page), which is unavailable rather than pending. + else if (configured === null) + state = failures > 0 ? 'unavailable' : 'pending'; + else if (pose && poseAgeMs < ISS_TELEMETRY_FRESH_MS) state = 'live'; + else if (failures === 0 && relayStatus === 'no-signal') + state = 'no-signal'; + else if ( + failures === 0 && + (relayStatus === 'connecting' || relayStatus === 'reconnecting') && + answeredAt !== null && + at - answeredAt < ISS_TELEMETRY_FRESH_MS + ) + state = 'pending'; + else state = 'unavailable'; + return { state, poseAgeMs, liveUntilMs: liveUntil }; + }, + destroy() { + generation += 1; + if (timer !== null) clearTimer(timer); + timer = null; + requesting = false; + lastTouchAt = null; + pose = null; + poseAt = null; + configured = null; + relayStatus = null; + answeredAt = null; + failures = 0; + liveUntil = null; + }, + }; +} diff --git a/src/layers/satellites/issTelemetry.test.mjs b/src/layers/satellites/issTelemetry.test.mjs new file mode 100644 index 0000000000..c77ed81beb --- /dev/null +++ b/src/layers/satellites/issTelemetry.test.mjs @@ -0,0 +1,511 @@ +import assert from 'node:assert/strict'; +import test, { after, before } from 'node:test'; +import * as Cesium from 'cesium'; +import { + ISS_ALPHA_JOINTS, + ISS_BETA_JOINTS, + ISS_DISH_JOINTS, + ISS_RADIATOR_JOINTS, + createIssArticulation, +} from './issArticulation.js'; +import { + issTelemetryLatestEpoch, + ISS_TELEMETRY_ALPHA, + ISS_TELEMETRY_BETA, + ISS_TELEMETRY_FRESH_MS, + ISS_TELEMETRY_GAMMA, + ISS_TELEMETRY_POLL_MS, + ISS_TELEMETRY_URL, + createIssTelemetryFeed, + issTelemetryDishDirection, + issTelemetryPose, +} from './issTelemetry.js'; + +// The joint driver asks Cesium for the Earth's orientation, which loads data +// over the network; without it Cesium's own fallback is used, as in the app +// before that data arrives. +const realIcrf = Cesium.Transforms.computeIcrfToFixedMatrix; +before(() => { + Cesium.Transforms.computeIcrfToFixedMatrix = () => undefined; +}); +after(() => { + Cesium.Transforms.computeIcrfToFixedMatrix = realIcrf; +}); + +const DEG = Math.PI / 180; +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const angleDeg = (a, b) => + Math.acos(Math.min(1, Math.max(-1, dot(a, b)))) / DEG; + +/** + * Two moments recorded from the feed on 13 November 2026, eleven minutes + * apart. `sun` and `relayDirection` are on the model's axes (port, zenith, + * forward), worked out from the station's own position and attitude in the + * same feed; the relay is the TDRS satellite the dish was aimed at. + */ +const RECORDED = [ + { + items: { + S0000004: [306.2512, 0], + S0000003: [53.7878, 0], + P4000007: [161.5045, 0], + P4000008: [198.4406, 0], + P6000008: [202.9449, 0], + P6000007: [161.0541, 0], + S4000007: [18.7427, 0], + S4000008: [341.3068, 0], + S6000008: [341.7682, 0], + S6000007: [18.8361, 0], + S0000002: [15.1868, 0], + S0000001: [24.8383, 0], + Z1000014: [-8.4924, 0], + Z1000015: [-31.6077, 0], + }, + sun: [0.45411, 0.5286, -0.7172], + relayDirection: [-0.5264, 0.84041, 0.12893], + }, + { + items: { + S0000004: [262.0807, 0], + S0000003: [97.9968, 0], + P4000007: [161.8451, 0], + P4000008: [198.2867, 0], + P6000008: [202.8131, 0], + P6000007: [161.4166, 0], + S4000007: [18.6932, 0], + S4000008: [341.7902, 0], + S6000008: [341.6089, 0], + S6000007: [18.4076, 0], + S0000002: [15.1923, 0], + S0000001: [24.8383, 0], + Z1000014: [39.5837, 0], + Z1000015: [-30.1135, 0], + }, + sun: [0.45807, -0.12024, -0.88075], + relayDirection: [-0.50436, 0.66714, -0.54822], + }, +]; + +/** + * An array's cell-side normal on the model's axes: ±X at rest, turned about + * the mast (Z) by beta, then about the truss (X) by alpha. + */ +function cellNormal(face, alpha, beta) { + const x = face * Math.cos(beta); + const y = face * Math.sin(beta); + return [x, Math.cos(alpha) * y, Math.sin(alpha) * y]; +} + +test('the joint lists line up with the model joints they drive', () => { + assert.equal(ISS_TELEMETRY_ALPHA.length, ISS_ALPHA_JOINTS.length); + assert.equal(ISS_TELEMETRY_BETA.length, ISS_BETA_JOINTS.length); + assert.equal(ISS_TELEMETRY_GAMMA.length, ISS_RADIATOR_JOINTS.length); + const items = [ + ...ISS_TELEMETRY_ALPHA, + ...ISS_TELEMETRY_BETA, + ...ISS_TELEMETRY_GAMMA, + ].map(({ item }) => item); + assert.equal(new Set(items).size, items.length, 'no item drives two joints'); +}); + +test('recorded telemetry turns every array toward where the Sun was', () => { + for (const { items, sun } of RECORDED) { + const pose = issTelemetryPose(items); + ISS_BETA_JOINTS.forEach(({ node, face }, i) => { + const alpha = pose.alpha[node.startsWith('PORT') ? 0 : 1]; + const off = angleDeg(cellNormal(face, alpha, pose.beta[i]), sun); + // The real arrays were held 5° to 9° off the Sun. + assert.ok(off < 11, `${node} is ${off.toFixed(1)}° off the Sun`); + }); + } +}); + +test('the other sign on any joint turns its arrays away from the Sun', () => { + const { items, sun } = RECORDED[0]; + const pose = issTelemetryPose(items); + ISS_BETA_JOINTS.forEach(({ node, face }, i) => { + const alpha = pose.alpha[node.startsWith('PORT') ? 0 : 1]; + // Beta with the opposite sign about its 90° zero. + const flipped = Math.PI - pose.beta[i]; + assert.ok(angleDeg(cellNormal(face, alpha, flipped), sun) > 35, node); + // Alpha with the opposite sign. + assert.ok(angleDeg(cellNormal(face, -alpha, pose.beta[i]), sun) > 35, node); + }); +}); + +test('the recorded dish angles point at the relay satellite', () => { + for (const { items, relayDirection } of RECORDED) { + const { dish } = issTelemetryPose(items); + assert.ok(Math.abs(Math.hypot(...dish) - 1) < 1e-9); + assert.ok(angleDeg(dish, relayDirection) < 0.5); + } + // At rest it looks at the zenith; cross-elevation leans to port, + // elevation tips aft. + assert.ok(angleDeg(issTelemetryDishDirection(0, 0), [0, 1, 0]) < 1e-6); + assert.ok(issTelemetryDishDirection(0, 30)[0] > 0); + assert.ok(issTelemetryDishDirection(30, 0)[2] < 0); +}); + +test('a snapshot missing a joint gives no pose; missing dish angles give no dish', () => { + const { items } = RECORDED[0]; + assert.equal(issTelemetryPose(null), null); + assert.equal(issTelemetryPose({}), null); + for (const item of ['S0000004', 'P6000007', 'S0000001']) { + const partial = { ...items }; + delete partial[item]; + assert.equal(issTelemetryPose(partial), null, item); + } + assert.equal( + issTelemetryPose({ ...items, S0000003: ['x', 0] }), + null, + 'a value that is not a number', + ); + const noDish = { ...items }; + delete noDish.Z1000015; + const pose = issTelemetryPose(noDish); + assert.equal(pose.dish, null); + assert.equal(pose.beta.length, 8); +}); + +/** A hand-moved clock with the timers set on it. */ +function fakeTime() { + const time = { ms: 1_000_000 }; + let timers = []; + let nextId = 1; + return { + now: () => time.ms, + setTimer(fn, ms) { + const id = nextId++; + timers.push({ id, at: time.ms + ms, fn }); + return id; + }, + clearTimer(id) { + timers = timers.filter((timer) => timer.id !== id); + }, + /** Move the clock on, running timers as they fall due. */ + async advance(ms) { + const end = time.ms + ms; + for (;;) { + // Let a finished request schedule its next timer first. + await new Promise((resolve) => setImmediate(resolve)); + const due = timers + .filter((timer) => timer.at <= end) + .sort((a, b) => a.at - b.at)[0]; + if (!due) break; + timers = timers.filter((timer) => timer !== due); + time.ms = Math.max(time.ms, due.at); + due.fn(); + } + time.ms = end; + await new Promise((resolve) => setImmediate(resolve)); + }, + }; +} + +/** A fetch that answers from a queue of bodies (or throws for an Error). */ +function fakeFetch(answers) { + const calls = []; + const fetchImpl = async (url, init) => { + calls.push({ url, init }); + const answer = answers.length > 1 ? answers.shift() : answers[0]; + if (answer instanceof Error) throw answer; + return { ok: true, json: async () => answer }; + }; + return { fetchImpl, calls }; +} + +const LIVE = { configured: true, status: 'live', items: RECORDED[0].items }; + +test('the feed asks only while the model is drawn, every five seconds', async () => { + const time = fakeTime(); + const { fetchImpl, calls } = fakeFetch([LIVE]); + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + await time.advance(60_000); + assert.equal(calls.length, 0, 'nothing is asked before the model shows'); + + feed.touch(); + await time.advance(0); + assert.equal(calls.length, 1); + assert.equal(calls[0].url, ISS_TELEMETRY_URL); + assert.equal(calls[0].init.cache, 'no-store'); + assert.equal(feed.configured(), true); + assert.deepEqual(feed.pose(), issTelemetryPose(RECORDED[0].items)); + + // Drawn for another 12 s: two more requests. + for (let i = 0; i < 12; i++) { + feed.touch(); + await time.advance(1000); + } + assert.equal(calls.length, 1 + Math.floor(12_000 / ISS_TELEMETRY_POLL_MS)); + + // Not drawn any more: it stops by itself, and the pose goes stale. + const drawn = calls.length; + await time.advance(60_000); + assert.ok(calls.length <= drawn + 2); + assert.equal(feed.pose(), null); + const settled = calls.length; + await time.advance(60_000); + assert.equal(calls.length, settled); +}); + +test('a relay that is switched off is asked once and never again', async () => { + const time = fakeTime(); + const { fetchImpl, calls } = fakeFetch([{ configured: false }]); + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + for (let i = 0; i < 30; i++) { + feed.touch(); + await time.advance(1000); + } + assert.equal(calls.length, 1); + assert.equal(feed.configured(), false); + assert.equal(feed.pose(), null); +}); + +test('no signal, a failed request or an old answer all give no pose', async () => { + const time = fakeTime(); + const { fetchImpl, calls } = fakeFetch([ + LIVE, + { configured: true, status: 'no-signal', items: RECORDED[0].items }, + LIVE, + new Error('offline'), + ]); + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + const drawFor = async (ms) => { + for (let t = 0; t < ms; t += 1000) { + feed.touch(); + await time.advance(1000); + } + }; + await drawFor(1000); + assert.ok(feed.pose()); + await drawFor(ISS_TELEMETRY_POLL_MS); + assert.equal(feed.pose(), null, 'no signal'); + await drawFor(ISS_TELEMETRY_POLL_MS); + assert.ok(feed.pose(), 'signal back'); + // Requests now fail: the last pose is used until it is 20 s old, and the + // feed asks less often. + const failingFrom = calls.length; + await drawFor(ISS_TELEMETRY_FRESH_MS - ISS_TELEMETRY_POLL_MS - 1000); + assert.ok(feed.pose()); + await drawFor(ISS_TELEMETRY_POLL_MS + 2000); + assert.equal(feed.pose(), null, 'too old'); + await drawFor(60_000); + assert.ok(calls.length - failingFrom <= 4, 'failures are retried slowly'); +}); + +test('destroy stops the feed, even with a request in flight', async () => { + const time = fakeTime(); + let release; + const calls = []; + const fetchImpl = (url) => { + calls.push(url); + return new Promise((resolve) => { + release = () => resolve({ ok: true, json: async () => LIVE }); + }); + }; + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + feed.touch(); + await time.advance(0); + assert.equal(calls.length, 1); + feed.destroy(); + release(); + await time.advance(60_000); + assert.equal(feed.pose(), null); + assert.equal(calls.length, 1); +}); + +/** + * A stand-in for the loaded model: named nodes that keep a copy of the + * matrix written to them, as a Cesium node does. + */ +function fakeModel() { + const nodes = new Map(); + return { + ready: true, + getNode(name) { + if (!nodes.has(name)) { + let copy = null; + nodes.set(name, { + name, + get matrix() { + return copy; + }, + set matrix(value) { + copy = Array.from(value); + }, + }); + } + return nodes.get(name); + }, + matrixOf(name) { + return nodes.get(name)?.matrix ?? null; + }, + }; +} + +const AXES = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; +const POSITION = { x: 6_800_000, y: 0, z: 0 }; + +test('with a telemetry pose the joints take its angles, each side its own', () => { + const articulation = createIssArticulation(); + const model = fakeModel(); + const pose = issTelemetryPose(RECORDED[0].items); + articulation.setTelemetry(() => pose); + articulation.update( + model, + new Date(Date.UTC(2026, 10, 13, 11, 8)), + POSITION, + AXES, + 1000, + ); + assert.equal(articulation.isLive(), true); + + // The alpha joints turn about X by the pose's angle: port and starboard differ. + ISS_ALPHA_JOINTS.forEach(({ node }, i) => { + const m = model.matrixOf(node); + assert.ok(Math.abs(m[5] - Math.cos(pose.alpha[i])) < 1e-9, node); + assert.ok(Math.abs(m[6] - Math.sin(pose.alpha[i])) < 1e-9, node); + }); + assert.notDeepEqual( + model.matrixOf(ISS_ALPHA_JOINTS[0].node), + model.matrixOf(ISS_ALPHA_JOINTS[1].node), + ); + ISS_BETA_JOINTS.forEach(({ node }, i) => { + const m = model.matrixOf(node); + assert.ok(Math.abs(m[0] - Math.cos(pose.beta[i])) < 1e-9, node); + assert.ok(Math.abs(m[1] - Math.sin(pose.beta[i])) < 1e-9, node); + }); + ISS_RADIATOR_JOINTS.forEach(({ node }, i) => { + const m = model.matrixOf(node); + assert.ok(Math.abs(m[0] - Math.cos(pose.gamma[i])) < 1e-9, node); + }); + // The first dish takes the reported aim (its rest boresight, +Y, turned + // onto it); the second is left where it was. + const dish = model.matrixOf(ISS_DISH_JOINTS[0].node); + assert.ok(angleDeg([dish[4], dish[5], dish[6]], pose.dish) < 1e-4); + const second = model.matrixOf(ISS_DISH_JOINTS[1].node); + assert.ok(angleDeg([second[4], second[5], second[6]], [0, 1, 0]) < 1e-4); +}); + +test('without a pose, or in Manual, the joints keep their computed rules', () => { + const date = new Date(Date.UTC(2026, 10, 13, 11, 8)); + const computed = fakeModel(); + createIssArticulation().update(computed, date, POSITION, AXES, 1000); + + // Telemetry with nothing to say. + const silent = createIssArticulation(); + silent.setTelemetry(() => null); + const silentModel = fakeModel(); + silent.update(silentModel, date, POSITION, AXES, 1000); + assert.equal(silent.isLive(), false); + + // Telemetry with a pose, but the command panel is on Manual. + const manual = createIssArticulation(); + manual.setTelemetry(() => issTelemetryPose(RECORDED[0].items)); + manual.setTelemetryAllowed(false); + const manualModel = fakeModel(); + manual.update(manualModel, date, POSITION, AXES, 1000); + assert.equal(manual.isLive(), false); + + // A Sun chosen by hand is computed too. + const forced = createIssArticulation(); + forced.setTelemetry(() => issTelemetryPose(RECORDED[0].items)); + forced.setOverride(() => ({ sun: [0, 1, 0], sunlit: true })); + forced.update(fakeModel(), date, POSITION, AXES, 1000); + assert.equal(forced.isLive(), false); + + for (const { node } of [ + ...ISS_ALPHA_JOINTS, + ...ISS_BETA_JOINTS, + ...ISS_RADIATOR_JOINTS, + ]) { + assert.deepEqual(silentModel.matrixOf(node), computed.matrixOf(node), node); + assert.deepEqual(manualModel.matrixOf(node), computed.matrixOf(node), node); + } + + // Back to Automatic: the pose is used again, gliding at the joint rate. + manual.setTelemetryAllowed(true); + manual.update(manualModel, date, POSITION, AXES, 1100); + assert.equal(manual.isLive(), true); +}); + +test('a page that opens during a loss of signal learns when the feed last had data', async () => { + const time = fakeTime(); + // The recording carries no times; date every item the same. + const dated = Object.fromEntries( + Object.entries(RECORDED[0].items).map(([key, [value]]) => [ + key, + [value, 1_700_000_000_000], + ]), + ); + const noSignal = { + configured: true, + status: 'no-signal', + items: dated, + }; + const { fetchImpl } = fakeFetch([noSignal, noSignal]); + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + feed.touch(); + await time.advance(1000); + const status = feed.status(); + assert.equal(status.state, 'no-signal'); + assert.equal(status.poseAgeMs, null); + const latest = issTelemetryLatestEpoch(dated); + assert.ok(Number.isFinite(latest) && latest > 0); + assert.equal(status.liveUntilMs, latest); + feed.destroy(); +}); + +test('the latest epoch is the newest dated item, and nothing without one', () => { + assert.equal( + issTelemetryLatestEpoch({ a: [1, 100], b: [2, 300], c: [3, 200] }), + 300, + ); + assert.equal(issTelemetryLatestEpoch({ a: [1, 'x'], b: 5, c: [2, 0] }), null); + assert.equal(issTelemetryLatestEpoch({}), null); + assert.equal(issTelemetryLatestEpoch(null), null); +}); + +test('the status says where the angles stand: pending, live, disabled', async () => { + const time = fakeTime(); + const { fetchImpl } = fakeFetch([LIVE]); + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + assert.equal(feed.status().state, 'pending', 'before the first answer'); + feed.touch(); + await time.advance(0); + const live = feed.status(); + assert.equal(live.state, 'live'); + assert.ok(live.poseAgeMs >= 0 && live.poseAgeMs < ISS_TELEMETRY_FRESH_MS); + + const off = fakeFetch([{ configured: false }]); + const offFeed = createIssTelemetryFeed({ fetchImpl: off.fetchImpl, ...time }); + offFeed.touch(); + await time.advance(0); + assert.equal(offFeed.status().state, 'disabled'); +}); + +test('a relay route that is not there reads as unavailable, not as connecting forever', async () => { + const time = fakeTime(); + // A 404, or a deploy's HTML fallback page: never a relay answer. + const answers = [ + { ok: false, status: 404, json: async () => ({}) }, + { + ok: true, + json: async () => { + throw new SyntaxError('Unexpected token <'); + }, + }, + ]; + let call = 0; + const fetchImpl = async () => answers[Math.min(call++, answers.length - 1)]; + const feed = createIssTelemetryFeed({ fetchImpl, ...time }); + feed.touch(); + await time.advance(0); + assert.equal(feed.configured(), null, 'never answered'); + assert.equal(feed.status().state, 'unavailable'); + for (let i = 0; i < 30; i++) { + feed.touch(); + await time.advance(1000); + } + assert.equal(feed.status().state, 'unavailable'); +}); diff --git a/src/layers/satellites/lifecycle.js b/src/layers/satellites/lifecycle.js index 832bf06e17..553e59ee40 100644 --- a/src/layers/satellites/lifecycle.js +++ b/src/layers/satellites/lifecycle.js @@ -47,6 +47,8 @@ export function createLifecycle({ const frame = frameOf(viewer); parts.catalog._abortActiveUpdates(); clearFocusTarget('satellites'); + for (const model of parts.stationModels ?? []) + model._destroyStationModel(); layerState._viewer = viewer; layerState._catalog = new Map(); layerState._points = new Map(); @@ -138,7 +140,10 @@ export function createLifecycle({ releaseContinuousRender('satellites'); parts.rendering._setPointsShown(false); parts.rendering._setOrbitPathsShown(false); + for (const model of parts.stationModels ?? []) + model._updateStationModel(); // off: releases the model parts.tracking._clearTracking(); + parts.stationPanel?._syncStationPanel(); // off: takes the panel down parts.labels._syncIssOverlay(); // Remove click handler + keydown listener + preRender propagation while disabled layerState._clickSubscription?.(); @@ -178,6 +183,9 @@ export function createLifecycle({ } layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID); layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false); + for (const model of parts.stationModels ?? []) + model._destroyStationModel(); + parts.stationPanel?._destroyStationPanel(); // The dots', tracked dot's and rings' sets are disposed of parts.rendering._detach(viewer); layerState._points.clear(); diff --git a/src/layers/satellites/offCesium.test.mjs b/src/layers/satellites/offCesium.test.mjs index e13d0af971..f1c538470d 100644 --- a/src/layers/satellites/offCesium.test.mjs +++ b/src/layers/satellites/offCesium.test.mjs @@ -321,6 +321,98 @@ test('the rendering part draws the dots, the tracked dot and the rings through t } }); +test('a dot handed to a station model draws only beyond its range; the tracked dot too', () => { + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + try { + const state = { + now: Date.now, + _points: new Map(), + _orbitPaths: new Map(), + _catalog: new Map(), + _viewer: viewer, + _trackedNorad: null, + _enabled: true, + _params: { showPoints: false, showOrbits: false }, + }; + const rendering = createRendering({ + state, + services: { + focus: { + focusNowMs: (ms) => ms, + getFocusTarget: () => null, + focusPassIsNeeded: () => false, + }, + }, + parts: { tracking: { _getTrackedFramePosition: () => null } }, + }); + rendering._attach(viewer); + const points = draw.find('satellites:').spec.id; + const set = draw.set(points); + const range = [1.5e6, Number.MAX_VALUE]; + let frame = 0; + const tick = () => rendering._preRenderTick({ frame: ++frame }); + rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss); + tick(); + assert.equal(set.items.get('25544').displayRange, undefined); + assert.equal(rendering._pointDisplayRange(25544), null); + // The range goes to the set with the frame, as the item's own copy. + assert.equal(rendering._setPointDisplayRange(25544, range), true); + assert.equal(rendering._setPointDisplayRange(1, range), false, 'no dot'); + let writes = set.writes; + tick(); + assert.equal(set.writes, writes + 1, 'sent with the frame'); + assert.deepEqual(set.items.get('25544').displayRange, range); + assert.notEqual(set.items.get('25544').displayRange, range); + assert.deepEqual(rendering._pointDisplayRange(25544), range); + assert.equal(set.items.get('25544').show, true, 'shown, within its range'); + // The same range again sends nothing (asked every frame). + writes = set.writes; + rendering._setPointDisplayRange(25544, [1.5e6, Number.MAX_VALUE]); + tick(); + assert.equal(set.writes, writes); + // None again: every distance. + rendering._setPointDisplayRange(25544, null); + tick(); + assert.equal(set.items.get('25544').displayRange, undefined); + assert.equal(rendering._pointDisplayRange(25544), null); + // A dot added again (a catalog rebuild) arrives with no range. + rendering._setPointDisplayRange(25544, range); + rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss); + tick(); + assert.equal(set.items.get('25544').displayRange, undefined); + + // The tracked dot: redrawn at once while drawn, fresh for each tracking. + const tracked = draw.set(points.replace(':points', ':tracked')); + state._trackedNorad = 25544; + assert.equal(rendering._trackedDotDisplayRange(), null, 'no tracked dot'); + rendering._setTrackedDotDisplayRange(range); // nothing to put it on + rendering._addTrackedEntity({ position: () => ({ x: 1, y: 2, z: 3 }) }); + assert.equal(rendering._trackedDotDisplayRange(), null); + tick(); + assert.equal(tracked.items.get('25544').displayRange, undefined); + writes = tracked.writes; + rendering._setTrackedDotDisplayRange(range); + assert.equal(tracked.writes, writes + 1, 'redrawn at once'); + assert.deepEqual(tracked.items.get('25544').displayRange, range); + assert.deepEqual(rendering._trackedDotDisplayRange(), range); + rendering._setTrackedDotDisplayRange([1.5e6, Number.MAX_VALUE]); + assert.equal(tracked.writes, writes + 1, 'the same range sends nothing'); + rendering._setTrackedDotDisplayRange(null); + assert.equal(tracked.items.get('25544').displayRange, undefined); + assert.equal(rendering._trackedDotDisplayRange(), null); + rendering._setTrackedDotDisplayRange(range); + rendering._removeTrackedEntity(); + assert.equal(rendering._trackedDotDisplayRange(), null); + rendering._addTrackedEntity({ position: () => ({ x: 1, y: 2, z: 3 }) }); + tick(); + assert.equal(tracked.items.get('25544').displayRange, undefined); + rendering._detach(viewer); + } finally { + unbind(); + } +}); + test('the orbit frame matrix turns ECEF about Z by minus the GMST elapsed', () => { const rendering = createRendering({ state: {}, diff --git a/src/layers/satellites/policy.js b/src/layers/satellites/policy.js index 43d5409436..41b6c0c138 100644 --- a/src/layers/satellites/policy.js +++ b/src/layers/satellites/policy.js @@ -19,6 +19,156 @@ import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js'; export const ISS_NORAD = 25544; +/** + * Tiangong's catalog entry: CelesTrak lists the core module as "CSS (TIANHE)" + * and the labs as "CSS (WENTIAN)" and "CSS (MENGTIAN)" under entries of their + * own, with the docked Shenzhou and Tianzhou ships beside them. + */ +export const TIANGONG_NORAD = 48274; + +/** + * Whether the tracked satellite is a station: the station's own entry, or an + * object docked to it (a module, a cargo ship…), which is the same body under + * a catalog entry of its own. A click on the station's dot lands on any of + * them. + * @param {number} stationNorad The station's entry (ISS_NORAD, TIANGONG_NORAD). + * @param {number|null|undefined} trackedNorad + * @param {{has(noradId: number): boolean}|null|undefined} dockedCompanions + * What shares the tracked satellite's position (`_dockedCompanions`). + * @returns {boolean} + */ +export function stationTrackedOn(stationNorad, trackedNorad, dockedCompanions) { + if (trackedNorad === stationNorad) return true; + return ( + trackedNorad !== null && + trackedNorad !== undefined && + Boolean(dockedCompanions?.has(stationNorad)) + ); +} + +/** `stationTrackedOn` for the ISS. */ +export function issTrackedOnStation(trackedNorad, dockedCompanions) { + return stationTrackedOn(ISS_NORAD, trackedNorad, dockedCompanions); +} + +/** + * The ISS drawn as a 3D model up close (issModel.js): NASA's "International + * Space Station (ISS) (D) (IGOAL)" from NASA 3D Resources, the station's + * current configuration (Nauka, Prichal, Bishop, the roll-out solar arrays), + * with NASA's own textures. The shipped file is that model reduced for the + * web and put in one frame, in meters (public/models/README.md says how). + */ +export const ISS_MODEL_URL = '/models/iss.glb'; + +/** The real station across its main truss, end to end, in meters. */ +export const ISS_SPAN_M = 109; + +/** + * The asset's span along its truss (glTF X, solar array to solar array) in + * its own units, read from the file's accessors. The file is in meters. + */ +export const ISS_MODEL_NATIVE_SPAN = 109; + +/** + * The station's bounding-box centre in the file's coordinates, whose origin is + * NASA's (the middle of the S0 truss). The scene root is translated by minus + * this, so the model's origin is the station's centre. That is what + * minimumPixelSize scales about, so the enlarged far-range model stays + * centred on the orbital position (and on the tracked card's leader). + */ +export const ISS_MODEL_CENTER_NATIVE = Object.freeze([0, -7.38, 0.001]); + +/** + * Which flight axis each of the model's local axes (Cesium's, after its glTF + * axis correction: local X = glTF Z, Y = glTF X, Z = glTF Y) points along. + * The file has the U.S. segment at +Z (forward), Kibo at +X (port) and the Z1 + * truss at +Y (zenith; the Cupola faces -Y), so: local X → along-track, local + * Y → orbit normal, local Z → zenith. + */ +export const ISS_MODEL_LOCAL_AXES = Object.freeze(['x', 'y', 'z']); + +/** + * Within this camera distance the model replaces the dot; farther out the dot + * stays. Covers the tracked view (~726 km back for LEO) with room to spare. + */ +export const ISS_MODEL_MAX_DISTANCE_M = 1_500_000; + +/** + * The model is never drawn smaller than this, in pixels. At true size the + * station is under a pixel from the tracked view, so the floor is what makes + * it readable there; within a few kilometres the true size takes over. + */ +export const ISS_MODEL_MIN_PX = 72; + +/** + * Objects within this distance of the ISS are docked to it (their element + * sets put them within a few hundred meters); while the model shows, their + * dots give way to it inside its range (issModel.js). + */ +export const ISS_COMPANION_RADIUS_M = 5_000; + +/** + * Dots are moved at different moments, so with the clock sped up a docked + * object's dot can trail the ISS's by a long way. Only objects whose dots are + * within this distance are checked orbit against orbit (issModel.js). + */ +export const ISS_COMPANION_COARSE_M = 3_000_000; + +/** How often the docked set is rescanned, ms. */ +export const ISS_COMPANION_SCAN_MS = 1_000; + +/** + * Within this camera distance of the ISS its orbit ring is hidden. The ring is + * drawn as ~230 km chords and turned with the Earth once a second, so up close + * it runs metres to kilometres off the model and jumps; at the tracked view + * (~726 km) and beyond it stays. + */ +export const ISS_ORBIT_HIDE_M = 50_000; + +/** + * The tracked card keeps clear of the model: its gap from the anchor is this + * many meters of the station as drawn on screen (about its reach from its + * centre in an oblique view), so up close the card sits beside the station, not on it. + */ +export const ISS_CARD_CLEAR_M = 40; + +/** + * Tiangong drawn as a 3D model up close (tiangongModel.js): the project's own + * model of the station's T configuration (Tianhe, Wentian, Mengtian, with a + * Shenzhou forward and nadir and a Tianzhou aft), built from primitives with + * procedural textures, in meters, same frame as the ISS file (glTF +X port, + * +Y zenith, +Z forward), the scene root at the station's bounding-box + * centre (public/models/README.md). + */ +export const TIANGONG_MODEL_URL = '/models/tiangong.glb'; + +/** + * The tracked card's clearance from Tiangong (ISS_CARD_CLEAR_M for the ISS): + * the station reaches ~29 m from its centre along the lab wings. + */ +export const TIANGONG_CARD_CLEAR_M = 30; + +/** + * The stations the layer treats as one body with their docked entries + * (stationModels.js): `key` is the STATION description's and the LIVE + * section's (`station:`); objects within `companionRadiusM` of the + * station, orbit against orbit, are docked to it. Each is also drawn as a 3D + * model up close (issModel.js, tiangongModel.js), but these rules hold + * whether or not a model part exists. + */ +export const STATIONS = Object.freeze([ + Object.freeze({ + key: 'iss', + norad: ISS_NORAD, + companionRadiusM: ISS_COMPANION_RADIUS_M, + }), + Object.freeze({ + key: 'tiangong', + norad: TIANGONG_NORAD, + companionRadiusM: ISS_COMPANION_RADIUS_M, + }), +]); + export const ISS_OVERLAY_SOURCE_ID = 'satellites-iss'; export const ISS_OVERLAY_SOURCE_OPTIONS = Object.freeze({ diff --git a/src/layers/satellites/rendering.js b/src/layers/satellites/rendering.js index 9704dac7cf..a382b78e49 100644 --- a/src/layers/satellites/rendering.js +++ b/src/layers/satellites/rendering.js @@ -54,6 +54,13 @@ const RING_BEHIND_ALPHA = 0.35; /** An RGBA colour with another alpha. */ const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha]; +/** Whether two display ranges are the same: both none, or the same bounds. */ +const sameRange = (a, b) => + a && b ? a[0] === b[0] && a[1] === b[1] : !a && !b; + +/** A display range as the item's own copy, or undefined for none. */ +const rangeOf = (range) => (range ? [range[0], range[1]] : undefined); + /** Layer instances so far: set ids unique to each. */ let instances = 0; @@ -206,7 +213,7 @@ export function createRendering({ function _setOrbitPathShown(noradId, show) { const path = layerState._orbitPaths.get(noradId); - if (!path) return; + if (!path || path.item.show === show) return; path.item.show = show; sets?.rings.upsert([path.item]); } @@ -258,6 +265,46 @@ export function createRendering({ if (trackedDot.drawn) sets?.tracked.upsert([trackedDot.item]); } + /** + * Draw one satellite's dot only at eye distances in `range` (`[near, far)`, + * metres), or at every distance for null, apart from whether it is shown: + * a station's model stands in for its dot, and for the dots of the objects + * docked to it, within the model's range (stationModel.js). A dot added + * again (a catalog rebuild) arrives with no range. + * @param {number} noradId + * @param {readonly [number, number]|null} range + * @returns {boolean} Whether the satellite has a dot. + */ + function _setPointDisplayRange(noradId, range) { + const point = layerState._points.get(noradId); + if (!point) return false; + if (sameRange(point.displayRange, range)) return true; + point.displayRange = rangeOf(range); + _markDirty(noradId); + return true; + } + + /** The eye distances a dot is drawn at, or null for every distance. */ + function _pointDisplayRange(noradId) { + return layerState._points.get(noradId)?.displayRange ?? null; + } + + /** + * The tracked satellite's dot likewise; a dot drawn is redrawn at once. A + * new tracked dot (tracking another satellite) arrives with no range. + * @param {readonly [number, number]|null} range + */ + function _setTrackedDotDisplayRange(range) { + if (!trackedDot || sameRange(trackedDot.item.displayRange, range)) return; + trackedDot.item.displayRange = rangeOf(range); + if (trackedDot.drawn) sets?.tracked.upsert([trackedDot.item]); + } + + /** The eye distances the tracked dot is drawn at, or null for every distance. */ + function _trackedDotDisplayRange() { + return trackedDot?.item.displayRange ?? null; + } + /** Remove every orbit ring. */ function _clearOrbitPaths() { const ids = [...layerState._orbitPaths.values()].map( @@ -666,6 +713,11 @@ export function createRendering({ function _tickAfterFrame() { const now = focusNowMs(Date.now()); + // The stations as 3D models up close. First, before the tracked sample + // below is refreshed: the follow camera and the tracked dot were placed + // this frame from the sample still cached, and a model must sit on it too. + for (const model of parts.stationModels ?? []) model._updateStationModel(); + const interval = layerState._trackedNorad ? 200 : POSITION_UPDATE_MS; // Space Missions keeps this layer enabled for TLE lookup while deliberately // hiding its standalone fleet. Do not rebuild hidden point buffers on the @@ -700,6 +752,9 @@ export function createRendering({ if (layerState._cockpitSubjectNorad !== null) parts.cockpit?._syncCockpitSubjectVisuals(); + // NASA's live video beside the card while the ISS is selected. + parts.stationPanel?._syncStationPanel(); + _updatePointFocus(now); // Hidden standalone orbit rings do not need turning while Space Missions @@ -861,6 +916,10 @@ export function createRendering({ _setPointStyle, _pointShown, _setTrackedDotShown, + _setPointDisplayRange, + _pointDisplayRange, + _setTrackedDotDisplayRange, + _trackedDotDisplayRange, _clearOrbitPaths, _addPoint, _movePoint, diff --git a/src/layers/satellites/state.js b/src/layers/satellites/state.js index 7894acafad..8ecb8911a0 100644 --- a/src/layers/satellites/state.js +++ b/src/layers/satellites/state.js @@ -80,6 +80,13 @@ export function createState({ services }) { // Click-to-track state state._trackedNorad = null; + /** + * The station the tracked satellite is docked to, by both orbits compared + * when tracking began (tracking.js): its NORAD number, or null. + */ + state._trackedDockedToStation = null; + /** Whether that station is the ISS, whose ring stands for the entry's. */ + state._trackedDockedToIss = false; state._pendingTrackingRestore = null; diff --git a/src/layers/satellites/stationModel.js b/src/layers/satellites/stationModel.js new file mode 100644 index 0000000000..f02a4fa38f --- /dev/null +++ b/src/layers/satellites/stationModel.js @@ -0,0 +1,850 @@ +import { eciToGeodetic, gstime, propagate } from 'satellite.js'; +import { fromRadians } from '../../geo/ellipsoid.js'; +import { headingPitchRollOfAxes } from '../../geo/frames.js'; +import { copyInto, distance, vec } from '../../geo/vector.js'; +import { canvasOf, drawOf, findCamera } from '../../render/rendererOf.js'; +import { stationTrackedOn } from './policy.js'; + +/** + * A space station as a 3D model when the camera is close, driven by a + * description of the station (`StationModelSpec`): the ISS (issModel.js) and + * Tiangong (tiangongModel.js) are two instances of this one factory. Far out + * the dot stays: the model and the dot (ambient and tracked) split the + * distance range, so exactly one of them draws (the model by the display + * range on its draw item, the dots by the display range the rendering part + * puts on theirs). The model is one item of a `models` set on the + * renderer's draw port, asked for on first need and only if the station is + * shown, and posed every frame from its own SGP4 sample (the dot moves once + * a second, which at model range would show as a jump). + * + * The moving parts (the joint driver, `createArticulation`) write node + * matrices into this part's node poses, as they would into a model's nodes; + * those poses are the draw item's `nodes`, which the renderer applies to the + * model's named glTF nodes. + * + * @typedef {object} StationModelSpec + * @property {string} key Short id ('iss', 'tiangong'): the STATION + * description's key and the LIVE section's `station:` subject key. + * @property {string} label The station's name, for log lines. + * @property {number} norad The catalog entry the model stands at. + * @property {string} modelUrl Asset path, resolved with `resolveAsset`. + * @property {number} scale The file's units to meters. + * @property {number} minPx The model is never drawn smaller than this. + * @property {number} maxDistanceM Within this camera distance the model + * replaces the dot. + * @property {number} orbitHideM Within this camera distance the station's + * orbit ring is hidden. + * @property {number} cardClearM How many meters of the station the tracked + * card keeps clear of. + * @property {number} companionRadiusM Objects within this of the station, + * orbit against orbit, are docked to it. + * @property {number} companionCoarseM Only dots within this are checked. + * @property {number} companionScanMs How often the docked set is rescanned. + * @property {readonly string[]} localAxes Which flight axis each of the + * model's local axes points along (see ISS_MODEL_LOCAL_AXES). + * @property {(noradId: number, entry: object|undefined) => boolean} isModule + * Whether a catalog entry at the station is one of its own modules (the + * ISS's Nauka, Tiangong's labs) rather than a visiting vehicle. + * @property {() => object} createArticulation The joint driver + * (`update(nodes, date, position, axes)`, `reset()`, and what the STATION + * section calls). `nodes` has a model's `ready` and `getNode(name)`, each + * node taking a `matrix`. + * @property {(() => {pose: () => object|null, touch: () => void, + * status: () => object, destroy: () => void})|null} createTelemetry A + * telemetry feed for the joints, or null for computed angles only. + * @property {((input: {key: string|null, centre: {x: number, y: number, z: number}, + * axes: {x: number[], y: number[], z: number[]}, + * name: (noradId: number|null) => string|null, + * entry: (noradId: number|null) => number|null, + * dockedVehicle: number|null}) => object|null)|null} cockpitMount The + * Cockpit camera's views on the model, or null when the station has none. + * @property {boolean} hideInCockpit Hide the model while the Cockpit rides + * the station: true where its camera would sit inside the hull, false + * where it rides a mount on the model. + * @property {(() => void)|null} syncOrbit Puts the station's ring back to + * its own rules on leaving the close-up; null for the layer's orbit toggle + * (a ring that exists only while the station is tracked). + * @property {number} [unloadAfterMs] How long the model may go undrawn (out + * of range, or hidden) before its draw set is released and its GPU memory + * with it; asked for again on the next approach. Default one minute. + * @property {number} [retryAfterMs] How long after a failed load the model + * is released and asked for again. Default 30 s. + */ + +/** Default `unloadAfterMs`: a minute undrawn releases the model. */ +export const STATION_MODEL_UNLOAD_AFTER_MS = 60_000; +/** + * A model that failed to load is released after this and asked for again + * on the next frame in range (the renderer retries a load only on an + * update, and a model that is not ready is not sent). + */ +export const STATION_MODEL_RETRY_AFTER_MS = 30_000; + +/** + * Whether a station model may be drawn: the dot's own rules (layer on, points + * on, the station loaded and its class shown or the station tracked), and + * not while the Cockpit hides it. + * @param {{enabled: boolean, showPoints: boolean, hasStation: boolean, + * classVisible: boolean, tracked: boolean, cockpitHidden: boolean}} input + * @returns {boolean} + */ +export function stationModelShouldShow({ + enabled, + showPoints, + hasStation, + classVisible, + tracked, + cockpitHidden, +}) { + return ( + Boolean(enabled) && + Boolean(showPoints) && + Boolean(hasStation) && + (Boolean(classVisible) || Boolean(tracked)) && + !cockpitHidden + ); +} + +/** + * A station's flight axes in the Earth-fixed frame, from one SGP4 state: a + * station normally flies "+XVV", its modules along the velocity, the truss or + * labs across the orbit plane, the same side always to the Earth. Returned + * as the model's local axes: x along-track, y the orbit normal, z zenith + * (away from the Earth's centre). + * @param {{x:number,y:number,z:number}} positionEcef Earth-fixed position. + * @param {{x:number,y:number,z:number}} velocityEcefAxes Inertial velocity, + * turned onto the Earth-fixed axes (direction only matters). + * @returns {{x:number[], y:number[], z:number[]}|null} Unit vectors, or null + * for a degenerate state (zero position or velocity along it). + */ +export function stationFlightAxes(positionEcef, velocityEcefAxes) { + const r = [positionEcef.x, positionEcef.y, positionEcef.z]; + const v = [velocityEcefAxes.x, velocityEcefAxes.y, velocityEcefAxes.z]; + const z = unit(r); + const y = unit(cross(r, v)); + if (!z || !y) return null; + const x = cross(y, z); + return { x, y, z }; +} + +/** + * Turn an inertial (TEME) vector onto the Earth-fixed axes at `gmst`: the same + * rotation `eciToGeodetic` applies to the position. + * @param {{x:number,y:number,z:number}} v + * @param {number} gmst Radians. + * @returns {{x:number,y:number,z:number}} + */ +export function temeToEcefAxes(v, gmst) { + const c = Math.cos(gmst); + const s = Math.sin(gmst); + return { x: c * v.x + s * v.y, y: -s * v.x + c * v.y, z: v.z }; +} + +/** + * The model's orientation for the renderer, `{heading, pitch, roll}` at + * `position`, from the station's flight axes and which of them each model + * axis points along (`localAxes`). + * @param {{x:number,y:number,z:number}} position Earth-fixed. + * @param {{x:number[], y:number[], z:number[]}} axes Flight axes. + * @param {readonly string[]} localAxes + * @returns {{heading: number, pitch: number, roll: number}} + */ +export function stationModelOrientation(position, axes, localAxes) { + const as = (key) => vec(axes[key][0], axes[key][1], axes[key][2]); + return headingPitchRollOfAxes(position, { + x: as(localAxes[0]), + y: as(localAxes[1]), + z: as(localAxes[2]), + }); +} + +/** + * Node poses as a joint driver writes them: `getNode(name)` hands a node + * whose `matrix` it sets (a column-major 4×4, copied on write, as a model's + * node copies), and `poses` keeps every matrix written, by node name: the + * draw item's `nodes` (`ModelItem.nodes`), one object for the item's life. + * @returns {{ready: boolean, getNode: (name: string) => {matrix: Float64Array}, + * poses: Record, clear: () => void}} + */ +export function createNodePoses() { + /** @type {Record} */ + const poses = {}; + const nodes = new Map(); + return { + ready: true, + poses, + getNode(name) { + let node = nodes.get(name); + if (!node) { + node = { + get matrix() { + return poses[name]; + }, + set matrix(value) { + // None: the node goes back to its authored pose (its name leaves + // the map), as a model's node does. + if (value === undefined || value === null) { + delete poses[name]; + return; + } + const kept = (poses[name] ??= new Float64Array(16)); + for (let i = 0; i < 16; i++) kept[i] = value[i]; + }, + }; + nodes.set(name, node); + } + return node; + }, + /** Every node back to its authored pose (its name leaves the map). */ + clear() { + for (const name of Object.keys(poses)) delete poses[name]; + }, + }; +} + +function cross(a, b) { + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ]; +} + +function unit(a) { + const n = Math.hypot(a[0], a[1], a[2]); + if (!(n > 0)) return null; + return [a[0] / n, a[1] / n, a[2] / n]; +} + +/** + * One station's model part. + * @param {StationModelSpec} spec + * @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context + */ +export function createStationModel( + spec, + { state: layerState, parts, resolveAsset }, +) { + const { norad } = spec; + /** The `models` draw set the station is an item of, once asked for. */ + let set = null; + let offReady = null; + let offFailed = null; + /** The station's draw item, sent again each frame it is posed. */ + const itemId = `station:${spec.key}`; + let item = null; + /** Whether the renderer has the model loaded and posed. */ + let ready = false; + let loading = false; + let failed = false; + /** When the renderer said the load failed (wall-clock ms), or null. */ + let failedAt = null; + /** Turns the moving parts by where the Sun (and the relays) are. */ + const articulation = spec.createArticulation(); + /** Where the joint driver writes; kept for a renderer that poses nodes. */ + const nodePoses = createNodePoses(); + /** + * Telemetry for the same joints, where the station has any: asked for only + * while the model is drawn, and used in place of the computed angles + * whenever it has a pose. + */ + const telemetry = spec.createTelemetry?.() ?? null; + if (telemetry) articulation.setTelemetry?.(() => telemetry.pose()); + /** The eye distances the model draws at. */ + const nearRange = Object.freeze([0, spec.maxDistanceM]); + /** The eye distances the dots the model stands in for are drawn at. */ + const farRange = Object.freeze([spec.maxDistanceM, Number.MAX_VALUE]); + /** Whether the station's own dot is left to the model within its range. */ + let dotHanded = false; + /** Whether the tracked dot is, the tracked satellite being the station. */ + let trackedDotHanded = false; + /** + * @type {Set} Objects docked to the station, orbit against orbit, + * at the last scan: the same body as the model whether or not it draws. + */ + const dockedByOrbit = new Set(); + /** @type {Set} Docked objects whose dots the model stands in for. */ + const handedCompanions = new Set(); + /** Whether the model draws and the docked dots are left to it. */ + let handingOver = false; + /** Wall-clock ms since when the model has not been drawn, or null. */ + let undrawnSince = null; + let lastCompanionScanMs = Number.NEGATIVE_INFINITY; + /** Whether the station's orbit ring is hidden for the close-up. */ + let orbitHidden = false; + /** The tracked docked object whose ring is hidden for the close-up, or null. */ + let companionRingHidden = null; + const scratchPosition = vec(); + const scratchMountCentre = vec(); + /** The station centre the model last rendered at (for the tracked card). */ + const visualPosition = vec(); + let visualValid = false; + + function _shouldShow() { + const tracked = layerState._trackedNorad === norad; + return stationModelShouldShow({ + enabled: layerState._enabled, + showPoints: layerState._params.showPoints, + hasStation: layerState._catalog.has(norad), + classVisible: parts.controls._classVisible(norad), + tracked, + // With no mounts on the model the Cockpit camera would sit inside the + // hull, so the model goes while the Cockpit rides the station. + cockpitHidden: + spec.hideInCockpit && + Boolean(parts.cockpit?._cockpitHeld?.()) && + _trackedOnStation(), + }); + } + + /** The eye, from the camera port, or null without one. */ + function _eye() { + return findCamera(layerState._viewer)?.pose?.()?.position ?? null; + } + + /** + * Ask the renderer for the model: a `models` set of its own with the + * station as its one item, hidden until posed. On a renderer that draws + * no models the dot keeps drawing at every distance. + * @param {{x:number,y:number,z:number}} at Where the station is now. + */ + function _load(at) { + const draw = drawOf(layerState._viewer); + if (typeof draw?.models !== 'function') { + failed = true; + return; + } + loading = true; + set = draw.models({ id: `satellites:${itemId}`, show: true }); + offReady = set.on('ready', (id) => { + if (id !== itemId) return; + ready = true; + loading = false; + failed = false; + }); + offFailed = set.on('loadFailed', (id, message) => { + if (id !== itemId) return; + // The dots keep drawing at every distance (the model is never ready); + // after `retryAfterMs` the model is released and asked for again. + failed = true; + failedAt = Date.now(); + loading = false; + console.warn( + `[Data:Satellites] ${spec.label} model failed to load:`, + message, + ); + }); + item = { + id: itemId, + pos: { x: at.x, y: at.y, z: at.z }, + url: resolveAsset(spec.modelUrl), + orientation: { heading: 0, pitch: 0, roll: 0 }, + scale: spec.scale, + minPixelSize: spec.minPx, + displayRange: nearRange, + // So a click on the model tracks the station, as a click on its dot does. + meta: { norad }, + // The joint driver's poses, applied to the model's named nodes. + nodes: nodePoses.poses, + show: false, + }; + set.upsert([item]); + } + + /** Send the item as it stands. */ + function _send() { + if (set && item) set.upsert([item]); + } + + /** Hide the model (nothing sent when it is hidden already). */ + function _hide() { + if (item && item.show) { + item.show = false; + _send(); + } + } + + /** An object's inertial position at `date`, km, or null. */ + function _temeKm(satrec, date) { + if (!satrec) return null; + try { + const position = propagate(satrec, date)?.position; + return position && typeof position !== 'boolean' ? position : null; + } catch { + return null; + } + } + + /** + * Whether the tracked satellite is the station itself: its own entry, or + * an object docked to it (a module, a cargo ship…), which has a catalog + * entry and a dot of its own but is the same body as the model. Read from + * the layer's docked set (dots sharing a position) and from this part's + * own scan (orbit against orbit), which stands whether or not the model + * draws: the answer must not depend on what it decides. + */ + function _trackedOnStation() { + const tracked = layerState._trackedNorad; + return ( + stationTrackedOn(norad, tracked, layerState._dockedCompanions) || + (tracked !== null && dockedByOrbit.has(tracked)) + ); + } + + /** + * Leave the near range to the model: the station's dot, and the tracked + * dot while the tracked satellite is the station, draw only beyond it. + * Asked every frame (the calls cost nothing when nothing changes): a + * catalog rebuild or a change of tracked satellite brings new dots that + * arrive with no range, and a tracked satellite that leaves the station + * (a vehicle undocking) gets its tracked dot back. + */ + function _handOverDots() { + dotHanded = parts.rendering._setPointDisplayRange(norad, farRange); + const trackedHere = _trackedOnStation(); + if (trackedHere) parts.rendering._setTrackedDotDisplayRange(farRange); + else if (trackedDotHanded) parts.rendering._setTrackedDotDisplayRange(null); + trackedDotHanded = trackedHere; + } + + /** Give the station's dot and the tracked dot back at every distance. */ + function _releaseDots() { + if (dotHanded) parts.rendering._setPointDisplayRange(norad, null); + dotHanded = false; + if (trackedDotHanded) parts.rendering._setTrackedDotDisplayRange(null); + trackedDotHanded = false; + } + + /** + * Objects docked to the station (a module, a crew or cargo ship) have dots + * of their own at the station's position. Near the model they are part of + * it, and their dots, moved only a few times a second, jump across the + * model at 7.6 km/s. While the model shows, their dots draw only beyond its + * range too. Rescanned once a second: a vehicle that undocks gets its dot + * back, and a catalog rebuild's new dots are picked up. + * @param {number} nowMs + * @param {boolean} handOver Whether the docked dots are left to the model + * (it draws); otherwise the scan only keeps the docked set current. + */ + function _scanCompanions(nowMs, handOver) { + if (nowMs - lastCompanionScanMs < spec.companionScanMs) return; + lastCompanionScanMs = nowMs; + const stationPosition = parts.rendering._pointPosition(norad); + // The dots are placed at different moments (far apart with the clock sped + // up), so their spacing only rules out what is nowhere near. Whether an + // object is docked is read from both orbits at one instant. + const date = new Date(layerState.now()); + const stationTeme = _temeKm(layerState._catalog.get(norad)?.satrec, date); + if (!stationPosition || !stationTeme) return; + for (const [noradId, point] of layerState._points) { + if (noradId === norad || !point?.pos) continue; + const entry = layerState._catalog.get(noradId); + if (entry?.group === 'dense') continue; + let docked = false; + if (distance(point.pos, stationPosition) <= spec.companionCoarseM) { + const teme = _temeKm(entry?.satrec, date); + docked = + Boolean(teme) && + Math.hypot( + teme.x - stationTeme.x, + teme.y - stationTeme.y, + teme.z - stationTeme.z, + ) * + 1000 <= + spec.companionRadiusM; + } + if (docked) dockedByOrbit.add(noradId); + else dockedByOrbit.delete(noradId); + if (docked && handOver) { + parts.rendering._setPointDisplayRange(noradId, farRange); // no-op when equal + handedCompanions.add(noradId); + } else if (handedCompanions.has(noradId)) { + parts.rendering._setPointDisplayRange(noradId, null); + handedCompanions.delete(noradId); + } + } + for (const noradId of dockedByOrbit) + if (!layerState._points.has(noradId)) dockedByOrbit.delete(noradId); + } + + /** Give docked objects their dots back at every distance. */ + function _releaseCompanions() { + for (const noradId of handedCompanions) + parts.rendering._setPointDisplayRange(noradId, null); + handedCompanions.clear(); + } + + /** The station's ring back to its own rules (see `syncOrbit`). */ + function _restoreOrbit() { + if (spec.syncOrbit) { + spec.syncOrbit(); + return; + } + parts.rendering._setOrbitPathShown( + norad, + parts.controls.satelliteVisualsVisible( + layerState._enabled, + layerState._params.showOrbits, + ), + ); + } + + /** + * Up close the orbit ring (polyline chords, turned once a second) runs off + * the model and jumps across it, so it is hidden there. + * @param {boolean} near Camera within `orbitHideM` of the station. + */ + function _syncOrbitCloseUp(near) { + if (near) { + // Kept hidden every frame: the ring may be built after this. + parts.rendering._setOrbitPathShown(norad, false); + orbitHidden = true; + } else if (orbitHidden) { + orbitHidden = false; + // Back to the ring's own rules, unless the Cockpit holds it hidden. + if (layerState._cockpitHiddenPath !== norad) _restoreOrbit(); + } + // A tracked docked object draws a ring of its own through the model. + const tracked = layerState._trackedNorad; + const companion = + near && tracked !== norad && _trackedOnStation() ? tracked : null; + if (companionRingHidden !== null && companionRingHidden !== companion) { + // A tracked satellite's ring shows; untracking has already hidden it. + if ( + tracked === companionRingHidden && + layerState._cockpitHiddenPath !== companionRingHidden + ) + parts.rendering._setOrbitPathShown(companionRingHidden, true); + companionRingHidden = null; + } + if (companion !== null) { + parts.rendering._setOrbitPathShown(companion, false); + companionRingHidden = companion; + } + } + + /** + * Where the station is this frame, and how it is turned: its centre and + * its flight axes. + * + * The follow camera and the Cockpit camera sit on the tracked satellite's + * per-frame sample. While the tracked satellite is the station (its own + * entry, or an object docked to it, which has a sample of its own) the + * model sits on that same sample, or it would be drawn a frame of orbital + * motion (over 100 m) away from where the camera looks. Otherwise it is + * placed from the station's own orbit now. + * @param {{x:number,y:number,z:number}} result Receives the centre. + * @returns {{date: Date, axes: {x:number[], y:number[], z:number[]}}|null} + * Null when the orbit cannot be propagated. + */ + function _stationFrame(result) { + const sat = layerState._catalog.get(norad); + if (!sat) return null; + const trackedSample = + _trackedOnStation() && Number.isFinite(layerState._trackedFrameGeo?.atMs) + ? layerState._trackedFrameGeo + : null; + const date = new Date( + trackedSample ? trackedSample.atMs : layerState.now(), + ); + let posVel; + try { + posVel = propagate(sat.satrec, date); + } catch { + posVel = null; + } + if ( + !posVel?.position || + typeof posVel.position === 'boolean' || + !posVel.velocity || + typeof posVel.velocity === 'boolean' + ) + return null; + const gmst = gstime(date); + if (trackedSample) { + // The sample the camera and the tracked dot were placed from. + copyInto(layerState._trackedFrameCartesian, result); + } else { + const geo = eciToGeodetic(posVel.position, gmst); + copyInto( + fromRadians(geo.longitude, geo.latitude, geo.height * 1000), + result, + ); + } + const axes = stationFlightAxes( + result, + temeToEcefAxes(posVel.velocity, gmst), + ); + return axes ? { date, axes } : null; + } + + /** + * The Cockpit camera's place on the station: one of the views on the + * model, in the world, worked out from the same sample the model is about + * to be placed on, so the camera stays on the model however fast the orbit + * moves it. The spec's `cockpitMount` chooses the view; null for a station + * without views. + * @param {string|null} [key] The view asked for; the first on offer when + * it is not given or not on offer. + * @returns {object|null} Null unless the tracked satellite is the station + * and the model is loaded and may show. + */ + function _cockpitMount(key = null) { + if (!spec.cockpitMount) return null; + if (!ready || !_trackedOnStation() || !_shouldShow()) return null; + const frame = _stationFrame(scratchMountCentre); + if (!frame) return null; + return spec.cockpitMount({ + key, + centre: scratchMountCentre, + axes: frame.axes, + name: (noradId) => layerState._catalog.get(noradId)?.name ?? null, + // An entry is offered to ride only when it has a dot to track. + entry: (noradId) => + noradId !== null && layerState._points.has(noradId) ? noradId : null, + dockedVehicle: _dockedVehicle(), + }); + } + + /** + * A vehicle docked to the station (a Progress, a Shenzhou, a Dragon): the + * tracked one when that is what is tracked, else the lowest catalog number + * among those docked. The station's own modules have entries too (Zarya, + * Nauka; Tianhe, Wentian): they are the station, not a vehicle. Null when + * no vehicle is docked. + * @returns {number|null} + */ + function _dockedVehicle() { + const vehicle = (noradId) => + noradId !== norad && + !spec.isModule(noradId, layerState._catalog.get(noradId)); + const tracked = layerState._trackedNorad; + if (tracked !== null && vehicle(tracked)) return tracked; + let lowest = null; + for (const group of [dockedByOrbit, layerState._dockedCompanions ?? []]) + for (const noradId of group) + if (vehicle(noradId) && (lowest === null || noradId < lowest)) + lowest = noradId; + return lowest; + } + + /** + * Per-frame update from the layer's preRender tick. + * @returns {void} + */ + function _updateStationModel() { + visualValid = false; + // The docked set first: whether the model may show (the Cockpit riding + // the station) is read from it, so it is kept current before that. Once + // a second; the dots are handed over or given back with the scan. + if (item) _scanCompanions(Date.now(), handingOver); + const show = _shouldShow(); + if (!show) { + _hide(); + // The dots draw at every distance while the model may not. + _releaseDots(); + if (handedCompanions.size) _releaseCompanions(); + handingOver = false; + _syncOrbitCloseUp(false); + // Off, the layer gives the model's memory back at once; hidden, after + // a while. + if (!layerState._enabled) _unload(); + else _undrawn(); + return; + } + const dotPosition = parts.rendering._pointPosition(norad); + const eye = _eye(); + const cameraDistance = + dotPosition && eye + ? distance(eye, dotPosition) + : Number.POSITIVE_INFINITY; + if (!item) { + // The file is fetched only once the camera nears the model's range, so + // a globe-wide view of the layer never downloads it. + if ( + !loading && + !failed && + dotPosition && + cameraDistance <= spec.maxDistanceM * 1.5 + ) + _load(dotPosition); + return; + } + // Until the renderer has the model loaded and posed, the dots stand at + // every distance: the station never goes dark while the file loads, nor + // for good when it fails to. + if (!ready) { + _hide(); + _releaseDots(); + if (handedCompanions.size) _releaseCompanions(); + handingOver = false; + _syncOrbitCloseUp(false); + if ( + failedAt !== null && + Date.now() - failedAt >= + (spec.retryAfterMs ?? STATION_MODEL_RETRY_AFTER_MS) + ) + _unload(); // asked for again on the next frame in range + else if (cameraDistance > spec.maxDistanceM * 1.5) _undrawn(); + else undrawnSince = null; + return; + } + // The docked dots are the model's within its range: handed over at + // once when the model starts drawing, then with each scan. + if (!handingOver) { + handingOver = true; + lastCompanionScanMs = Number.NEGATIVE_INFINITY; + _scanCompanions(Date.now(), true); + } + _handOverDots(); + _syncOrbitCloseUp(cameraDistance < spec.orbitHideM); + // Out of range the model would not draw anyway: skip the SGP4 sample. + if (cameraDistance > spec.maxDistanceM * 1.5) { + _hide(); + _undrawn(); + return; + } + undrawnSince = null; + + const frame = _stationFrame(scratchPosition); + if (!frame) { + // Nowhere to draw the model (the orbit would not propagate): the dots + // draw at every distance rather than nothing at all. + _hide(); + _releaseDots(); + return; + } + const { date, axes } = frame; + copyInto(scratchPosition, visualPosition); + copyInto(scratchPosition, item.pos); + item.orientation = stationModelOrientation( + scratchPosition, + axes, + spec.localAxes, + ); + telemetry?.touch(); + articulation.update(nodePoses, date, scratchPosition, axes); + item.show = true; + _send(); + visualValid = ready; + } + + /** + * Where the tracked card should anchor: the station centre the model is + * rendering at this frame, or null while the model is not drawn (the card + * then keeps the dot's position). Up close the dot's cache can be a frame + * ahead of the rendered model, ~130 m of orbit, which shook the card. + * @returns {{x:number,y:number,z:number}|null} + */ + function _visualPosition() { + if (!visualValid || !item?.show) return null; + const eye = _eye(); + if (eye && distance(eye, visualPosition) > spec.maxDistanceM) return null; + return visualPosition; + } + + /** + * How far the tracked card must stay from its anchor to clear the model, in + * pixels, or null while the dot shows. + */ + function _cardClearPx() { + const position = _visualPosition(); + const pose = findCamera(layerState._viewer)?.pose?.() ?? null; + const height = canvasOf(layerState._viewer)?.clientHeight; + const fovy = pose?.fovy; + if (!position || !height || !fovy) return null; + const cameraDistance = distance(pose.position, position); + if (!(cameraDistance > 0)) return null; + const pixelsPerMeter = height / (2 * Math.tan(fovy / 2)) / cameraDistance; + return Math.min( + height * 0.45, + Math.max(spec.minPx * 0.35, spec.cardClearM * pixelsPerMeter), + ); + } + + /** + * The model has not been drawn this frame: once that has lasted + * `unloadAfterMs`, release it. + */ + function _undrawn() { + if (!item) return; + const nowMs = Date.now(); + undrawnSince ??= nowMs; + if ( + nowMs - undrawnSince >= + (spec.unloadAfterMs ?? STATION_MODEL_UNLOAD_AFTER_MS) + ) + _unload(); + } + + /** + * Release the model's draw set, and the renderer's model and GPU memory + * with it; the dots stand at every distance. The next approach loads it + * again (a failed load is tried again then too). + */ + function _unload() { + _releaseDots(); + _releaseCompanions(); + handingOver = false; + loading = false; + failed = false; + failedAt = null; + ready = false; + visualValid = false; + undrawnSince = null; + offReady?.(); + offFailed?.(); + offReady = null; + offFailed = null; + set?.dispose(); + set = null; + item = null; + } + + function _destroyStationModel() { + _unload(); + articulation.reset(); + nodePoses.clear(); + telemetry?.destroy(); + dockedByOrbit.clear(); + lastCompanionScanMs = Number.NEGATIVE_INFINITY; + _syncOrbitCloseUp(false); + } + + /** Whether the model is standing in for this docked object's dot. */ + function _standsInFor(noradId) { + return handedCompanions.has(noradId) && _visualPosition() !== null; + } + + /** + * The station's NORAD number when a draw hit landed on its model, so a + * click on the model tracks the station as a click on its dot does; null + * for any other hit. + * @param {{set?: string, id?: string}|null|undefined} hit The click's + * `drawHit`. + * @returns {number|null} + */ + function _hitNorad(hit) { + return set && hit?.set === set.id && hit.id === itemId ? norad : null; + } + + return { + key: spec.key, + norad, + spec, + _updateStationModel, + _destroyStationModel, + _visualPosition, + _cardClearPx, + _standsInFor, + _hitNorad, + _cockpitMount, + _trackedOnStation, + /** Where the joints' angles come from, or null for a station without telemetry. */ + _telemetryStatus: () => telemetry?.status() ?? null, + /** The joint driver, for the STATION section. */ + _articulation: articulation, + /** The node matrices the joint driver last wrote, by node name (the item's `nodes`). */ + _nodePoses: nodePoses.poses, + }; +} diff --git a/src/layers/satellites/stationModel.test.mjs b/src/layers/satellites/stationModel.test.mjs new file mode 100644 index 0000000000..5884f79074 --- /dev/null +++ b/src/layers/satellites/stationModel.test.mjs @@ -0,0 +1,481 @@ +// src/layers/satellites/stationModel.test.mjs — a station's model over the +// rendering part's draw items: it loads once the camera nears its range, +// stands in for the station's dot, the docked companions' dots and the +// tracked dot within that range (a display range on the dots, the model's +// own display condition the other side of it), hides the ring up close, and +// gives everything back when it may not show or is destroyed. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { eciToGeodetic, gstime, propagate, twoline2satrec } from 'satellite.js'; +import { createOrbits } from './orbits.js'; +import { createRendering } from './rendering.js'; +import { createStationModel } from './stationModel.js'; +import { + ISS_MODEL_LOCAL_AXES, + POINT_STYLES, + TRACKED_ORBIT_COLOR, +} from './policy.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; + +const STATION = 25544; +const COMPANION = 49044; +const STRANGER = 32711; +const ISS = twoline2satrec( + '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927', + '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537', +); +const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0); +const MAX_M = 1_000_000; +/** The dots the model stands in for draw only beyond the model's range. */ +const FAR_RANGE = [MAX_M, Number.MAX_VALUE]; + +/** A satellite's ECEF position at `atMs`, as a plain `{x, y, z}`. */ +function ecef(satrec, atMs) { + const date = new Date(atMs); + const geo = eciToGeodetic(propagate(satrec, date).position, gstime(date)); + const c = Cesium.Cartesian3.fromRadians( + geo.longitude, + geo.latitude, + geo.height * 1000, + ); + return { x: c.x, y: c.y, z: c.z }; +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +const MODEL_SET = 'satellites:station:test'; +const MODEL_ITEM = 'station:test'; + +/** + * A station model over the real rendering part, a fake draw port (the + * model is an item of a `models` set on it) and a fake camera port. The + * station and a companion share an orbit (docked); a stranger's dot sits + * 500 km off. + */ +function fixture(t) { + const stationPos = ecef(ISS, AT_MS); + const strangerPos = { ...stationPos, x: stationPos.x + 500_000 }; + const camera = fakeCameraPort({ + pose: { position: { ...stationPos }, fovy: Math.PI / 3 }, + }); + const viewer = { canvas: { clientHeight: 1000 } }; + const { draw, unbind } = bindFakeDraw(viewer, { camera: camera.port }); + const state = { + now: () => AT_MS, + _enabled: true, + _params: { showPoints: true, showOrbits: true }, + _points: new Map(), + _orbitPaths: new Map(), + _catalog: new Map([ + [STATION, { satrec: ISS, group: 'core', name: 'ISS (ZARYA)' }], + [COMPANION, { satrec: ISS, group: 'core', name: 'ISS (NAUKA)' }], + ]), + _viewer: viewer, + _trackedNorad: null, + _trackedFrameGeo: null, + _trackedFrameNumber: -1, + _dockedCompanions: new Set(), + _cockpitHiddenPath: null, + _cockpitSubjectNorad: null, + _lastPropagation: -Infinity, + _lastReckonMs: AT_MS, + _lastRingRotation: -Infinity, + _lastFocusUpdate: -Infinity, + _activeFocusCount: 0, + }; + const parts = { + orbits: createOrbits({ state: {}, services: {}, parts: {} }), + tracking: { _getTrackedFramePosition: () => null }, + catalog: { _propagateDenseChunk() {} }, + controls: { + _classVisible: () => true, + satelliteVisualsVisible: (enabled, requested) => + Boolean(enabled) && Boolean(requested), + }, + }; + parts.rendering = createRendering({ + state, + services: { + focus: { + focusNowMs: (ms) => ms, + getFocusTarget: () => null, + focusPassIsNeeded: () => false, + }, + }, + parts, + }); + const updates = []; + const spec = { + key: 'test', + label: 'TEST', + norad: STATION, + modelUrl: '/models/test.glb', + scale: 2, + minPx: 64, + maxDistanceM: MAX_M, + orbitHideM: 50_000, + cardClearM: 60, + companionRadiusM: 5_000, + companionCoarseM: 200_000, + companionScanMs: 0, + localAxes: ISS_MODEL_LOCAL_AXES, + isModule: () => true, + createArticulation: () => ({ + update: (...args) => updates.push(args), + reset() {}, + }), + createTelemetry: null, + cockpitMount: null, + hideInCockpit: true, + syncOrbit: null, + }; + const model = createStationModel(spec, { + state, + parts, + resolveAsset: (url) => `/assets${url}`, + }); + parts.stationModels = [model]; + parts.rendering._attach(viewer); + parts.rendering._addPoint(STATION, stationPos, POINT_STYLES.iss); + parts.rendering._addPoint(COMPANION, stationPos, POINT_STYLES.iss); + parts.rendering._addPoint(STRANGER, strangerPos, POINT_STYLES.iss); + const points = [...draw.sets.keys()].find((id) => id.endsWith(':points')); + const set = (suffix) => draw.set(points.replace(':points', suffix)); + let frame = 0; + t.after(() => unbind()); + const f = { + state, + parts, + model, + updates, + stationPos, + strangerPos, + /** The model's draw set, while it is live. */ + modelSet: () => draw.set(MODEL_SET), + /** The model's draw item, once asked for. */ + modelItem: () => draw.set(MODEL_SET)?.items.get(MODEL_ITEM), + cameraAt(metres) { + camera.setPose({ + position: { ...stationPos, x: stationPos.x + metres }, + }); + }, + tick() { + parts.rendering._preRenderTick({ frame: ++frame }); + }, + /** Bring the camera into loading range and let the renderer load it. */ + async load() { + f.cameraAt(MAX_M * 1.4); + f.tick(); + draw.ready(MODEL_SET, MODEL_ITEM); + await settle(); + }, + /** The renderer reports the model loaded, or failed to. */ + readyModel: () => draw.ready(MODEL_SET, MODEL_ITEM), + failModel: () => draw.loadFailed(MODEL_SET, MODEL_ITEM), + /** Track `noradId`, placing the tracked sample on the station. */ + track(noradId, at) { + state._trackedNorad = noradId; + state._trackedFrameGeo = { atMs: AT_MS }; + Object.assign(state._trackedFrameCartesian, at); + parts.rendering._removeTrackedEntity(); + parts.rendering._addTrackedEntity({ position: () => at }); + }, + drawn: (id) => set(':points').items.get(String(id)), + trackedDot: () => set(':tracked').items.get(String(state._trackedNorad)), + ring: (id) => set(':rings').items.get(String(id)), + }; + return f; +} + +test('the model loads once the camera nears its range, measured from the dot as drawn', async (t) => { + const f = fixture(t); + f.cameraAt(MAX_M * 5); + f.tick(); + assert.equal(f.modelSet(), undefined, 'a globe-wide view never asks for it'); + f.cameraAt(MAX_M * 1.4); + f.tick(); + const item = f.modelItem(); + assert.ok(item, 'one item of a models set of its own'); + assert.equal(item.url, '/assets/models/test.glb'); + assert.deepEqual( + item.meta, + { norad: STATION }, + 'a click on the model tracks the station', + ); + assert.equal(item.scale, 2); + assert.equal(item.minPixelSize, 64); + assert.deepEqual(item.displayRange, [0, MAX_M], 'drawn within its range'); + assert.equal(item.show, false, 'hidden until posed'); + const writes = f.modelSet().writes; + f.cameraAt(MAX_M * 5); + f.tick(); + assert.equal(f.modelSet().writes, writes, 'out of range nothing is sent'); + assert.equal(f.model._hitNorad({ set: MODEL_SET, id: MODEL_ITEM }), STATION); + assert.equal(f.model._hitNorad({ set: 'other', id: MODEL_ITEM }), null); + assert.equal(f.model._hitNorad(null), null); + assert.equal( + f.model._visualPosition(), + null, + 'the card keeps the dot until the renderer has the model', + ); +}); + +test('posed, the model sits on the station with its flight axes as heading, pitch and roll', async (t) => { + const f = fixture(t); + await f.load(); + f.cameraAt(20_000); + f.tick(); + const item = f.modelItem(); + assert.equal(item.show, true); + assert.ok(Math.abs(item.pos.x - f.stationPos.x) < 1, 'on the station'); + // The renderer places a model by heading, pitch and roll at its position + // (Cesium's headingPitchRollToFixedFrame): the frame that gives must have + // the model's local axes where ISS_MODEL_LOCAL_AXES says, zenith away from + // the Earth and along-track horizontal. + const { heading, pitch, roll } = item.orientation; + const at = new Cesium.Cartesian3(item.pos.x, item.pos.y, item.pos.z); + const m = Cesium.Transforms.headingPitchRollToFixedFrame( + at, + new Cesium.HeadingPitchRoll(heading, pitch, roll), + ); + const column = (c) => [m[c * 4], m[c * 4 + 1], m[c * 4 + 2]]; + const up = Cesium.Cartesian3.normalize(at, new Cesium.Cartesian3()); + const along = (v) => v[0] * up.x + v[1] * up.y + v[2] * up.z; + const zenith = column(ISS_MODEL_LOCAL_AXES.indexOf('z')); + assert.ok( + Math.abs(along(zenith) - 1) < 1e-6, + 'the zenith axis points away from the Earth', + ); + const track = column(ISS_MODEL_LOCAL_AXES.indexOf('x')); + assert.ok(Math.abs(along(track)) < 1e-6, 'the along-track axis is level'); + assert.equal(f.updates.length, 1, 'the joints are driven'); + const nodes = f.updates[0][0]; + assert.equal(nodes.ready, true, 'into node poses'); + // What the driver writes to a node is the item's `nodes`, by name, as a + // column-major matrix the renderer applies to the model's glTF node. + const turned = new Float64Array(16); + turned[0] = turned[5] = turned[10] = turned[15] = 1; + turned[14] = 2.5; + nodes.getNode('SOLAR_JOINT').matrix = turned; + f.tick(); + assert.equal(item.nodes, f.model._nodePoses, 'one object for the item'); + assert.deepEqual(Array.from(item.nodes.SOLAR_JOINT), Array.from(turned)); + f.model._destroyStationModel(); + assert.equal( + Object.keys(f.model._nodePoses).length, + 0, + 'destroyed, every node goes back to its authored pose', + ); +}); + +test('a station without views on its model hides it while the Cockpit rides the station, its own entry or a docked one', async (t) => { + const f = fixture(t); + let held = false; + f.parts.cockpit = { _cockpitHeld: () => held }; + await f.load(); + f.cameraAt(20); + // Riding a docked object (the companion shares the orbit). + f.track(COMPANION, f.stationPos); + f.tick(); + assert.equal(f.modelItem().show, true, 'outside the Cockpit it draws'); + held = true; + // Frame after frame: hiding the model gives the docked dots back, and + // that must not make the layer forget the companion is docked (which + // showed the model again, and so on, every other frame). + for (let i = 0; i < 4; i++) { + f.tick(); + assert.equal( + f.modelItem().show, + false, + `the Cockpit camera would sit inside the hull (tick ${i})`, + ); + assert.equal(f.model._trackedOnStation(), true, `docked (tick ${i})`); + } + assert.equal(f.model._visualPosition(), null); + // Riding the station itself. + held = false; + f.track(STATION, f.stationPos); + f.tick(); + assert.equal(f.modelItem().show, true); + held = true; + f.tick(); + assert.equal(f.modelItem().show, false); + // A station that mounts the Cockpit camera on its model keeps drawing. + f.model.spec.hideInCockpit = false; + f.tick(); + assert.equal(f.modelItem().show, true); +}); + +test('until the renderer has the model the dots stand at every distance, and stay so when it fails to load', async (t) => { + const f = fixture(t); + f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR); + f.track(COMPANION, f.stationPos); + f.cameraAt(MAX_M * 1.4); + f.tick(); // asks for the model + f.cameraAt(20_000); + f.tick(); + f.tick(); + // Loading: nothing is handed over, so the station never goes dark. + assert.equal(f.modelItem().show, false); + assert.equal(f.drawn(STATION).displayRange, undefined); + assert.equal(f.drawn(COMPANION).displayRange, undefined); + assert.equal(f.trackedDot().displayRange, undefined); + assert.equal( + f.ring(STATION).show, + true, + 'the ring is not hidden for a model not drawn', + ); + assert.equal(f.model._visualPosition(), null, 'the card keeps the dot'); + assert.equal(f.model._cockpitMount(), null); + // The load fails: the dots stay at every distance, frame after frame. + f.failModel(); + for (let i = 0; i < 3; i++) f.tick(); + assert.equal(f.modelItem().show, false); + assert.equal(f.drawn(STATION).displayRange, undefined); + assert.equal(f.drawn(COMPANION).displayRange, undefined); + assert.equal(f.trackedDot().displayRange, undefined); + // After the retry delay the model is released, and the next frame asks + // for it again: one transient failure does not cost the session. + f.model.spec.retryAfterMs = 0; + f.tick(); + assert.equal(f.modelSet(), undefined, 'released after a failure'); + f.tick(); + assert.ok(f.modelItem(), 'asked for again'); + // That load finishes: the dots are handed over. + f.readyModel(); + f.tick(); + assert.equal(f.modelItem().show, true); + assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE); + assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE); +}); + +test('a model still loading counts as undrawn out of range and is released', (t) => { + const f = fixture(t); + f.cameraAt(MAX_M * 1.4); + f.tick(); // asks for the model, which never answers + f.cameraAt(MAX_M * 5); + f.tick(); + assert.ok(f.modelSet(), 'kept for a while'); + f.model.spec.unloadAfterMs = 0; + f.tick(); + assert.equal(f.modelSet(), undefined); +}); + +test('turning the layer off, or a while undrawn, releases the model; the next approach asks for it again', async (t) => { + const f = fixture(t); + await f.load(); + f.cameraAt(20_000); + f.tick(); + assert.equal(f.modelItem().show, true); + // Out of range, within the grace: kept. + f.cameraAt(MAX_M * 5); + f.tick(); + assert.ok(f.modelSet(), 'kept for a while'); + // Past it: released, and the dots stand everywhere. + f.model.spec.unloadAfterMs = 0; + f.tick(); + assert.equal(f.modelSet(), undefined, 'its set is disposed'); + assert.equal(f.drawn(STATION).displayRange, undefined); + // The next approach asks for it again. + f.cameraAt(MAX_M * 1.4); + f.tick(); + assert.ok(f.modelItem(), 'asked for again'); + f.readyModel(); + f.cameraAt(20_000); + f.tick(); + assert.equal(f.modelItem().show, true); + // Turning the layer off releases it at once. + f.model.spec.unloadAfterMs = 60_000; + // (The layer's disable asks the model once, as here: no frame runs then.) + f.state._enabled = false; + f.model._updateStationModel(); + assert.equal(f.modelSet(), undefined); + assert.equal(f.drawn(STATION).displayRange, undefined); +}); + +test('within its range the model stands in for the dots and hides the ring; beyond it the dots draw', async (t) => { + const f = fixture(t); + await f.load(); + f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR); + f.cameraAt(20_000); + f.tick(); + assert.equal(f.modelItem().show, true); + assert.equal(f.updates.length, 1, 'the joints are driven'); + assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE); + assert.deepEqual( + f.drawn(COMPANION).displayRange, + FAR_RANGE, + 'docked, by orbit against orbit', + ); + assert.equal(f.drawn(STRANGER).displayRange, undefined, 'not docked'); + assert.equal( + f.drawn(STATION).show, + true, + 'the range alone splits the distances', + ); + assert.equal(f.model._standsInFor(COMPANION), true); + assert.equal(f.model._standsInFor(STRANGER), false); + assert.equal( + f.ring(STATION).show, + false, + 'the ring runs off the model up close', + ); + assert.ok(f.model._visualPosition(), 'the card anchors on the model'); + assert.ok(f.model._cardClearPx() > 0); + // The tracked dot too, while the tracked satellite is the station (here + // an object docked to it)… + f.track(COMPANION, f.stationPos); + f.tick(); + assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE); + // …and not once another satellite is tracked. + f.track(STRANGER, f.strangerPos); + f.tick(); + assert.equal(f.trackedDot().displayRange, undefined); + // Beyond its range the model is not drawn and the dots are, by their range. + f.cameraAt(MAX_M * 2.5); + f.tick(); + assert.equal(f.modelItem().show, false); + assert.equal(f.model._visualPosition(), null); + assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE); + assert.equal(f.ring(STATION).show, true, "back to the layer's orbit toggle"); +}); + +test('the dots and the ring come back when the model may not show, and on destroy', async (t) => { + const f = fixture(t); + await f.load(); + f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR); + f.track(COMPANION, f.stationPos); + f.cameraAt(20_000); + f.tick(); + assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE); + assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE); + assert.equal(f.ring(STATION).show, false); + // Points off: the model may not show, so every dot draws at any distance. + f.state._params.showPoints = false; + f.tick(); + assert.equal(f.modelItem().show, false); + assert.equal(f.drawn(STATION).displayRange, undefined); + assert.equal(f.drawn(COMPANION).displayRange, undefined); + assert.equal(f.trackedDot().displayRange, undefined); + assert.equal(f.model._standsInFor(COMPANION), false); + assert.equal(f.ring(STATION).show, true); + // Points on again: handed over again. + f.state._params.showPoints = true; + f.tick(); + assert.equal(f.modelItem().show, true); + assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE); + assert.deepEqual(f.drawn(COMPANION).displayRange, FAR_RANGE); + assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE); + assert.equal(f.ring(STATION).show, false); + // Destroyed: the model leaves the scene and the dots are given back. + f.model._destroyStationModel(); + f.parts.rendering._flushPoints(); + assert.equal(f.modelSet(), undefined, 'its set is disposed'); + assert.equal(f.drawn(STATION).displayRange, undefined); + assert.equal(f.drawn(COMPANION).displayRange, undefined); + assert.equal(f.trackedDot().displayRange, undefined); + assert.equal(f.ring(STATION).show, true); + assert.equal(f.model._visualPosition(), null); +}); diff --git a/src/layers/satellites/stationModels.js b/src/layers/satellites/stationModels.js new file mode 100644 index 0000000000..722b972ec4 --- /dev/null +++ b/src/layers/satellites/stationModels.js @@ -0,0 +1,92 @@ +import { STATIONS, stationTrackedOn } from './policy.js'; + +/** + * Which station a catalog entry belongs to. The layer knows more than one + * station (STATIONS in policy.js: the ISS, Tiangong), each drawn as a model + * part (stationModel.js) at its own catalog entry and standing in for the + * entries docked to it; the parts that key behaviour to "the station" (card + * anchor and clearance, detection marks, the LIVE and STATION sections, the + * Cockpit's mounts) ask here instead of naming the ISS. The model parts are + * read from `parts.stationModels` each time, so a layer built without them + * (tests, a part replaced) still answers. + */ + +/** + * The model whose station `noradId` is drawn as: the station's own entry, + * or a docked object whose dot the model stands in for right now. + * @param {Array<{norad: number, _standsInFor?: (noradId: number) => boolean}>} models + * @param {number|null|undefined} noradId + * @returns {object|null} + */ +export function stationModelFor(models, noradId) { + if (noradId === null || noradId === undefined) return null; + for (const model of models) + if (model.norad === noradId || model._standsInFor?.(noradId)) return model; + return null; +} + +/** + * The station that is selected: the tracked satellite is the station + * itself, or an object docked to it, judged by the dots sharing a position + * (`dockedCompanions`), by both orbits compared when tracking began + * (`trackedDockedToStation`, the station's NORAD or null), or by the + * station's model standing in for its dot. + * @param {ReadonlyArray<{key: string, norad: number}>} stations + * @param {Array<{norad: number, _standsInFor?: (noradId: number) => boolean}>} models + * @param {{trackedNorad: number|null, dockedCompanions?: {has(id: number): boolean}|null, + * trackedDockedToStation?: number|null}} selection + * @returns {{key: string, norad: number, model: object|null}|null} The + * station and its model part (null when none is built). + */ +export function trackedStationOf( + stations, + models, + { trackedNorad, dockedCompanions, trackedDockedToStation }, +) { + if (trackedNorad === null || trackedNorad === undefined) return null; + for (const station of stations) { + const model = models.find((m) => m.norad === station.norad) ?? null; + if ( + stationTrackedOn(station.norad, trackedNorad, dockedCompanions) || + trackedDockedToStation === station.norad || + Boolean(model?._standsInFor?.(trackedNorad)) + ) + return { ...station, model }; + } + return null; +} + +/** The layer's station model parts, as built (index.js). */ +export function stationModels(parts) { + return parts.stationModels ?? []; +} + +/** See stationModelFor, over the layer's model parts. */ +export function modelFor(parts, noradId) { + return stationModelFor(stationModels(parts), noradId); +} + +/** See trackedStationOf, over the layer's stations, model parts and state. */ +export function trackedStation(layerState, parts) { + return trackedStationOf(STATIONS, stationModels(parts), { + trackedNorad: layerState._trackedNorad, + dockedCompanions: layerState._dockedCompanions, + trackedDockedToStation: layerState._trackedDockedToStation ?? null, + }); +} + +/** + * The station whose model a click's draw hit landed on, over the layer's + * model parts: its NORAD number, or null for any other hit. + * @param {object} parts + * @param {{set?: string, id?: string}|null|undefined} hit + * @returns {number|null} + */ +export function modelHitNorad(parts, hit) { + if (!hit) return null; + for (const model of stationModels(parts)) { + const norad = model._hitNorad?.(hit) ?? null; + if (norad !== null) return norad; + } + return null; +} diff --git a/src/layers/satellites/stationModels.test.mjs b/src/layers/satellites/stationModels.test.mjs new file mode 100644 index 0000000000..ec2ec722e1 --- /dev/null +++ b/src/layers/satellites/stationModels.test.mjs @@ -0,0 +1,91 @@ +// src/layers/satellites/stationModels.test.mjs — which station a catalog +// entry belongs to, over stand-in model parts. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { ISS_NORAD, STATIONS, TIANGONG_NORAD } from './policy.js'; +import { + modelFor, + stationModelFor, + trackedStation, + trackedStationOf, +} from './stationModels.js'; + +const NAUKA = 49044; +const SHENZHOU = 60000; +const GPS = 32711; + +const part = (norad, standsIn = []) => ({ + norad, + _standsInFor: (id) => standsIn.includes(id), +}); + +test('the layer knows the ISS and Tiangong, each with a LIVE key', () => { + assert.deepEqual( + STATIONS.map((s) => [s.key, s.norad]), + [ + ['iss', ISS_NORAD], + ['tiangong', TIANGONG_NORAD], + ], + ); + for (const station of STATIONS) assert.ok(station.companionRadiusM > 0); +}); + +test('an entry is drawn by the model at its own number, or one standing in for it', () => { + const iss = part(ISS_NORAD, [NAUKA]); + const tiangong = part(TIANGONG_NORAD, [SHENZHOU]); + const models = [iss, tiangong]; + assert.equal(stationModelFor(models, ISS_NORAD), iss); + assert.equal(stationModelFor(models, NAUKA), iss); + assert.equal(stationModelFor(models, TIANGONG_NORAD), tiangong); + assert.equal(stationModelFor(models, SHENZHOU), tiangong); + assert.equal(stationModelFor(models, GPS), null); + assert.equal(stationModelFor(models, null), null); + assert.equal(stationModelFor([], ISS_NORAD), null); +}); + +test('the selected station: itself, a docked companion by position, by orbit, or by stand-in', () => { + const models = [part(ISS_NORAD), part(TIANGONG_NORAD, [SHENZHOU])]; + const select = (selection) => trackedStationOf(STATIONS, models, selection); + assert.equal(select({ trackedNorad: null }), null); + assert.equal(select({ trackedNorad: GPS }), null); + assert.equal(select({ trackedNorad: ISS_NORAD })?.key, 'iss'); + assert.equal(select({ trackedNorad: TIANGONG_NORAD })?.key, 'tiangong'); + // Nauka's dot shares the ISS's position. + assert.equal( + select({ trackedNorad: NAUKA, dockedCompanions: new Set([ISS_NORAD]) }) + ?.key, + 'iss', + ); + // A Tianzhou judged docked by orbit when tracking began. + assert.equal( + select({ trackedNorad: 60001, trackedDockedToStation: TIANGONG_NORAD }) + ?.key, + 'tiangong', + ); + // A Shenzhou whose dot the Tiangong model stands in for. + assert.equal(select({ trackedNorad: SHENZHOU })?.key, 'tiangong'); + // The answer carries the station's model part, or null without one. + assert.equal(select({ trackedNorad: ISS_NORAD })?.model, models[0]); + assert.equal( + trackedStationOf(STATIONS, [], { trackedNorad: TIANGONG_NORAD })?.model, + null, + ); +}); + +test('the layer-state readers take the parts as built, or none', () => { + const parts = {}; + const layerState = { + _trackedNorad: SHENZHOU, + _dockedCompanions: new Set(), + _trackedDockedToStation: TIANGONG_NORAD, + }; + assert.equal(modelFor(parts, ISS_NORAD), null); + assert.equal(trackedStation(layerState, parts)?.key, 'tiangong'); + assert.equal(trackedStation(layerState, parts)?.model, null); + parts.stationModels = [part(TIANGONG_NORAD)]; + assert.equal( + trackedStation(layerState, parts)?.model, + parts.stationModels[0], + ); + assert.equal(modelFor(parts, TIANGONG_NORAD), parts.stationModels[0]); +}); diff --git a/src/layers/satellites/stationPanel.js b/src/layers/satellites/stationPanel.js new file mode 100644 index 0000000000..e159c88a41 --- /dev/null +++ b/src/layers/satellites/stationPanel.js @@ -0,0 +1,376 @@ +import { distance } from '../../geo/index.js'; +import { findCamera, findFrame } from '../../render/rendererOf.js'; +import { + issCommandCameraOnStation, + issCommandOffersZoom, + issCommandZoomOffset, +} from './issCommand.js'; + +/** + * The STATION section in Context, for whichever station is selected. A + * station is described once (`issStation.js` describes the ISS) and this + * presents it: Automatic, where the joints follow their rules and the panel + * says where the angles come from (telemetry, or computed when there is + * none); Manual, where the person moves them with the controls the + * description lists; and a zoom to the station from far away. Another + * station plugs in with a description of its own. + * + * @typedef {object} StationDescription + * @property {string} key Short id, e.g. 'iss'. + * @property {string} title The station's name, as a badge. + * @property {() => boolean} selected Whether this station is the tracked + * subject (also as one of its docked entries). + * @property {() => string} subjectName The tracked entry's name. + * @property {() => object|null} articulation The joint driver. + * @property {() => {state: string, poseAgeMs: number|null, + * liveUntilMs: number|null}|null} telemetry Where the angles come from. + * @property {() => {x: number, y: number, z: number}|null} position The + * station's drawn centre (ECEF metres), for the zoom. + * @property {string} zoomLabel The zoom button's text (a msg key). + * @property {{live?: string, computed: string}} notes Automatic's note on + * what moves the joints (msg keys): `live` while the articulation reports + * telemetry, `computed` otherwise (and always, for a station without a + * feed). + * @property {Array<{id: string, label: string, note?: string|null, + * kind: 'choices', choices: Array<{id: string, label: string, + * isDefault?: boolean, apply: (articulation: object) => void}>}| + * {id: string, label: string, kind: 'sliders', resume?: string, + * sliders: Array<{id: string, label: string, min: number, max: number, + * apply: (articulation: object, value: number) => void}>, + * resumeApply?: (articulation: object) => void}>} groups Manual controls. + * @property {(articulation: object) => void} automatic Hand every joint + * back to its rule. + */ + +/** How often the status line's age is refreshed while the panel shows. */ +export const STATION_PANEL_TICK_MS = 1000; + +/** + * @param {{state: object, parts: object, stations: StationDescription[], + * now?: () => number}} context + */ +export function createStationPanel({ + state: layerState, + parts, + stations, + now = Date.now, +}) { + const listeners = new Set(); + let view = null; + /** The station shown, its mode, its Manual choices and slider values. */ + let current = null; + let mode = 'automatic'; + let choices = new Map(); + let sliders = new Map(); + let ticker = null; + let zoomTimer = null; + /** The frame pump while a joint glides, and when it stops. */ + let pump = null; + let pumpUntil = 0; + /** The last view published, as text: an unchanged view is not republished. */ + let publishedKey = null; + + function _stationShown() { + if (!layerState._enabled) return null; + // The right rail is hidden while the Cockpit rides; nothing to show. + if (parts.cockpit?._cockpitHeld()) return null; + return stations.find((station) => station.selected()) ?? null; + } + + function _resetManual(station) { + choices = new Map(); + sliders = new Map(); + for (const group of station?.groups ?? []) { + if (group.kind === 'choices') { + const chosen = group.choices.find((choice) => choice.isDefault); + if (chosen) choices.set(group.id, chosen.id); + } else for (const slider of group.sliders) sliders.set(slider.id, 0); + } + } + + /** + * The telemetry status with its ages in whole seconds: the section words + * them so, and an age in ms would make every frame a change. + */ + function wholeSeconds(status) { + if (!status) return status; + const second = (ms) => + Number.isFinite(ms) ? Math.floor(ms / 1000) * 1000 : ms; + return { ...status, poseAgeMs: second(status.poseAgeMs) }; + } + + function _publish() { + const station = current; + if (!station) { + if (view !== null) { + view = null; + publishedKey = null; + for (const listener of listeners) listener(null); + } + return; + } + const articulation = station.articulation(); + const position = station.position(); + const eye = position + ? (findCamera(layerState._viewer)?.pose?.()?.position ?? null) + : null; + const range = position && eye ? distance(eye, position) : null; + const next = { + key: station.key, + title: station.title, + subject: station.subjectName(), + mode, + telemetry: wholeSeconds(station.telemetry()), + sunlit: mode === 'manual' ? null : (articulation?.isSunlit?.() ?? null), + note: + (articulation?.isLive?.() ? station.notes?.live : null) ?? + station.notes?.computed ?? + '', + groups: station.groups.map((group) => + group.kind === 'choices' + ? { + id: group.id, + label: group.label, + note: group.note ?? null, + kind: 'choices', + choices: group.choices.map((choice) => ({ + id: choice.id, + label: choice.label, + active: choices.get(group.id) === choice.id, + })), + } + : { + id: group.id, + label: group.label, + note: group.note ?? null, + kind: 'sliders', + resume: group.resume ?? null, + sliders: group.sliders.map((slider) => ({ + id: slider.id, + label: slider.label, + min: slider.min, + max: slider.max, + value: sliders.get(slider.id) ?? 0, + })), + }, + ), + zoom: { + offered: + range !== null && issCommandOffersZoom(range) && _cameraOnStation(), + label: station.zoomLabel, + }, + }; + // Called every frame from the tick: the section re-renders only on a + // change (the age line moves once a second, the rest on an action). + const key = JSON.stringify(next); + if (key === publishedKey) return; + publishedKey = key; + view = next; + for (const listener of listeners) listener(view); + } + + function _tick() { + if (ticker) return; + ticker = setInterval(() => { + if (!current) { + clearInterval(ticker); + ticker = null; + return; + } + _publish(); + _requestRender(); + }, STATION_PANEL_TICK_MS); + ticker.unref?.(); + } + + /** Ask the renderer for a frame, through the frame port. */ + function _requestRender() { + findFrame(layerState._viewer)?.requestRender('station-panel'); + } + + /** + * Keep frames coming while a joint glides to a new pose: one pump, run + * until the latest ask (a slider drag asks many times a second). + */ + function _renderFor(ms) { + if (!findFrame(layerState._viewer)) return; + pumpUntil = Math.max(pumpUntil, now() + ms); + if (pump) return; + pump = setInterval(() => { + _requestRender(); + if (now() > pumpUntil) _stopPump(); + }, 33); + pump.unref?.(); + } + + function _stopPump() { + if (pump) clearInterval(pump); + pump = null; + pumpUntil = 0; + } + + function _stopZoom() { + if (zoomTimer) clearInterval(zoomTimer); + zoomTimer = null; + } + + /** + * Whether the camera follows the layer's follow target, framed (see + * issCommand.js): the tracked satellite is the station, or docked to it. + */ + function _cameraOnStation() { + return issCommandCameraOnStation( + findCamera(layerState._viewer), + layerState._followTarget, + ); + } + + /** + * Bring the follow camera in to the station, a step per frame. Only while + * the follow camera is on it: from any other camera the steps would lead + * away, and a zoom pressed during the flight to the station would do so. + */ + function _zoom() { + _stopZoom(); + if (!_cameraOnStation()) return false; + let steps = 0; + zoomTimer = setInterval(() => { + const camera = findCamera(layerState._viewer); + steps += 1; + if ( + !camera || + !current?.position() || + !current?.selected() || + !_cameraOnStation() || + steps > 400 + ) { + _stopZoom(); + return; + } + // While the camera follows the station, its follow offset is the eye's + // offset from it: shorten that, never move along the view. The port + // asks for the frame itself. + const next = issCommandZoomOffset(camera.followOffset.get()); + if (!next) { + _stopZoom(); + return; + } + camera.followOffset.set(next); + }, 16); + return true; + } + + const actions = { + setStationMode(next) { + const articulation = current?.articulation(); + if (!current || !articulation) return false; + const wanted = next === 'manual' ? 'manual' : 'automatic'; + if (wanted === mode) return true; + mode = wanted; + if (mode === 'manual') articulation.setTelemetryAllowed?.(false); + else { + _resetManual(current); + current.automatic(articulation); + } + _renderFor(20_000); + _publish(); + return true; + }, + chooseStation(groupId, choiceId) { + const articulation = current?.articulation(); + const group = current?.groups.find((g) => g.id === groupId); + const choice = group?.choices?.find((c) => c.id === choiceId); + if (!articulation || !choice) return false; + choices.set(groupId, choiceId); + choice.apply(articulation); + _renderFor(20_000); + _publish(); + return true; + }, + slideStation(sliderId, value) { + const articulation = current?.articulation(); + const group = current?.groups.find((g) => + g.sliders?.some((s) => s.id === sliderId), + ); + const slider = group?.sliders.find((s) => s.id === sliderId); + const number = Number(value); + if (!articulation || !slider || !Number.isFinite(number)) return false; + const clamped = Math.min(slider.max, Math.max(slider.min, number)); + sliders.set(sliderId, clamped); + slider.apply(articulation, clamped); + _renderFor(2000); + _publish(); + return true; + }, + resumeStationArm(groupId) { + const articulation = current?.articulation(); + const group = current?.groups.find((g) => g.id === groupId); + if (!articulation || !group?.resumeApply) return false; + for (const slider of group.sliders) sliders.set(slider.id, 0); + group.resumeApply(articulation); + _renderFor(20_000); + _publish(); + return true; + }, + zoomStation() { + if (!current) return false; + return _zoom(); + }, + }; + + /** + * Per tick and on tracking changes: show the selected station's panel, + * or take it down. Leaving a station hands its joints back to Automatic, + * so no manual pose lingers. + */ + function _syncStationPanel() { + const station = _stationShown(); + if (station !== current) { + if (current && mode === 'manual') { + const articulation = current.articulation(); + if (articulation) current.automatic(articulation); + } + _stopZoom(); + current = station; + mode = 'automatic'; + _resetManual(station); + if (station) _tick(); + } + _publish(); + } + + function _destroyStationPanel() { + // The joints go back to Automatic with the panel, as on leaving a station. + if (current && mode === 'manual') { + const articulation = current.articulation(); + if (articulation) current.automatic(articulation); + } + _stopZoom(); + _stopPump(); + if (ticker) clearInterval(ticker); + ticker = null; + current = null; + mode = 'automatic'; + _publish(); + } + + const methods = { + /** + * Receive the STATION section's view: the current one at once, then + * each change; null while no station is selected. + * @param {(view: object|null) => void} listener + * @returns {() => void} Stops listening. + */ + subscribeStationPanel(listener) { + listeners.add(listener); + listener(view); + return () => listeners.delete(listener); + }, + /** The actions the section's controls call (the store's owners). */ + getStationActions() { + return actions; + }, + }; + + return { _syncStationPanel, _destroyStationPanel, methods }; +} diff --git a/src/layers/satellites/stationPanel.test.mjs b/src/layers/satellites/stationPanel.test.mjs new file mode 100644 index 0000000000..faf0075402 --- /dev/null +++ b/src/layers/satellites/stationPanel.test.mjs @@ -0,0 +1,370 @@ +// src/layers/satellites/stationPanel.test.mjs — the STATION section's +// presenter, over a stand-in station description. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import { ISS_COMMAND_ZOOM_RANGE_M } from './issCommand.js'; +import { createStationPanel } from './stationPanel.js'; + +/** + * A camera port that follows what it is told to and keeps a follow offset, + * as the renderer's does once the follow has framed the eye. + */ +function fakeFollowCamera({ eye, offset }) { + const camera = { + eye, + offset, + followed: null, + followFramed: false, + offsetsSet: [], + pose: () => ({ position: { ...camera.eye } }), + followOffset: { + get: () => (camera.followFramed ? { ...camera.offset } : null), + set(next) { + camera.offset = { ...next }; + camera.offsetsSet.push({ ...next }); + }, + }, + }; + return camera; +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +function fixture() { + const calls = []; + const articulation = { + isSunlit: () => true, + isLive: () => false, + setTelemetryAllowed: (allowed) => calls.push(['telemetry', allowed]), + }; + let selected = false; + let held = false; + let position = null; + let telemetry = { state: 'live', poseAgeMs: 3000, liveUntilMs: null }; + const station = { + key: 'test', + title: 'TEST', + selected: () => selected, + subjectName: () => 'TEST STATION', + articulation: () => articulation, + telemetry: () => telemetry, + position: () => position, + zoomLabel: 'Zoom to the station', + notes: { + live: 'Joints on live telemetry.', + computed: 'Computed, not live telemetry.', + }, + groups: [ + { + id: 'sun', + label: 'Sun position', + kind: 'choices', + choices: [ + { + id: 'follow', + label: 'Follow', + isDefault: true, + apply: () => calls.push(['sun', 'follow']), + }, + { + id: 'ahead', + label: 'Ahead', + apply: () => calls.push(['sun', 'ahead']), + }, + ], + }, + { + id: 'arm', + label: 'Arm', + kind: 'sliders', + resume: 'Resume', + sliders: [ + { + id: 'shoulder', + label: 'Shoulder', + min: -120, + max: 120, + apply: (a, v) => calls.push(['shoulder', v]), + }, + { + id: 'elbow', + label: 'Elbow', + min: -90, + max: 90, + apply: (a, v) => calls.push(['elbow', v]), + }, + ], + resumeApply: () => calls.push(['resume']), + }, + ], + automatic: () => calls.push(['automatic']), + }; + const layerState = { _enabled: true, _viewer: null }; + const parts = { cockpit: { _cockpitHeld: () => held } }; + const panel = createStationPanel({ + state: layerState, + parts, + stations: [station], + }); + const views = []; + panel.methods.subscribeStationPanel((view) => views.push(view)); + const actions = panel.methods.getStationActions(); + return { + panel, + actions, + calls, + views, + view: () => views.at(-1), + layerState, + select: (on) => (selected = on), + hold: (on) => (held = on), + setTelemetry: (next) => (telemetry = next), + setPosition: (next) => (position = next), + }; +} + +test('the zoom is offered, and runs, only while the follow camera is on the station', async (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + const viewer = {}; + const camera = fakeFollowCamera({ + eye: { x: 5000, y: 0, z: 0 }, + offset: { x: 3000, y: 4000, z: 0 }, + }); + const frames = []; + const { unbind } = bindFakeDraw(viewer, { + camera, + frame: { requestRender: (reason) => frames.push(reason) }, + }); + t.after(unbind); + const target = { key: 'satellites:25544' }; + f.layerState._viewer = viewer; + f.layerState._followTarget = target; + f.setPosition({ x: 0, y: 0, z: 0 }); + f.select(true); + f.panel._syncStationPanel(); + assert.equal(f.view().zoom.offered, false, 'still flying to the station'); + assert.equal(f.actions.zoomStation(), false); + camera.followed = { key: 'flights:other' }; + camera.followFramed = true; + f.panel._syncStationPanel(); + assert.equal(f.view().zoom.offered, false, 'following something else'); + camera.followed = target; + camera.followFramed = false; + f.panel._syncStationPanel(); + assert.equal(f.view().zoom.offered, false, 'the follow has not framed yet'); + camera.followFramed = true; + f.panel._syncStationPanel(); + assert.equal(f.view().zoom.offered, true); + assert.equal(f.actions.zoomStation(), true); + await sleep(120); + const ranges = camera.offsetsSet.map((o) => Math.hypot(o.x, o.y, o.z)); + assert.ok(ranges.length >= 3, 'the zoom stepped the follow offset'); + for (let i = 0; i < ranges.length; i++) { + const before = i === 0 ? 5000 : ranges[i - 1]; + assert.ok( + ranges[i] < before, + `step ${i} came in: ${before} -> ${ranges[i]}`, + ); + assert.ok(ranges[i] >= ISS_COMMAND_ZOOM_RANGE_M, 'never past the range'); + } + // The bearing is kept: the offset only shortens. + const last = camera.offsetsSet.at(-1); + assert.ok(Math.abs(last.x / last.y - 3 / 4) < 1e-9); + assert.equal(last.z, 0); + // The follow ending stops the zoom where it is. + camera.followed = null; + const steps = camera.offsetsSet.length; + await sleep(50); + assert.equal(camera.offsetsSet.length, steps); + camera.followed = target; + camera.eye = { x: 300, y: 0, z: 0 }; + f.panel._syncStationPanel(); + assert.equal(f.view().zoom.offered, false, 'close in, the zoom goes'); + assert.ok(frames.length === 0 || frames.every((r) => r === 'station-panel')); +}); + +test('a new subscriber gets the current view at once: nothing while no station is selected', () => { + const f = fixture(); + assert.deepEqual(f.views, [null]); + f.panel._syncStationPanel(); + assert.deepEqual(f.views, [null], 'unchanged nothing is not re-published'); + f.panel._destroyStationPanel(); +}); + +test('selecting the station publishes it in Automatic with its defaults', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + const view = f.view(); + assert.equal(view.key, 'test'); + assert.equal(view.title, 'TEST'); + assert.equal(view.subject, 'TEST STATION'); + assert.equal(view.mode, 'automatic'); + assert.deepEqual(view.telemetry, { + state: 'live', + poseAgeMs: 3000, + liveUntilMs: null, + }); + assert.equal(view.sunlit, true); + assert.match(view.note, /Computed, not live telemetry/); + assert.deepEqual( + view.groups[0].choices.map((c) => [c.id, c.active]), + [ + ['follow', true], + ['ahead', false], + ], + ); + assert.deepEqual( + view.groups[1].sliders.map((s) => s.value), + [0, 0], + ); + assert.equal(view.groups[1].resume, 'Resume'); + assert.deepEqual(view.zoom, { offered: false, label: 'Zoom to the station' }); + assert.deepEqual(f.calls, [], 'Automatic touches nothing on entry'); +}); + +test('Manual pauses telemetry and offers the controls; Automatic hands the joints back', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + assert.equal(f.actions.setStationMode('manual'), true); + assert.equal(f.view().mode, 'manual'); + assert.equal(f.view().sunlit, null, "the Sun line is Automatic's"); + assert.deepEqual(f.calls, [['telemetry', false]]); + assert.equal(f.actions.setStationMode('manual'), true, 'again is a no-op'); + assert.equal(f.calls.length, 1); + assert.equal(f.actions.chooseStation('sun', 'ahead'), true); + assert.equal(f.view().groups[0].choices[1].active, true); + assert.equal(f.actions.setStationMode('automatic'), true); + assert.equal(f.view().mode, 'automatic'); + assert.deepEqual(f.calls.at(-1), ['automatic']); + assert.equal(f.view().groups[0].choices[0].active, true, 'choices reset'); +}); + +test('choices apply to the articulation; an unknown choice is refused', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + assert.equal(f.actions.chooseStation('sun', 'ahead'), true); + assert.deepEqual(f.calls, [['sun', 'ahead']]); + assert.equal(f.actions.chooseStation('sun', 'nowhere'), false); + assert.equal(f.actions.chooseStation('arm', 'ahead'), false); +}); + +test('sliders clamp to their range and refuse non-numbers', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + assert.equal(f.actions.slideStation('shoulder', '45'), true); + assert.equal(f.actions.slideStation('elbow', 500), true); + assert.equal(f.actions.slideStation('elbow', 'abc'), false); + assert.equal(f.actions.slideStation('wrist', 10), false); + assert.deepEqual(f.calls, [ + ['shoulder', 45], + ['elbow', 90], + ]); + assert.deepEqual( + f.view().groups[1].sliders.map((s) => s.value), + [45, 90], + ); + assert.equal(f.actions.resumeStationArm('arm'), true); + assert.deepEqual(f.calls.at(-1), ['resume']); + assert.deepEqual( + f.view().groups[1].sliders.map((s) => s.value), + [0, 0], + ); + assert.equal( + f.actions.resumeStationArm('sun'), + false, + 'choices have no resume', + ); +}); + +test('leaving the station in Manual hands its joints back and takes the section down', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + f.actions.setStationMode('manual'); + f.actions.slideStation('shoulder', 30); + f.select(false); + f.panel._syncStationPanel(); + assert.equal(f.view(), null); + assert.deepEqual(f.calls.at(-1), ['automatic']); + f.select(true); + f.panel._syncStationPanel(); + assert.equal(f.view().mode, 'automatic'); + assert.deepEqual( + f.view().groups[1].sliders.map((s) => s.value), + [0, 0], + ); +}); + +test('the section is away while the Cockpit holds the rail, and while the layer is off', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.hold(true); + f.panel._syncStationPanel(); + assert.equal(f.view(), null); + f.hold(false); + f.panel._syncStationPanel(); + assert.equal(f.view().key, 'test'); + f.layerState._enabled = false; + f.panel._syncStationPanel(); + assert.equal(f.view(), null); +}); + +test('every sync re-reads the telemetry status for the status line', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.panel._syncStationPanel(); + f.setTelemetry({ + state: 'unavailable', + poseAgeMs: 61_000, + liveUntilMs: null, + }); + f.panel._syncStationPanel(); + assert.equal(f.view().telemetry.state, 'unavailable'); +}); + +test('actions without a station are refused; destroy publishes nothing', () => { + const f = fixture(); + assert.equal(f.actions.setStationMode('manual'), false); + assert.equal(f.actions.chooseStation('sun', 'ahead'), false); + assert.equal(f.actions.slideStation('shoulder', 1), false); + assert.equal(f.actions.resumeStationArm('arm'), false); + assert.equal(f.actions.zoomStation(), false); + f.select(true); + f.panel._syncStationPanel(); + assert.ok(f.view()); + f.panel._destroyStationPanel(); + assert.equal(f.view(), null); +}); + +test('frame after frame, the section is republished only when the age crosses a whole second', (t) => { + const f = fixture(); + t.after(() => f.panel._destroyStationPanel()); + f.select(true); + f.setTelemetry({ state: 'live', poseAgeMs: 3010, liveUntilMs: null }); + f.panel._syncStationPanel(); + const published = f.views.length; + assert.equal(f.view().telemetry.poseAgeMs, 3000, 'in whole seconds'); + // The tick runs every frame; the age moves by milliseconds. + for (const age of [3020, 3150, 3600, 3999]) { + f.setTelemetry({ state: 'live', poseAgeMs: age, liveUntilMs: null }); + f.panel._syncStationPanel(); + } + assert.equal(f.views.length, published, 'nothing new to show'); + f.setTelemetry({ state: 'live', poseAgeMs: 4001, liveUntilMs: null }); + f.panel._syncStationPanel(); + assert.equal(f.views.length, published + 1); + assert.equal(f.view().telemetry.poseAgeMs, 4000); +}); diff --git a/src/layers/satellites/stationResume.test.mjs b/src/layers/satellites/stationResume.test.mjs new file mode 100644 index 0000000000..de2d96f471 --- /dev/null +++ b/src/layers/satellites/stationResume.test.mjs @@ -0,0 +1,97 @@ +// src/layers/satellites/stationResume.test.mjs — handing a station's moving +// parts back from the STATION section's Manual: every joint posed by hand +// leaves its manual angle, the ones the illustrative sway does not move +// included, and the ISS's Automatic lets telemetry back in. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createIssArticulation, ISS_ARM_JOINTS } from './issArticulation.js'; +import { issStationDescription } from './issStation.js'; +import { createNodePoses } from './stationModel.js'; +import { + createTiangongArticulation, + TIANGONG_ARMS, +} from './tiangongArticulation.js'; + +/** A station on its usual axes, in sunlight, as the model part places it. */ +const AT = { x: 6_780_000, y: 0, z: 0 }; +const AXES = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] }; +const DATE = new Date(Date.UTC(2026, 10, 16, 12, 0, 0)); + +test('ISS: Resume gives the Canadarm2 joints the sway does not move their filed pose back', () => { + const articulation = createIssArticulation(); + const nodes = createNodePoses(); + articulation.update(nodes, DATE, AT, AXES, 1_000); + const held = ISS_ARM_JOINTS.filter((joint) => !joint.sway); + const swaying = ISS_ARM_JOINTS.find((joint) => joint.sway); + assert.ok(held.length > 0 && swaying); + for (const joint of [...held, swaying]) + articulation.setJoint(joint.node, joint.pivot, joint.axis, Math.PI / 2); + for (const joint of held) assert.ok(nodes.poses[joint.node], joint.node); + articulation.resumeArm(); + for (const joint of held) + assert.equal( + nodes.poses[joint.node], + undefined, + `${joint.node} back to its filed pose`, + ); + // A swaying joint is posed by the sway again on the next update. + articulation.update(nodes, DATE, AT, AXES, 2_000); + assert.ok(nodes.poses[swaying.node]); +}); + +test('Tiangong: resuming an arm gives its held joints their folded pose back, and only that arm', () => { + const articulation = createTiangongArticulation(); + const nodes = createNodePoses(); + articulation.update(nodes, DATE, AT, AXES, 1_000); + const heldOf = (key) => + TIANGONG_ARMS[key].filter((joint) => !joint.sway && !joint.centre); + for (const key of ['cmm', 'emm']) + for (const joint of heldOf(key)) + articulation.setJoint(joint.node, joint.pivot, joint.axis, 1); + articulation.resumeArm('cmm'); + for (const joint of heldOf('cmm')) + assert.equal(nodes.poses[joint.node], undefined, joint.node); + for (const joint of heldOf('emm')) + assert.ok(nodes.poses[joint.node], `${joint.node} still by hand`); + articulation.resumeArm(); + for (const joint of heldOf('emm')) + assert.equal(nodes.poses[joint.node], undefined, joint.node); +}); + +test('a node given no matrix leaves the item’s nodes, as a model node goes back to its authored pose', () => { + const nodes = createNodePoses(); + const identity = new Float64Array(16); + identity[0] = identity[5] = identity[10] = identity[15] = 1; + nodes.getNode('JOINT').matrix = identity; + assert.ok(nodes.poses.JOINT); + nodes.getNode('JOINT').matrix = undefined; + assert.equal('JOINT' in nodes.poses, false); +}); + +test("the ISS's Automatic lets telemetry back in and hands every part back", () => { + const calls = []; + const recorder = new Proxy( + {}, + { + get: + (_, name) => + (...args) => + calls.push([name, ...args]), + }, + ); + const station = issStationDescription({ state: {}, parts: {} }); + station.automatic(recorder); + const names = calls.map(([name]) => name); + assert.deepEqual( + calls.find(([name]) => name === 'setTelemetryAllowed'), + ['setTelemetryAllowed', true], + ); + for (const name of [ + 'setOverride', + 'setDishOverride', + 'setDeploy', + 'setRadiatorDeploy', + 'resumeArm', + ]) + assert.ok(names.includes(name), name); +}); diff --git a/src/layers/satellites/tiangongArticulation.js b/src/layers/satellites/tiangongArticulation.js new file mode 100644 index 0000000000..d1fb79fc0a --- /dev/null +++ b/src/layers/satellites/tiangongArticulation.js @@ -0,0 +1,484 @@ +import { sunPositionFixed } from '../../geo/celestial.js'; +import { + ISS_JOINT_RATE, + issAimMatrix, + issArmAngles, + issAxisMatrix, + issInShadow, + issRelayDirections, + issStepAngle, + issStepDirection, + issSunInModelFrame, +} from './issArticulation.js'; +import { tiangongJoint } from './tiangongJoints.js'; + +/** + * Tiangong's moving parts, driven from the joint table (tiangongJoints.js): + * every angle is computed, since China publishes no live telemetry for the + * station. The rules are the ISS's (issArticulation.js), written for joints + * whose axes and rest normals come from the table instead of being fixed: + * + * - a wing on one joint (Tianhe's two, each visiting vehicle's two) turns + * about its boom so its cell side faces the Sun; + * - a lab wing (Wentian's and Mengtian's two each) turns first about the + * lab's axis (alpha), so the wing's own axis is across the Sun, then about + * that axis (beta), so the cells face it, the ISS's SARJ/BGA pair; + * - in the Earth's shadow the wings turn flat to the Earth (cell side to + * zenith), which puts them edge-on to the flight direction, the ISS's + * feathering; + * - the high-gain antenna aims at the highest of China's Tianlian relay + * satellites over the equator; + * - the two arms sway slowly for illustration (their real pose is not public). + * + * Joints turn at most ISS_JOINT_RATE on screen. + */ + +/** Below this the Sun is too close to a joint's axis to steer by it. */ +const MIN_STEER = 0.05; +/** The dish does not look below this much above the station's horizon plane. */ +const DISH_MIN_UP = 0.15; +/** Where the wings turn in shadow: cell side to zenith, on the model's axes. */ +const ZENITH = Object.freeze([0, 1, 0]); + +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a, b) => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; + +/** `v` turned by `angle` about the unit vector `axis` (Rodrigues). */ +function rotate(v, axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const k = cross(axis, v); + const d = dot(axis, v) * (1 - c); + return [0, 1, 2].map((i) => v[i] * c + k[i] * s + axis[i] * d); +} + +/** The signed difference wrapped to (-π, π]. */ +function wrap(delta) { + let d = delta % (2 * Math.PI); + if (d > Math.PI) d -= 2 * Math.PI; + if (d <= -Math.PI) d += 2 * Math.PI; + return d; +} + +/** Of `angle` and `angle + π`, the one nearer to `previous`. */ +function nearestHalfTurn(angle, previous) { + const flipped = angle + Math.PI; + return Math.abs(wrap(angle - previous)) <= Math.abs(wrap(flipped - previous)) + ? angle + : flipped; +} + +const wing = (node, normal) => + Object.freeze({ ...tiangongJoint(node), normal: Object.freeze(normal) }); + +/** + * Wings turned by one joint, with the cell side's normal at rest. The + * station's and the forward and aft vehicles' wings lie flat (cells up); the + * nadir Shenzhou hangs below the node, so its wings' cells face forward. + */ +export const TIANGONG_ONE_AXIS_WINGS = Object.freeze([ + wing('TIANHE_ARRAY_PORT_ALPHA', ZENITH), + wing('TIANHE_ARRAY_STBD_ALPHA', ZENITH), + wing('SHENZHOU_FORWARD_ARRAY_PORT_ALPHA', ZENITH), + wing('SHENZHOU_FORWARD_ARRAY_STBD_ALPHA', ZENITH), + wing('SHENZHOU_NADIR_ARRAY_PORT_ALPHA', [0, 0, 1]), + wing('SHENZHOU_NADIR_ARRAY_STBD_ALPHA', [0, 0, 1]), + wing('TIANZHOU_AFT_ARRAY_PORT_ALPHA', ZENITH), + wing('TIANZHOU_AFT_ARRAY_STBD_ALPHA', ZENITH), +]); + +/** The lab wings: an alpha joint about the lab's axis, a beta joint under it. */ +export const TIANGONG_TWO_AXIS_WINGS = Object.freeze( + [ + 'WENTIAN_ARRAY_FWD', + 'WENTIAN_ARRAY_AFT', + 'MENGTIAN_ARRAY_FWD', + 'MENGTIAN_ARRAY_AFT', + ].map((stem) => + Object.freeze({ + alpha: tiangongJoint(`${stem}_ALPHA`), + beta: tiangongJoint(`${stem}_BETA`), + normal: ZENITH, + }), + ), +); + +/** + * The arms' joints, base to tip, with the illustrative sway: `centre` and + * `sway` radians over `period` seconds, about the folded pose in the file. + * The joints that lift the booms sway on one side of rest only, so the arms + * rise off the hull and never swing into it. + */ +const arm = (prefix, sway) => + Object.freeze( + ['SHR', 'SHY', 'SHP', 'EP', 'WP', 'WY', 'WR'].map((name) => { + const [centreDeg = 0, swayDeg = 0, period = 0] = sway[name] ?? []; + return Object.freeze({ + ...tiangongJoint(`${prefix}_${name}`), + centre: (centreDeg * Math.PI) / 180, + sway: (swayDeg * Math.PI) / 180, + period, + }); + }), + ); + +export const TIANGONG_ARMS = Object.freeze({ + /** The Tianhe arm (CMM), its booms folded along the core module. */ + cmm: arm('CMM', { SHP: [12, 6, 71], EP: [-14, 8, 53], WP: [0, 5, 41] }), + /** The Wentian arm (EMM), folded along the lab. */ + emm: arm('EMM', { SHP: [-12, 6, 67], EP: [14, 8, 47], WP: [0, 5, 37] }), +}); + +/** The high-gain antenna's gimbal; rest boresight +Y. */ +export const TIANGONG_HGA = tiangongJoint('TIANHE_HGA'); + +/** + * China's Tianlian II relay satellites over the equator, degrees east, the + * station's counterparts to NASA's TDRS: II-01 at 79.9°E, II-02 at 171.04°E, + * II-03 at 10.5°E (Wikipedia, "Tianlian", and satcat.com's definitive orbit + * for 53100 at 10.56°E; II-03's slot is not stated by the launch reports, which + * say only that the three form a global network). Nominal slots, not a live + * roster: which satellite the station uses at a given moment is not public. + */ +export const TIANGONG_RELAY_LONGITUDES_DEG = Object.freeze([ + 79.9, 171.04, 10.5, +]); + +/** + * The angle that turns a wing's cell side onto the Sun about one axis. + * @param {number[]} sun Unit vector on the model's axes. + * @param {{axis: readonly number[], normal: readonly number[]}} joint The + * turn axis and the cell side's normal at rest (perpendicular to it). + * @param {number} [previous] Held when the Sun is along the axis. + * @returns {number} Radians. + */ +export function tiangongOneAxisAngle(sun, { axis, normal }, previous = 0) { + const across = cross(axis, normal); + const u = dot(sun, normal); + const v = dot(sun, across); + if (Math.hypot(u, v) < MIN_STEER) return previous; + return Math.atan2(v, u); +} + +/** + * The two angles that face a lab wing to the Sun: `alpha` about the lab's + * axis puts the wing's own axis across the Sun, `beta` about that axis turns + * the cell side onto it. + * @param {number[]} sun Unit vector on the model's axes. + * @param {{alphaAxis: readonly number[], betaAxis: readonly number[], + * normal: readonly number[]}} joint Axes at rest; the normal is + * perpendicular to both. + * @param {number} [previousAlpha] Alpha has two answers half a turn apart + * (beta makes up the difference); the nearer to this is kept, and it is + * held when the Sun is along the alpha axis. + * @returns {{alpha: number, beta: number}} Radians. + */ +export function tiangongTwoAxisAngles( + sun, + { alphaAxis, betaAxis, normal }, + previousAlpha = 0, +) { + const across = cross(alphaAxis, betaAxis); + const u = dot(sun, betaAxis); + const v = dot(sun, across); + const alpha = + Math.hypot(u, v) < MIN_STEER + ? previousAlpha + : nearestHalfTurn(Math.atan2(-u, v), previousAlpha); + // The Sun as the wing sees it after the alpha turn. + const local = rotate(sun, alphaAxis, -alpha); + const beta = Math.atan2( + dot(local, cross(betaAxis, normal)), + dot(local, normal), + ); + return { alpha, beta }; +} + +/** + * Every wing's target angles. + * @param {number[]} sun Unit vector toward the Sun on the model's axes. + * @param {boolean} sunlit False in the Earth's shadow: the wings turn flat. + * @param {{one: number[], alpha: number[]}} [previous] The last targets. + * @returns {{one: number[], alpha: number[], beta: number[]}} Radians, per + * TIANGONG_ONE_AXIS_WINGS and TIANGONG_TWO_AXIS_WINGS entry. + */ +export function tiangongWingTargets(sun, sunlit, previous = null) { + const toward = sunlit ? sun : ZENITH; + const one = TIANGONG_ONE_AXIS_WINGS.map((joint, i) => + tiangongOneAxisAngle(toward, joint, previous?.one[i] ?? 0), + ); + const two = TIANGONG_TWO_AXIS_WINGS.map((pair, i) => + tiangongTwoAxisAngles( + toward, + { + alphaAxis: pair.alpha.axis, + betaAxis: pair.beta.axis, + normal: pair.normal, + }, + previous?.alpha[i] ?? 0, + ), + ); + return { + one, + alpha: two.map((t) => t.alpha), + beta: two.map((t) => t.beta), + }; +} + +/** + * Where the Tianlian satellites are from the station, on the model's axes, + * the highest above the station first. + * @param {number[]} positionEcef Meters. + * @param {{x:number[], y:number[], z:number[]}} axes Flight axes. + * @returns {number[][]} Unit vectors [port, zenith, forward]. + */ +export function tiangongRelayDirections(positionEcef, axes) { + return issRelayDirections(positionEcef, axes, TIANGONG_RELAY_LONGITUDES_DEG); +} + +/** + * Drives the loaded model's joints. Same contract as the ISS driver + * (`update`, `reset`, the STATION section's `setOverride`, `setJoint`, + * `resumeArm`, `isSunlit`), minus telemetry: `isLive` is always false. + */ +export function createTiangongArticulation() { + let boundModel = null; + let nodes = null; + let angles = null; + let targets = null; + let lastMs = 0; + let override = null; + let lastSunlit = null; + /** Where the dish looks now, on the model's axes. */ + let dish = null; + /** STATION section: arms being posed by hand, so their sway is off. */ + const armManual = new Set(); + /** + * STATION section: wings set by hand, node name → radians. A wing with an + * entry here holds that angle (reached at the joint rate) instead of + * following the Sun; the others keep following. + */ + const wingManual = new Map(); + const scratchMatrix = new Float64Array(16); + + function bind(model) { + boundModel = model; + const get = (joint) => model.getNode(joint.node) ?? null; + nodes = { + one: TIANGONG_ONE_AXIS_WINGS.map(get), + alpha: TIANGONG_TWO_AXIS_WINGS.map((pair) => get(pair.alpha)), + beta: TIANGONG_TWO_AXIS_WINGS.map((pair) => get(pair.beta)), + dish: get(TIANGONG_HGA), + arms: Object.fromEntries( + Object.entries(TIANGONG_ARMS).map(([key, joints]) => [ + key, + joints.map(get), + ]), + ), + }; + angles = null; + dish = null; + } + + function sunEcef(date) { + const sun = sunPositionFixed(date.getTime()); + const length = Math.hypot(sun.x, sun.y, sun.z) || 1; + return [sun.x / length, sun.y / length, sun.z / length]; + } + + function write(node, joint, angle) { + if (!node) return; + node.matrix = issAxisMatrix(joint.pivot, joint.axis, angle, scratchMatrix); + } + + /** + * @param {{ready: boolean, getNode: (name: string) => object|undefined}} model + * A ready model, or any holder of nodes that take a `matrix`. + * @param {Date} date The instant the model is placed at. + * @param {{x:number,y:number,z:number}} position Earth-fixed station position. + * @param {{x:number[], y:number[], z:number[]}} axes Its flight axes. + * @param {number} [nowMs] Wall clock, for the turn rate. + */ + function update(model, date, position, axes, nowMs = Date.now()) { + if (!model.ready) return; + if (model !== boundModel) bind(model); + const forced = override?.(nowMs) ?? null; + if (forced) { + lastSunlit = Boolean(forced.sunlit); + targets = tiangongWingTargets(forced.sun, forced.sunlit, targets); + } else { + const sun = sunEcef(date); + const sunlit = !issInShadow([position.x, position.y, position.z], sun); + lastSunlit = sunlit; + targets = tiangongWingTargets( + issSunInModelFrame(sun, axes), + sunlit, + targets, + ); + } + // A first frame, or one after a pause, goes straight to the pose. + const elapsed = (nowMs - lastMs) / 1000; + lastMs = nowMs; + const maxStep = + !angles || !(elapsed >= 0) || elapsed > 2 + ? Number.POSITIVE_INFINITY + : ISS_JOINT_RATE * elapsed; + // A wing set by hand aims for its set angle; the rest for the Sun's. + const goalFor = (group, joints) => + targets[group].map((target, i) => + wingManual.has(joints[i].node) + ? wingManual.get(joints[i].node) + : target, + ); + const goals = { + one: goalFor('one', TIANGONG_ONE_AXIS_WINGS), + alpha: goalFor( + 'alpha', + TIANGONG_TWO_AXIS_WINGS.map((pair) => pair.alpha), + ), + beta: goalFor( + 'beta', + TIANGONG_TWO_AXIS_WINGS.map((pair) => pair.beta), + ), + }; + const step = (group) => + goals[group].map((target, i) => + issStepAngle(angles?.[group][i] ?? 0, target, maxStep), + ); + const next = { one: step('one'), alpha: step('alpha'), beta: step('beta') }; + TIANGONG_ONE_AXIS_WINGS.forEach((joint, i) => { + if (!angles || next.one[i] !== angles.one[i]) + write(nodes.one[i], joint, next.one[i]); + }); + TIANGONG_TWO_AXIS_WINGS.forEach((pair, i) => { + if (!angles || next.alpha[i] !== angles.alpha[i]) + write(nodes.alpha[i], pair.alpha, next.alpha[i]); + if (!angles || next.beta[i] !== angles.beta[i]) + write(nodes.beta[i], pair.beta, next.beta[i]); + }); + angles = next; + + // The dish: the highest relay satellite; one below the station's horizon + // plane keeps its last aim. + const current = dish ?? [0, 1, 0]; + const wanted = tiangongRelayDirections( + [position.x, position.y, position.z], + axes, + )[0]; + const target = wanted && wanted[1] >= DISH_MIN_UP ? wanted : current; + const stepped = issStepDirection(current, target, maxStep); + if (!dish || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9)) + if (nodes.dish) + nodes.dish.matrix = issAimMatrix( + TIANGONG_HGA.pivot, + stepped, + scratchMatrix, + ); + dish = stepped; + + // Arms: an illustrative sway about the folded pose (see TIANGONG_ARMS). + for (const [key, joints] of Object.entries(TIANGONG_ARMS)) { + if (armManual.has(key)) continue; + const sway = issArmAngles(nowMs / 1000, joints); + joints.forEach((joint, i) => { + if (!joint.sway && !joint.centre) return; + write(nodes.arms[key][i], joint, joint.centre + sway[i]); + }); + } + } + + /** + * STATION section: turn any named node about an axis through a pivot. A + * node of either arm takes that arm off its sway. + * @param {string} name + * @param {number[]} pivot + * @param {number[]} axis Unit vector. + * @param {number} angle Radians. + */ + function setJoint(name, pivot, axis, angle) { + for (const [key, joints] of Object.entries(TIANGONG_ARMS)) + if (joints.some((joint) => joint.node === name)) armManual.add(key); + const node = boundModel?.getNode(name); + if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix); + } + + /** Forget the model and every manual choice: the next update starts clean. */ + function reset() { + boundModel = null; + nodes = null; + angles = null; + targets = null; + dish = null; + override = null; + wingManual.clear(); + armManual.clear(); + } + + /** + * STATION section: a function giving the Sun on the model's axes (and + * whether the station is lit) in place of the real one, or null for the + * real one. + * @param {((nowMs:number)=>{sun:number[], sunlit:boolean}|null)|null} fn + */ + function setOverride(fn) { + override = fn; + } + + /** Whether the station is in sunlight, as of the last update. */ + function isSunlit() { + return lastSunlit; + } + + /** + * STATION section: hand an arm back to its sway; both when no arm is named. + * @param {'cmm'|'emm'} [key] + */ + function resumeArm(key) { + for (const arm of key ? [key] : [...armManual]) { + if (!armManual.delete(arm)) continue; + // Joints the sway does not move would keep their manual angle: they go + // back to the folded pose. The swaying ones are posed again next update. + for (const joint of TIANGONG_ARMS[arm] ?? []) { + if (joint.sway || joint.centre) continue; + const node = boundModel?.getNode(joint.node); + if (node) node.matrix = undefined; + } + } + } + + /** + * STATION section: hold one wing joint at an angle, by its node name + * (a TIANGONG_ONE_AXIS_WINGS entry, or a lab wing's alpha or beta node). + * The joint turns there at the joint rate on the next updates. Null lets + * the wing follow the Sun again. + * @param {string} name + * @param {number|null} angle Radians. + */ + function setWingAngle(name, angle) { + if (angle === null || !Number.isFinite(angle)) wingManual.delete(name); + else wingManual.set(name, angle); + } + + /** STATION section: every wing back to the Sun. */ + function resumeWings() { + wingManual.clear(); + } + + return { + update, + reset, + setOverride, + setJoint, + resumeArm, + setWingAngle, + resumeWings, + isSunlit, + /** No telemetry exists for Tiangong: the angles are always computed. */ + isLive: () => false, + setTelemetryAllowed() {}, + }; +} diff --git a/src/layers/satellites/tiangongArticulation.test.mjs b/src/layers/satellites/tiangongArticulation.test.mjs new file mode 100644 index 0000000000..88d776aee0 --- /dev/null +++ b/src/layers/satellites/tiangongArticulation.test.mjs @@ -0,0 +1,238 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import { ISS_RELAY_LONGITUDES_DEG } from './issArticulation.js'; +import { TIANGONG_MODEL_URL } from './policy.js'; +import { + TIANGONG_ARMS, + TIANGONG_HGA, + TIANGONG_ONE_AXIS_WINGS, + TIANGONG_RELAY_LONGITUDES_DEG, + TIANGONG_TWO_AXIS_WINGS, + tiangongOneAxisAngle, + tiangongRelayDirections, + tiangongTwoAxisAngles, + tiangongWingTargets, +} from './tiangongArticulation.js'; +import { TIANGONG_JOINTS, tiangongJoint } from './tiangongJoints.js'; + +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a, b) => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +const unit = (v) => v.map((c) => c / Math.hypot(...v)); +/** `v` turned by `angle` about `axis` (Rodrigues), the turn the matrix makes. */ +const rotate = (v, axis, angle) => { + const c = Math.cos(angle); + const s = Math.sin(angle); + const k = cross(axis, v); + const d = dot(axis, v) * (1 - c); + return [0, 1, 2].map((i) => v[i] * c + k[i] * s + axis[i] * d); +}; + +const SUNS = [ + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [1, 0, 0], + [0.5, 0.5, 0.7], + [-0.6, 0.2, -0.77], + [0.3, -0.9, 0.3], + [0.9, 0.1, -0.4], +].map(unit); + +test("the joint table is the model build's: 37 nodes, every kind, frozen", () => { + assert.equal(TIANGONG_JOINTS.length, 37); + const kinds = new Map(); + for (const joint of TIANGONG_JOINTS) { + kinds.set(joint.kind, (kinds.get(joint.kind) ?? 0) + 1); + assert.ok(Object.isFrozen(joint) && Object.isFrozen(joint.pivot)); + assert.equal(joint.pivot.length, 3); + assert.ok(Math.abs(Math.hypot(...joint.axis) - 1) < 1e-9, joint.node); + if (joint.kind === 'dock') assert.equal(joint.rangeDeg, null); + else assert.equal(joint.rangeDeg.length, 2); + } + // 2 Tianhe wings, 4 lab wings and 6 vehicle wings turn on alpha joints. + assert.deepEqual(Object.fromEntries(kinds), { + alpha: 12, + beta: 4, + antenna: 1, + dock: 6, + arm: 14, + }); + assert.equal(tiangongJoint('CMM_EP').parent, 'CMM_SHP'); + assert.throws(() => tiangongJoint('NOT_A_JOINT')); +}); + +test('a one-axis wing turns its cell side onto the Sun, as far as its axis allows', () => { + for (const wing of TIANGONG_ONE_AXIS_WINGS) { + assert.ok(Math.abs(dot(wing.axis, wing.normal)) < 1e-9, wing.node); + for (const sun of SUNS) { + const angle = tiangongOneAxisAngle(sun, wing); + const normal = rotate(wing.normal, wing.axis, angle); + // The best the wing can do: the Sun's part across its axis. + const reachable = Math.hypot( + dot(sun, wing.normal), + dot(sun, cross(wing.axis, wing.normal)), + ); + if (reachable < 0.05) continue; + assert.ok( + Math.abs(dot(normal, sun) - reachable) < 1e-6, + `${wing.node} ${sun}`, + ); + } + } + // The Sun along the axis: nothing to steer by, the last angle holds. + const tianhe = TIANGONG_ONE_AXIS_WINGS[0]; + assert.equal(tiangongOneAxisAngle([1, 0, 0], tianhe, 0.7), 0.7); +}); + +test('a lab wing faces the Sun exactly: alpha across it, beta onto it', () => { + for (const pair of TIANGONG_TWO_AXIS_WINGS) { + const joint = { + alphaAxis: pair.alpha.axis, + betaAxis: pair.beta.axis, + normal: pair.normal, + }; + for (const sun of SUNS) { + if (Math.abs(dot(sun, pair.alpha.axis)) > 0.95) continue; + const { alpha, beta } = tiangongTwoAxisAngles(sun, joint); + // The beta joint hangs from the alpha joint: beta turns first. + const normal = rotate( + rotate(pair.normal, pair.beta.axis, beta), + pair.alpha.axis, + alpha, + ); + assert.ok(dot(normal, sun) > 1 - 1e-6, `${pair.alpha.node} ${sun}`); + const wingAxis = rotate(pair.beta.axis, pair.alpha.axis, alpha); + assert.ok( + Math.abs(dot(wingAxis, sun)) < 1e-6, + 'wing axis across the Sun', + ); + } + // Alpha keeps the half turn nearer its last answer. + const first = tiangongTwoAxisAngles(unit([0.2, 1, 0.3]), joint, 0); + const flipped = tiangongTwoAxisAngles( + unit([0.2, 1, 0.3]), + joint, + first.alpha + Math.PI, + ); + assert.ok(Math.abs(Math.abs(flipped.alpha - first.alpha) - Math.PI) < 1e-9); + // Sun along the lab: alpha holds. + assert.equal(tiangongTwoAxisAngles([1, 0, 0], joint, 0.4).alpha, 0.4); + } +}); + +test("in the Earth's shadow every wing turns flat to the Earth, edge into the flight", () => { + const targets = tiangongWingTargets(unit([0.3, -0.9, 0.3]), false, { + one: TIANGONG_ONE_AXIS_WINGS.map(() => 3), + alpha: TIANGONG_TWO_AXIS_WINGS.map(() => 3), + }); + TIANGONG_ONE_AXIS_WINGS.forEach((wing, i) => { + const normal = rotate(wing.normal, wing.axis, targets.one[i]); + assert.ok(Math.abs(normal[1] - 1) < 1e-9, wing.node); + }); + TIANGONG_TWO_AXIS_WINGS.forEach((pair, i) => { + // The nearer half turn to 3 rad is ±π, with beta making up the rest. + assert.ok(Math.abs(Math.cos(targets.alpha[i]) + 1) < 1e-9, pair.alpha.node); + const normal = rotate( + rotate(pair.normal, pair.beta.axis, targets.beta[i]), + pair.alpha.axis, + targets.alpha[i], + ); + assert.ok(Math.abs(normal[1] - 1) < 1e-9); + }); + // Lit, the targets face the Sun instead. + const lit = tiangongWingTargets([0, 0, 1], true); + assert.ok(Math.abs(Math.abs(lit.one[0]) - Math.PI / 2) < 1e-9); +}); + +test('the antenna aims at Tianlian, not TDRS: unit vectors, highest first', () => { + assert.deepEqual([...TIANGONG_RELAY_LONGITUDES_DEG], [79.9, 171.04, 10.5]); + assert.notDeepEqual( + [...TIANGONG_RELAY_LONGITUDES_DEG], + [...ISS_RELAY_LONGITUDES_DEG], + ); + // Over 80°E at 400 km: Tianlian II-01 is nearly overhead. + const lon = (79.9 * Math.PI) / 180; + const r = 6_771_000; + const position = [r * Math.cos(lon), r * Math.sin(lon), 0]; + const axes = { + x: [-Math.sin(lon), Math.cos(lon), 0], + y: [0, 0, 1], + z: unit(position), + }; + const directions = tiangongRelayDirections(position, axes); + assert.equal(directions.length, 3); + for (const d of directions) assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-9); + assert.ok(directions[0][1] > 0.999, 'II-01 overhead'); + assert.ok( + directions[0][1] >= directions[1][1] && + directions[1][1] >= directions[2][1], + ); + assert.deepEqual(TIANGONG_HGA.axis, [0, 1, 0]); +}); + +test('the arms sway on one side of rest only, so they lift off the hull', () => { + for (const joints of Object.values(TIANGONG_ARMS)) { + assert.equal(joints.length, 7); + for (const joint of joints) { + if (!joint.sway) { + assert.equal(joint.centre, 0); + continue; + } + // The sway never crosses rest unless it is centred on it (wrist pitch). + assert.ok( + joint.centre === 0 || Math.abs(joint.centre) > joint.sway, + joint.node, + ); + assert.ok(joint.period > 0); + } + } +}); + +test('the model file has every joint node, under its parent, with an identity rest', () => { + const glb = readFileSync( + new URL(`../../../public${TIANGONG_MODEL_URL}`, import.meta.url), + ); + const jsonLength = glb.readUInt32LE(12); + const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8')); + const byName = new Map(gltf.nodes.map((node, index) => [node.name, index])); + const parentOf = new Map(); + gltf.nodes.forEach((node, index) => + (node.children ?? []).forEach((child) => parentOf.set(child, index)), + ); + for (const joint of TIANGONG_JOINTS) { + const index = byName.get(joint.node); + assert.ok(index !== undefined, joint.node); + const node = gltf.nodes[index]; + assert.equal( + gltf.nodes[parentOf.get(index)].name, + joint.parent, + joint.node, + ); + if (joint.kind !== 'dock') { + assert.equal(node.translation ?? null, null, joint.node); + assert.equal(node.rotation ?? null, null, joint.node); + assert.equal(node.matrix ?? null, null, joint.node); + } + } + // Each wing's mesh is thin along the cell normal the rules assume. + const thin = (meshNode, normal) => { + const node = gltf.nodes[byName.get(meshNode)]; + const accessor = + gltf.accessors[gltf.meshes[node.mesh].primitives[0].attributes.POSITION]; + const size = [0, 1, 2].map((i) => accessor.max[i] - accessor.min[i]); + const along = normal.findIndex((c) => c !== 0); + assert.ok( + size[along] < Math.min(...size.filter((_, i) => i !== along)) / 3, + meshNode, + ); + }; + for (const wing of TIANGONG_ONE_AXIS_WINGS) + thin(wing.node.replace(/_ALPHA$/, ''), wing.normal); + for (const pair of TIANGONG_TWO_AXIS_WINGS) + thin(pair.beta.node.replace(/_BETA$/, ''), pair.normal); +}); diff --git a/src/layers/satellites/tiangongJoints.js b/src/layers/satellites/tiangongJoints.js new file mode 100644 index 0000000000..bd0b832493 --- /dev/null +++ b/src/layers/satellites/tiangongJoints.js @@ -0,0 +1,280 @@ +/** + * Tiangong's joint and dock-marker nodes, as the model file carries them in + * each node's glTF `extras` (the model build's joints.json, copied here; the + * app reads this table, never the file's extras). Root frame, meters: glTF +X + * port, +Y zenith, +Z forward. Every driven joint is a node with an identity + * rest transform whose moving mesh hangs beneath it, so a turn of `angle` about + * `axis` through `pivot` is `issAxisMatrix(pivot, axis, angle)`, as for the ISS. + * `kind`: alpha (a wing's drive about its boom), beta (a lab wing's turn about + * its own axis, under its alpha), arm (the two robotic arms, seven joints + * each, base to tip), antenna (the high-gain dish, rest boresight +Y), dock (a + * docking port's outer face, not driven: `axis` is a docked vehicle's + * direction, `rangeDeg` null). `approximate` marks the model author's + * estimates against published dimensions. + * @type {ReadonlyArray>} + */ +export const TIANGONG_JOINTS = Object.freeze( + [ + [ + 'TIANHE_ARRAY_PORT_ALPHA', + [1.4, 0, -6.7], + [1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'TIANHE_ARRAY_STBD_ALPHA', + [-1.4, 0, -6.7], + [-1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'TIANHE_HGA', + [0, 2.4, -6], + [0, 1, 0], + 'antenna', + [-90, 90], + true, + 'tiangong', + ], + ['DOCK_FORWARD', [0, 0, 8.3], [0, 0, 1], 'dock', null, false, 'tiangong'], + ['DOCK_AFT', [0, 0, -8.3], [0, 0, -1], 'dock', null, false, 'tiangong'], + ['DOCK_NADIR', [0, -2, 6.4], [0, -1, 0], 'dock', null, true, 'tiangong'], + ['DOCK_ZENITH', [0, 2, 6.4], [0, 1, 0], 'dock', null, true, 'tiangong'], + ['BERTH_PORT', [2.1, 0, 6.4], [1, 0, 0], 'dock', null, true, 'tiangong'], + ['BERTH_STBD', [-2.1, 0, 6.4], [-1, 0, 0], 'dock', null, true, 'tiangong'], + [ + 'WENTIAN_ARRAY_FWD_ALPHA', + [-18.9, 0, 6.9], + [-1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'WENTIAN_ARRAY_FWD_BETA', + [-18.9, 0, 7.7], + [0, 0, 1], + 'beta', + [-180, 180], + false, + 'WENTIAN_ARRAY_FWD_ALPHA', + ], + [ + 'WENTIAN_ARRAY_AFT_ALPHA', + [-18.9, 0, 5.9], + [-1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'WENTIAN_ARRAY_AFT_BETA', + [-18.9, 0, 5.1], + [0, 0, -1], + 'beta', + [-180, 180], + false, + 'WENTIAN_ARRAY_AFT_ALPHA', + ], + [ + 'MENGTIAN_ARRAY_FWD_ALPHA', + [18.9, 0, 6.9], + [1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'MENGTIAN_ARRAY_FWD_BETA', + [18.9, 0, 7.7], + [0, 0, 1], + 'beta', + [-180, 180], + false, + 'MENGTIAN_ARRAY_FWD_ALPHA', + ], + [ + 'MENGTIAN_ARRAY_AFT_ALPHA', + [18.9, 0, 5.9], + [1, 0, 0], + 'alpha', + [-180, 180], + false, + 'tiangong', + ], + [ + 'MENGTIAN_ARRAY_AFT_BETA', + [18.9, 0, 5.1], + [0, 0, -1], + 'beta', + [-180, 180], + false, + 'MENGTIAN_ARRAY_AFT_ALPHA', + ], + [ + 'CMM_SHR', + [0.5, 1.9, 3.6], + [0, 1, 0], + 'arm', + [-270, 270], + true, + 'tiangong', + ], + [ + 'CMM_SHY', + [0.5, 2.3, 3.6], + [0, 0, 1], + 'arm', + [-270, 270], + true, + 'CMM_SHR', + ], + [ + 'CMM_SHP', + [0.5, 2.7, 3.6], + [1, 0, 0], + 'arm', + [-270, 270], + true, + 'CMM_SHY', + ], + [ + 'CMM_EP', + [0.5, 2.7, -0.9], + [1, 0, 0], + 'arm', + [-270, 270], + true, + 'CMM_SHP', + ], + ['CMM_WP', [0.5, 3.3, 3.6], [1, 0, 0], 'arm', [-270, 270], true, 'CMM_EP'], + ['CMM_WY', [0.5, 3.3, 4.1], [0, 1, 0], 'arm', [-270, 270], true, 'CMM_WP'], + ['CMM_WR', [0.5, 3.3, 4.6], [0, 0, 1], 'arm', [-270, 270], true, 'CMM_WY'], + [ + 'EMM_SHR', + [-6, 2.3, 6.4], + [0, 1, 0], + 'arm', + [-270, 270], + true, + 'tiangong', + ], + [ + 'EMM_SHY', + [-6, 2.55, 6.4], + [1, 0, 0], + 'arm', + [-270, 270], + true, + 'EMM_SHR', + ], + [ + 'EMM_SHP', + [-6, 2.85, 6.4], + [0, 0, 1], + 'arm', + [-270, 270], + true, + 'EMM_SHY', + ], + ['EMM_EP', [-8, 2.85, 6.4], [0, 0, 1], 'arm', [-270, 270], true, 'EMM_SHP'], + ['EMM_WP', [-6, 3.2, 6.4], [0, 0, 1], 'arm', [-270, 270], true, 'EMM_EP'], + ['EMM_WY', [-5.7, 3.2, 6.4], [0, 1, 0], 'arm', [-270, 270], true, 'EMM_WP'], + ['EMM_WR', [-5.4, 3.2, 6.4], [1, 0, 0], 'arm', [-270, 270], true, 'EMM_WY'], + [ + 'SHENZHOU_FORWARD_ARRAY_PORT_ALPHA', + [1.4, 0, 15.1], + [1, 0, 0], + 'alpha', + [-180, 180], + true, + 'SHENZHOU_FORWARD', + ], + [ + 'SHENZHOU_FORWARD_ARRAY_STBD_ALPHA', + [-1.4, 0, 15.1], + [-1, -0, -0], + 'alpha', + [-180, 180], + true, + 'SHENZHOU_FORWARD', + ], + [ + 'SHENZHOU_NADIR_ARRAY_PORT_ALPHA', + [1.4, -8.8, 6.4], + [1, 0, 0], + 'alpha', + [-180, 180], + true, + 'SHENZHOU_NADIR', + ], + [ + 'SHENZHOU_NADIR_ARRAY_STBD_ALPHA', + [-1.4, -8.8, 6.4], + [-1, -0, -0], + 'alpha', + [-180, 180], + true, + 'SHENZHOU_NADIR', + ], + [ + 'TIANZHOU_AFT_ARRAY_PORT_ALPHA', + [1.4, 0, -16.6], + [1, 0, 0], + 'alpha', + [-180, 180], + true, + 'TIANZHOU_AFT', + ], + [ + 'TIANZHOU_AFT_ARRAY_STBD_ALPHA', + [-1.4, 0, -16.6], + [-1, -0, -0], + 'alpha', + [-180, 180], + true, + 'TIANZHOU_AFT', + ], + ].map(([node, pivot, axis, kind, rangeDeg, approximate, parent]) => + Object.freeze({ + node, + pivot: Object.freeze(pivot), + axis: Object.freeze(axis), + kind, + rangeDeg: rangeDeg && Object.freeze(rangeDeg), + approximate, + parent, + }), + ), +); + +const BY_NODE = new Map(TIANGONG_JOINTS.map((joint) => [joint.node, joint])); + +/** + * One joint by node name. + * @param {string} node + * @returns {(typeof TIANGONG_JOINTS)[number]} + */ +export function tiangongJoint(node) { + const joint = BY_NODE.get(node); + if (!joint) throw new Error(`Tiangong has no joint ${node}`); + return joint; +} + +/** The visiting vehicles' mesh nodes; hiding one hides its arrays with it. */ +export const TIANGONG_VEHICLE_NODES = Object.freeze([ + 'SHENZHOU_FORWARD', + 'SHENZHOU_NADIR', + 'TIANZHOU_AFT', +]); diff --git a/src/layers/satellites/tiangongModel.js b/src/layers/satellites/tiangongModel.js new file mode 100644 index 0000000000..57713260e5 --- /dev/null +++ b/src/layers/satellites/tiangongModel.js @@ -0,0 +1,74 @@ +import { + ISS_COMPANION_COARSE_M, + ISS_COMPANION_RADIUS_M, + ISS_COMPANION_SCAN_MS, + ISS_MODEL_LOCAL_AXES, + ISS_MODEL_MAX_DISTANCE_M, + ISS_MODEL_MIN_PX, + ISS_ORBIT_HIDE_M, + TIANGONG_CARD_CLEAR_M, + TIANGONG_MODEL_URL, + TIANGONG_NORAD, +} from './policy.js'; +import { createStationModel } from './stationModel.js'; +import { createTiangongArticulation } from './tiangongArticulation.js'; +import { tiangongCockpitMount } from './tiangongMounts.js'; + +/** + * Whether a catalog entry at Tiangong is one of the station's own modules + * (CelesTrak lists them as "CSS (TIANHE)", "CSS (WENTIAN)", "CSS (MENGTIAN)") + * rather than a visiting Shenzhou or Tianzhou. A missing entry counts as a + * module. + * @param {number} noradId + * @param {{name?: string}|undefined} entry + * @returns {boolean} + */ +export function tiangongIsModule(noradId, entry) { + return ( + noradId === TIANGONG_NORAD || /^CSS\s*\(/i.test(entry?.name ?? 'CSS (') + ); +} + +/** + * Tiangong as the station model factory describes it. The file is in meters + * (scale 1) and in the ISS file's frame, so it takes the ISS's local-axes + * mapping: the station is assumed to fly like the ISS, Tianhe along the + * velocity with the node (forward port) forward, the labs across the orbit, + * nadir to the Earth. Its joints are computed only; there is no telemetry. + * The Cockpit rides it from views on the model (`tiangongMounts.js`), and + * its ring follows the layer's orbit toggle like any tracked satellite's. + * @returns {import('./stationModel.js').StationModelSpec} + */ +export function tiangongModelSpec() { + return { + key: 'tiangong', + label: 'Tiangong', // i18n-ignore: the station's name, for log lines + norad: TIANGONG_NORAD, + modelUrl: TIANGONG_MODEL_URL, + scale: 1, + minPx: ISS_MODEL_MIN_PX, + maxDistanceM: ISS_MODEL_MAX_DISTANCE_M, + orbitHideM: ISS_ORBIT_HIDE_M, + cardClearM: TIANGONG_CARD_CLEAR_M, + companionRadiusM: ISS_COMPANION_RADIUS_M, + companionCoarseM: ISS_COMPANION_COARSE_M, + companionScanMs: ISS_COMPANION_SCAN_MS, + localAxes: ISS_MODEL_LOCAL_AXES, + isModule: tiangongIsModule, + createArticulation: createTiangongArticulation, + createTelemetry: null, + cockpitMount: tiangongCockpitMount, + // The Cockpit rides the station from a mount on the model, so the model + // stays while it does. + hideInCockpit: false, + syncOrbit: null, + }; +} + +/** + * Tiangong as a 3D model when the camera is close (stationModel.js). + * @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context + */ +export function createTiangongModel(context) { + return createStationModel(tiangongModelSpec(), context); +} diff --git a/src/layers/satellites/tiangongModel.test.mjs b/src/layers/satellites/tiangongModel.test.mjs new file mode 100644 index 0000000000..ee7dbb5a54 --- /dev/null +++ b/src/layers/satellites/tiangongModel.test.mjs @@ -0,0 +1,125 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { issModelSpec } from './issModel.js'; +import { + ISS_MODEL_LOCAL_AXES, + ISS_NORAD, + TIANGONG_MODEL_URL, + TIANGONG_NORAD, +} from './policy.js'; +import { stationModelShouldShow } from './stationModel.js'; +import { tiangongIsModule, tiangongModelSpec } from './tiangongModel.js'; + +test("Tiangong is CSS (TIANHE) by NORAD number, drawn at the file's meters", () => { + const spec = tiangongModelSpec(); + assert.equal(TIANGONG_NORAD, 48274); + assert.equal(spec.norad, TIANGONG_NORAD); + assert.equal(spec.key, 'tiangong'); + assert.equal(spec.scale, 1); + assert.equal(spec.modelUrl, TIANGONG_MODEL_URL); + // The same frame as the ISS file, so the same flight-axes mapping. + assert.equal(spec.localAxes, ISS_MODEL_LOCAL_AXES); + // No telemetry; Cockpit views on the model, so the model stays while the + // Cockpit rides it. + assert.equal(spec.createTelemetry, null); + assert.equal(typeof spec.cockpitMount, 'function'); + assert.equal(spec.hideInCockpit, false); + assert.equal(spec.syncOrbit, null); + assert.equal(typeof spec.createArticulation().update, 'function'); +}); + +test("the ISS spec keeps the ISS's own rules", () => { + const spec = issModelSpec({ parts: {} }); + assert.equal(spec.norad, ISS_NORAD); + assert.equal(spec.key, 'iss'); + assert.equal(spec.hideInCockpit, false); + assert.equal(typeof spec.cockpitMount, 'function'); + assert.equal(typeof spec.createTelemetry, 'function'); + assert.equal(typeof spec.syncOrbit, 'function'); +}); + +test("the station's modules are CSS (…) entries; ships are vehicles", () => { + assert.equal( + tiangongIsModule(TIANGONG_NORAD, { name: 'CSS (TIANHE)' }), + true, + ); + assert.equal(tiangongIsModule(53239, { name: 'CSS (WENTIAN)' }), true); + assert.equal(tiangongIsModule(54216, { name: 'CSS (MENGTIAN)' }), true); + assert.equal(tiangongIsModule(60000, { name: 'SHENZHOU-23 (SZ-23)' }), false); + assert.equal(tiangongIsModule(60001, { name: 'TIANZHOU-10' }), false); + assert.equal( + tiangongIsModule(60002, undefined), + true, + 'unknown: not a vehicle', + ); +}); + +test("a station hidden for the Cockpit stays hidden; the dot's rules otherwise", () => { + const shown = { + enabled: true, + showPoints: true, + hasStation: true, + classVisible: true, + tracked: false, + cockpitHidden: false, + }; + assert.equal(stationModelShouldShow(shown), true); + assert.equal( + stationModelShouldShow({ ...shown, cockpitHidden: true }), + false, + ); + assert.equal(stationModelShouldShow({ ...shown, hasStation: false }), false); + assert.equal( + stationModelShouldShow({ ...shown, classVisible: false, tracked: true }), + true, + ); +}); + +test('the shipped asset is centred on the station, in meters, with its own textures', () => { + const glb = readFileSync( + new URL(`../../../public${TIANGONG_MODEL_URL}`, import.meta.url), + ); + assert.equal(glb.toString('latin1', 0, 4), 'glTF'); + const jsonLength = glb.readUInt32LE(12); + const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8')); + assert.deepEqual(gltf.scenes[0].nodes.length, 1); + const root = gltf.nodes[gltf.scenes[0].nodes[0]]; + assert.equal(root.name, 'tiangong'); + // The same compression and texture format as the ISS file. + assert.ok(gltf.extensionsUsed.includes('KHR_draco_mesh_compression')); + assert.ok(gltf.extensionsUsed.includes('EXT_texture_webp')); + assert.ok(gltf.textures.length > 0); + assert.equal(gltf.animations ?? undefined, undefined); + // Station extents (without the vehicles): 41.9 m across the lab wings, + // 57.2 m along the flight direction. The root puts their centre at the + // origin, so minimumPixelSize scales about the orbital position. + const vehicles = new Set([ + 'SHENZHOU_FORWARD', + 'SHENZHOU_NADIR', + 'TIANZHOU_AFT', + ]); + const min = [Infinity, Infinity, Infinity]; + const max = [-Infinity, -Infinity, -Infinity]; + const visit = (index) => { + const node = gltf.nodes[index]; + if (vehicles.has(node.name)) return; + const offset = node.translation ?? [0, 0, 0]; + for (const primitive of gltf.meshes[node.mesh]?.primitives ?? []) { + const accessor = gltf.accessors[primitive.attributes.POSITION]; + for (let i = 0; i < 3; i++) { + min[i] = Math.min(min[i], accessor.min[i] + offset[i]); + max[i] = Math.max(max[i], accessor.max[i] + offset[i]); + } + } + (node.children ?? []).forEach(visit); + }; + root.children.forEach(visit); + assert.ok(Math.abs(max[0] - min[0] - 41.9) < 0.1, `X ${max[0] - min[0]}`); + assert.ok(Math.abs(max[2] - min[2] - 57.2) < 0.1, `Z ${max[2] - min[2]}`); + for (let i = 0; i < 3; i++) + assert.ok( + Math.abs((min[i] + max[i]) / 2 + root.translation[i]) < 0.05, + `centre ${i}`, + ); +}); diff --git a/src/layers/satellites/tiangongMounts.js b/src/layers/satellites/tiangongMounts.js new file mode 100644 index 0000000000..c42bb44045 --- /dev/null +++ b/src/layers/satellites/tiangongMounts.js @@ -0,0 +1,156 @@ +import { TIANGONG_NORAD } from './policy.js'; +import { + issMountView, + issMountWorld, + issNextMountView, + issPreviousMountView, +} from './issMounts.js'; + +/** + * The Cockpit's views from Tiangong, as `issMounts.js` gives the ISS's: a + * place on the model (`eye`, metres on the model's axes: port, zenith, + * forward) and where it looks (`forward`, `up`). The model is the layer's + * own build (`public/models/README.md`): Tianhe along the forward axis with + * the node at its forward end, Wentian and Mengtian out to either side of + * the node, a Shenzhou on the forward and nadir ports and a Tianzhou aft. + * The views are from the modules the catalog lists (CSS (TIANHE), CSS + * (WENTIAN), CSS (MENGTIAN)) and from the docked vehicle, so each rides an + * entry of its own; Tiangong needs no cards. + */ + +export const TIANGONG_WENTIAN_NORAD = 53239; +export const TIANGONG_MENGTIAN_NORAD = 54216; + +const mount = (eye, forward, up) => + Object.freeze({ + eye: Object.freeze(eye), + forward: Object.freeze(forward), + up: Object.freeze(up), + }); + +export const TIANGONG_MOUNTS = Object.freeze({ + /** + * Tianhe lies along the station's long axis, its wings at the aft end: + * from the top of the hull just forward of the wing roots, looking ahead + * along the station to the node and the two labs across it, the Earth + * below. + */ + tianhe: mount([0, 3.0, -3], [0, -0.4, 0.92], [0, 1, 0]), + /** + * Wentian reaches out from the node on the model's starboard side: from + * the top of its outer end, looking out past its wings and down, the + * arrays turning through the view as they follow the Sun. + */ + wentian: mount([-14, 2.9, 6.4], [-0.8, -0.5, 0.3], [0, 1, 0]), + /** Mengtian, the same on the port side. */ + mengtian: mount([14, 2.9, 6.4], [0.8, -0.5, 0.3], [0, 1, 0]), + /** + * A docked vehicle (a Shenzhou, a Tianzhou): the catalog does not say + * which port it is on, so it takes the place of the Tianzhou on the aft + * port: looking out behind the station and down, the Earth falling away. + */ + docked: mount([2.4, 0.5, -13], [0, -0.5, -0.87], [0, 1, 0]), +}); + +export const TIANGONG_MOUNT_ORDER = Object.freeze([ + 'tianhe', + 'wentian', + 'mengtian', + 'docked', +]); + +/** + * The views on offer, in order, each with the name it is shown under and + * the catalog entry it rides: the modules whenever the station is drawn + * (with no entry to ride when the catalog lacks one), the docked vehicle + * only when there is one. + * @param {{tianheName?: string|null, wentianName?: string|null, + * mengtianName?: string|null, dockedName?: string|null, + * tianheNorad?: number|null, wentianNorad?: number|null, + * mengtianNorad?: number|null, dockedNorad?: number|null}} [input] + * @returns {Array<{key: 'tianhe'|'wentian'|'mengtian'|'docked', + * label: string, noradId: number|null, card: null}>} + */ +export function tiangongMountViews({ + tianheName, + wentianName, + mengtianName, + dockedName, + tianheNorad = null, + wentianNorad = null, + mengtianNorad = null, + dockedNorad = null, +} = {}) { + const labels = { + tianhe: tiangongMountLabel(tianheName) || 'TIANHE', + wentian: tiangongMountLabel(wentianName) || 'WENTIAN', + mengtian: tiangongMountLabel(mengtianName) || 'MENGTIAN', + docked: tiangongMountLabel(dockedName), + }; + const entries = { + tianhe: tianheNorad, + wentian: wentianNorad, + mengtian: mengtianNorad, + docked: dockedNorad, + }; + return TIANGONG_MOUNT_ORDER.filter((key) => labels[key]).map((key) => ({ + key, + label: labels[key], + noradId: Number.isFinite(entries[key]) ? entries[key] : null, + card: null, + })); +} + +/** + * A view's name from its entry's catalog name, without the "CSS (…)" the + * catalog wraps the station's modules in. + * @param {string|null|undefined} name + * @returns {string} + */ +export function tiangongMountLabel(name) { + const text = String(name ?? '').trim(); + const inner = /^CSS\s*\((.+)\)$/i.exec(text); + return (inner ? inner[1] : text).trim(); +} + +/** + * The station model spec's `cockpitMount` for Tiangong: the view asked for + * (the first when none is, or it is not on offer), in the world. + * @param {{key: string|null, centre: {x:number,y:number,z:number}, + * axes: {x:number[], y:number[], z:number[]}, + * name: (noradId: number|null) => string|null, + * entry: (noradId: number|null) => number|null, + * dockedVehicle: number|null}} input + * @returns {object} + */ +export function tiangongCockpitMount({ + key, + centre, + axes, + name, + entry, + dockedVehicle, +}) { + const views = tiangongMountViews({ + tianheName: name(TIANGONG_NORAD), + wentianName: name(TIANGONG_WENTIAN_NORAD), + mengtianName: name(TIANGONG_MENGTIAN_NORAD), + dockedName: name(dockedVehicle), + tianheNorad: entry(TIANGONG_NORAD), + wentianNorad: entry(TIANGONG_WENTIAN_NORAD), + mengtianNorad: entry(TIANGONG_MENGTIAN_NORAD), + dockedNorad: entry(dockedVehicle), + }); + const view = issMountView(views, key); + return { + ...issMountWorld(TIANGONG_MOUNTS[view.key], centre, axes), + key: view.key, + label: view.label, + noradId: view.noradId, + card: view.card, + views, + }; +} + +export { issNextMountView as tiangongNextMountView }; +export { issPreviousMountView as tiangongPreviousMountView }; diff --git a/src/layers/satellites/tiangongMounts.test.mjs b/src/layers/satellites/tiangongMounts.test.mjs new file mode 100644 index 0000000000..31775b7edc --- /dev/null +++ b/src/layers/satellites/tiangongMounts.test.mjs @@ -0,0 +1,127 @@ +// src/layers/satellites/tiangongMounts.test.mjs — the Cockpit's views from +// Tiangong: offered in order from the modules the catalog lists and the +// docked vehicle, each riding its own entry, placed on the model's axes. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { TIANGONG_NORAD } from './policy.js'; +import { + TIANGONG_MENGTIAN_NORAD, + TIANGONG_MOUNT_ORDER, + TIANGONG_MOUNTS, + TIANGONG_WENTIAN_NORAD, + tiangongCockpitMount, + tiangongMountLabel, + tiangongMountViews, +} from './tiangongMounts.js'; + +const summary = (views) => + views.map(({ key, label, noradId }) => ({ key, label, noradId })); + +test('the station offers its views in order, Tianhe first', () => { + assert.deepEqual( + [...TIANGONG_MOUNT_ORDER], + ['tianhe', 'wentian', 'mengtian', 'docked'], + ); + for (const key of TIANGONG_MOUNT_ORDER) assert.ok(TIANGONG_MOUNTS[key]); + assert.equal( + new Set([TIANGONG_NORAD, TIANGONG_WENTIAN_NORAD, TIANGONG_MENGTIAN_NORAD]) + .size, + 3, + ); + const views = tiangongMountViews({ + tianheName: 'CSS (TIANHE)', + wentianName: 'CSS (WENTIAN)', + mengtianName: 'CSS (MENGTIAN)', + dockedName: 'SHENZHOU-23 (SZ-23)', + tianheNorad: TIANGONG_NORAD, + wentianNorad: TIANGONG_WENTIAN_NORAD, + mengtianNorad: TIANGONG_MENGTIAN_NORAD, + dockedNorad: 69180, + }); + assert.deepEqual(summary(views), [ + { key: 'tianhe', label: 'TIANHE', noradId: TIANGONG_NORAD }, + { key: 'wentian', label: 'WENTIAN', noradId: TIANGONG_WENTIAN_NORAD }, + { key: 'mengtian', label: 'MENGTIAN', noradId: TIANGONG_MENGTIAN_NORAD }, + { key: 'docked', label: 'SHENZHOU-23 (SZ-23)', noradId: 69180 }, + ]); + // Every view rides a catalog entry: no cards. + assert.ok(views.every((view) => view.card === null)); + // No vehicle docked: no view from one. The modules are part of the model, + // so they are offered even when the catalog has no entry for them. + assert.deepEqual(summary(tiangongMountViews()), [ + { key: 'tianhe', label: 'TIANHE', noradId: null }, + { key: 'wentian', label: 'WENTIAN', noradId: null }, + { key: 'mengtian', label: 'MENGTIAN', noradId: null }, + ]); +}); + +test('the view is named after the entry, without the catalog’s "CSS (…)"', () => { + assert.equal(tiangongMountLabel('CSS (WENTIAN)'), 'WENTIAN'); + assert.equal(tiangongMountLabel('TIANZHOU-10'), 'TIANZHOU-10'); + assert.equal(tiangongMountLabel(null), ''); +}); + +test('every mount is outside the hull, with a usable view frame', () => { + for (const key of TIANGONG_MOUNT_ORDER) { + const { eye, forward, up } = TIANGONG_MOUNTS[key]; + // Tianhe and the labs are 4.2 m across: no eye inside them (2.1 m of an + // axis), and none far from the station (the labs reach ~20 m out). + const offAxis = Math.hypot(eye[0], eye[1]); + const offLab = Math.hypot(eye[1], eye[2] - 6.4); + assert.ok(offAxis > 2.1 || offLab > 2.1, `${key} sits inside a module`); + assert.ok(Math.hypot(...eye) < 40, `${key} is off the station`); + assert.ok(Math.hypot(...forward) > 0.9, `${key} looks somewhere`); + assert.ok(Math.hypot(...up) > 0.9, `${key} has an up`); + assert.ok(forward[1] < 0, `${key} looks down at the Earth`); + } +}); + +test('the spec’s mount gives the view asked for in the world, else the first', () => { + const centre = { x: 6_780_000, y: 0, z: 0 }; + // The model's axes in the world: port = +y, zenith = +x (away from the + // Earth), forward = +z. + const axes = { x: [0, 0, 1], y: [0, 1, 0], z: [1, 0, 0] }; + const names = new Map([ + [TIANGONG_NORAD, 'CSS (TIANHE)'], + [TIANGONG_WENTIAN_NORAD, 'CSS (WENTIAN)'], + [69180, 'SHENZHOU-23 (SZ-23)'], + ]); + const input = { + centre, + axes, + name: (id) => names.get(id) ?? null, + entry: (id) => (names.has(id) ? id : null), + dockedVehicle: 69180, + }; + const first = tiangongCockpitMount({ ...input, key: null }); + assert.equal(first.key, 'tianhe'); + // The modules are 4.2 m across: no eye inside Tianhe (2.1 m of its axis). + assert.ok( + Math.hypot(TIANGONG_MOUNTS.tianhe.eye[0], TIANGONG_MOUNTS.tianhe.eye[1]) > + 2.1, + ); + assert.equal(first.noradId, TIANGONG_NORAD); + assert.deepEqual( + first.views.map((view) => view.key), + ['tianhe', 'wentian', 'mengtian', 'docked'], + ); + // Tianhe's eye is 3 m above the hull (+x in the world), 3 m aft (−z). + assert.ok(Math.abs(first.position.y) < 1e-9); + assert.ok(Math.abs(first.position.x - (6_780_000 + 3.0)) < 1e-9); + assert.ok(Math.abs(first.position.z + 3) < 1e-9); + assert.ok(first.direction.z > 0.9, 'looks ahead along the station'); + assert.ok(first.direction.x < 0, 'and down'); + const docked = tiangongCockpitMount({ ...input, key: 'docked' }); + assert.equal(docked.key, 'docked'); + assert.equal(docked.noradId, 69180); + assert.equal(docked.label, 'SHENZHOU-23 (SZ-23)'); + assert.ok(docked.direction.z < -0.8, 'looks behind the station'); + const unknown = tiangongCockpitMount({ ...input, key: 'cupola' }); + assert.equal(unknown.key, 'tianhe', 'a view not on offer gives the first'); + // The frame is unit and square. + const d = docked.direction; + const u = docked.up; + assert.ok(Math.abs(Math.hypot(d.x, d.y, d.z) - 1) < 1e-9); + assert.ok(Math.abs(Math.hypot(u.x, u.y, u.z) - 1) < 1e-9); + assert.ok(Math.abs(d.x * u.x + d.y * u.y + d.z * u.z) < 1e-9); +}); diff --git a/src/layers/satellites/tiangongStation.js b/src/layers/satellites/tiangongStation.js new file mode 100644 index 0000000000..4b03c00e16 --- /dev/null +++ b/src/layers/satellites/tiangongStation.js @@ -0,0 +1,141 @@ +import { msg } from '../../i18n/index.js'; +import { issCommandFastOrbit } from './issCommand.js'; +import { ISS_ARM_LABELS, ISS_SUN_POSES } from './issStation.js'; +import { TIANGONG_NORAD } from './policy.js'; +import { trackedStation } from './stationModels.js'; +import { + TIANGONG_ARMS, + TIANGONG_ONE_AXIS_WINGS, + TIANGONG_TWO_AXIS_WINGS, +} from './tiangongArticulation.js'; + +/** The lab wings' slider labels, per TIANGONG_TWO_AXIS_WINGS entry. */ +const LAB_WING_LABELS = [ + [msg('Wentian forward · alpha'), msg('Wentian forward · beta')], + [msg('Wentian aft · alpha'), msg('Wentian aft · beta')], + [msg('Mengtian forward · alpha'), msg('Mengtian forward · beta')], + [msg('Mengtian aft · alpha'), msg('Mengtian aft · beta')], +]; + +/** + * Tiangong as the STATION section describes it (stationPanel.js): its joint + * driver from the model part, computed values only (China publishes no + * telemetry), and the Manual controls: the Sun's position or a fast orbit, + * and the two arms posed by joint. + * @param {{state: object, parts: object}} context + * @returns {import('./stationPanel.js').StationDescription} + */ +export function tiangongStationDescription({ state: layerState, parts }) { + const model = () => parts.tiangongModel ?? null; + const armGroup = (id, label, joints) => ({ + id, + label, + kind: 'sliders', + resume: msg('Resume sway'), + sliders: joints.map((joint, i) => ({ + id: joint.node, + label: ISS_ARM_LABELS[i], + min: -120, + max: 120, + apply: (a, value) => + a.setJoint( + joint.node, + joint.pivot, + joint.axis, + (value * Math.PI) / 180, + ), + })), + resumeApply: (a) => a.resumeArm(id), + }); + // Every wing has a joint of its own, so each can be set apart from the + // others; a wing not touched keeps following the Sun. + const wingSlider = (joint, label) => ({ + id: joint.node, + label, + min: -180, + max: 180, + apply: (a, value) => a.setWingAngle(joint.node, (value * Math.PI) / 180), + }); + const wingGroup = (id, label, sliders) => ({ + id, + label, + kind: 'sliders', + resume: msg('Follow the Sun'), + sliders, + resumeApply: (a) => a.resumeWings(), + }); + const tianheWings = wingGroup('tianhe-wings', msg('Tianhe wings (degrees)'), [ + wingSlider(TIANGONG_ONE_AXIS_WINGS[0], msg('Port wing')), + wingSlider(TIANGONG_ONE_AXIS_WINGS[1], msg('Starboard wing')), + ]); + const labWings = wingGroup( + 'lab-wings', + msg('Lab wings (degrees)'), + TIANGONG_TWO_AXIS_WINGS.flatMap((pair, i) => [ + wingSlider(pair.alpha, LAB_WING_LABELS[i][0]), + wingSlider(pair.beta, LAB_WING_LABELS[i][1]), + ]), + ); + return { + key: 'tiangong', + title: 'Tiangong', // i18n-ignore: the station's name + selected: () => trackedStation(layerState, parts)?.norad === TIANGONG_NORAD, + subjectName: () => + layerState._catalog.get(layerState._trackedNorad)?.name?.trim() || + `Tiangong · NORAD ${TIANGONG_NORAD}`, + articulation: () => model()?._articulation ?? null, + // No feed exists: the status line says so instead of waiting for one. + telemetry: () => ({ state: 'none', poseAgeMs: null, liveUntilMs: null }), + position: () => + model()?._visualPosition?.() ?? + layerState._trackedFrameCartesian ?? + parts.rendering?._pointPosition?.(TIANGONG_NORAD) ?? + null, + zoomLabel: msg('Zoom to Tiangong'), + notes: { + computed: msg( + 'Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.', + ), + }, + groups: [ + { + id: 'sun', + label: msg('Sun position'), + kind: 'choices', + choices: [ + { + id: 'follow', + label: msg('Follow the Sun'), + isDefault: true, + apply: (a) => a.setOverride(null), + }, + ...ISS_SUN_POSES.map(({ id, label, sun, sunlit }) => ({ + id, + label, + apply: (a) => { + const fixed = { sun, sunlit }; + a.setOverride(() => fixed); + }, + })), + { + id: 'orbit', + label: msg('Fast orbit (40 s)'), + apply: (a) => { + const start = Date.now(); + a.setOverride((nowMs) => issCommandFastOrbit(nowMs - start)); + }, + }, + ], + }, + tianheWings, + labWings, + armGroup('cmm', msg('Tianhe arm (degrees)'), TIANGONG_ARMS.cmm), + armGroup('emm', msg('Wentian arm (degrees)'), TIANGONG_ARMS.emm), + ], + automatic: (a) => { + a.setOverride(null); + a.resumeWings(); + a.resumeArm(); + }, + }; +} diff --git a/src/layers/satellites/tiangongStation.test.mjs b/src/layers/satellites/tiangongStation.test.mjs new file mode 100644 index 0000000000..2b0cddb2f8 --- /dev/null +++ b/src/layers/satellites/tiangongStation.test.mjs @@ -0,0 +1,179 @@ +// src/layers/satellites/tiangongStation.test.mjs — Tiangong's STATION +// description: every wing can be set apart from the others, and Automatic +// hands them all back to the Sun. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + createTiangongArticulation, + TIANGONG_ONE_AXIS_WINGS, + TIANGONG_TWO_AXIS_WINGS, +} from './tiangongArticulation.js'; +import { issAxisMatrix } from './issArticulation.js'; +import { tiangongStationDescription } from './tiangongStation.js'; +import { TIANGONG_NORAD } from './policy.js'; + +function recordingArticulation() { + const calls = []; + return { + calls, + setOverride: (fn) => calls.push(['override', fn === null ? null : 'fn']), + setJoint: (node, pivot, axis, angle) => calls.push(['joint', node, angle]), + resumeArm: (key) => calls.push(['resumeArm', key ?? null]), + setWingAngle: (node, angle) => calls.push(['wing', node, angle]), + resumeWings: () => calls.push(['resumeWings']), + }; +} + +function description() { + const layerState = { + _trackedNorad: TIANGONG_NORAD, + _catalog: new Map([[TIANGONG_NORAD, { name: 'CSS (TIANHE)' }]]), + _points: new Map(), + _trackedFrameCartesian: null, + }; + const parts = { tiangongModel: { _articulation: null } }; + return tiangongStationDescription({ state: layerState, parts }); +} + +test('the description offers one slider per wing joint: two on Tianhe, eight on the labs', () => { + const d = description(); + const tianhe = d.groups.find((g) => g.id === 'tianhe-wings'); + const labs = d.groups.find((g) => g.id === 'lab-wings'); + assert.equal(tianhe.kind, 'sliders'); + assert.deepEqual( + tianhe.sliders.map((s) => s.id), + TIANGONG_ONE_AXIS_WINGS.slice(0, 2).map((w) => w.node), + ); + assert.equal(labs.sliders.length, 8); + assert.deepEqual( + labs.sliders.map((s) => s.id), + TIANGONG_TWO_AXIS_WINGS.flatMap((p) => [p.alpha.node, p.beta.node]), + ); + const labels = new Set(labs.sliders.map((s) => s.label)); + assert.equal(labels.size, 8, 'every lab slider has a label of its own'); + for (const slider of [...tianhe.sliders, ...labs.sliders]) { + assert.equal(slider.min, -180); + assert.equal(slider.max, 180); + } + // The arms are still there, after the wings. + assert.deepEqual( + d.groups.map((g) => g.id), + ['sun', 'tianhe-wings', 'lab-wings', 'cmm', 'emm'], + ); +}); + +test('a wing slider sets that wing alone, in radians; the group resume frees them all', () => { + const d = description(); + const a = recordingArticulation(); + const labs = d.groups.find((g) => g.id === 'lab-wings'); + labs.sliders[3].apply(a, 90); + assert.deepEqual(a.calls, [['wing', labs.sliders[3].id, Math.PI / 2]]); + labs.resumeApply(a); + assert.deepEqual(a.calls.at(-1), ['resumeWings']); + assert.equal(labs.resume, 'Follow the Sun'); +}); + +test('Automatic hands the Sun, the wings and the arms back', () => { + const d = description(); + const a = recordingArticulation(); + d.automatic(a); + assert.deepEqual(a.calls, [ + ['override', null], + ['resumeWings'], + ['resumeArm', null], + ]); +}); + +/** A stand-in model whose nodes keep the last matrix written. */ +function fakeModel() { + const nodes = new Map(); + return { + ready: true, + nodes, + getNode(name) { + // Cesium's node clones the matrix it is given; the driver writes a + // shared scratch matrix, so the stand-in must clone too. + if (!nodes.has(name)) + nodes.set(name, { + _matrix: null, + get matrix() { + return this._matrix; + }, + set matrix(value) { + this._matrix = Cesium.Matrix4.clone(value); + }, + }); + return nodes.get(name); + }, + }; +} + +test('the driver holds a wing set by hand at its angle while the others follow the Sun', () => { + const driver = createTiangongArticulation(); + const model = fakeModel(); + const date = new Date('2026-11-13T12:00:00Z'); + const position = new Cesium.Cartesian3(6_780_000, 0, 0); + const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] }; + // A fixed Sun: the real one would fetch Cesium's Earth-orientation data. + const fixed = { sun: [0, 0.6, 0.8], sunlit: true }; + driver.setOverride(() => fixed); + driver.update(model, date, position, axes, 1000); + const port = TIANGONG_ONE_AXIS_WINGS[0]; + const starboard = TIANGONG_ONE_AXIS_WINGS[1]; + const portBefore = Cesium.Matrix4.clone(model.getNode(port.node).matrix); + const starboardBefore = Cesium.Matrix4.clone( + model.getNode(starboard.node).matrix, + ); + driver.setWingAngle(port.node, 1.2); + // Long after the last frame: the step is not rate-limited. + driver.update(model, date, position, axes, 11_000); + const expected = issAxisMatrix( + port.pivot, + port.axis, + 1.2, + new Cesium.Matrix4(), + ); + assert.ok( + Cesium.Matrix4.equalsEpsilon( + model.getNode(port.node).matrix, + expected, + 1e-9, + ), + 'the port wing is at the set angle', + ); + assert.ok( + Cesium.Matrix4.equalsEpsilon( + model.getNode(starboard.node).matrix, + starboardBefore, + 1e-9, + ), + 'the starboard wing kept its Sun angle (same Sun, same date)', + ); + assert.equal( + Cesium.Matrix4.equals(model.getNode(port.node).matrix, portBefore), + false, + 'the set angle differs from the Sun angle', + ); + driver.resumeWings(); + driver.update(model, date, position, axes, 21_000); + assert.ok( + Cesium.Matrix4.equalsEpsilon( + model.getNode(port.node).matrix, + portBefore, + 1e-9, + ), + 'back to the Sun once freed', + ); + // Null frees one wing on its own. + driver.setWingAngle(port.node, 0.3); + driver.setWingAngle(port.node, null); + driver.update(model, date, position, axes, 31_000); + assert.ok( + Cesium.Matrix4.equalsEpsilon( + model.getNode(port.node).matrix, + portBefore, + 1e-9, + ), + ); +}); diff --git a/src/layers/satellites/tracking.js b/src/layers/satellites/tracking.js index 8d80fd6c4c..1fd23f3492 100644 --- a/src/layers/satellites/tracking.js +++ b/src/layers/satellites/tracking.js @@ -1,19 +1,21 @@ import { cameraOf } from '../../render/rendererOf.js'; import { entityFollowTarget, stopFollowing } from '../../data/followed.js'; import { satelliteClassText } from '../../data/satelliteClass.js'; -import { fromDegreesInto } from '../../geo/ellipsoid.js'; -import { clone, scale } from '../../geo/vector.js'; +import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js'; +import { clone, distance, scale } from '../../geo/vector.js'; import { t } from '../../i18n/index.js'; import { formatQuantity, unitLabel } from '../../ui/unitLabels.js'; import { - ISS_NORAD, CONTEXT_REFRESH_INTERVAL_MS, HIGH_ORBIT_ALTITUDE_M, + ISS_NORAD, + STATIONS, TRACK_VIEW_FROM_HIGH_SCALE, TRACK_VIEW_FROM_LEO, TRACKED_ORBIT_COLOR, } from './policy.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; +import { modelFor } from './stationModels.js'; export function createTracking({ state: layerState, services, parts, source }) { const { clearFocusTarget } = services.focus; @@ -118,6 +120,8 @@ export function createTracking({ state: layerState, services, parts, source }) { layerState._trackedEntity = null; } layerState._trackedNorad = null; + layerState._trackedDockedToStation = null; + layerState._trackedDockedToIss = false; parts.controls._syncIssOrbit?.(); // A held Cockpit subject that stops being tracked gets its marks back. if (layerState._cockpitSubjectNorad !== null) @@ -384,11 +388,27 @@ export function createTracking({ state: layerState, services, parts, source }) { : t('DOCKED · {name}', { name: companions[0] }), ); } + // While a station's model shows, the card keeps clear of it: the gap + // follows the station's size on screen, in steps so the card is not + // republished every frame. + const clearPx = + modelFor(parts, layerState._trackedNorad)?._cardClearPx?.() ?? null; const current = readEntityRecord(layerState._trackedEntity)?.labelModel; + // The overlay's gap is twice the anchor radius, so half the clearance, + // in 4 px steps. The step kept stands until the clearance has moved a + // pixel past the step's edge: at an edge, sub-pixel jitter in the range + // would otherwise flip it, and republish the card, every frame. + const kept = current?.anchorRadiusPx ?? null; + const anchorRadiusPx = !clearPx + ? null + : kept !== null && Math.abs(clearPx / 2 - kept) < 3 + ? kept + : Math.round(clearPx / 8) * 4; // Compare the WHOLE detail array: comparing only `details[0]` swallowed any // change confined to the companions line, so the card would never republish. const unchanged = current?.title === title && + (current?.anchorRadiusPx ?? null) === anchorRadiusPx && current?.details?.length === details.length && details.every((line, index) => current.details[index] === line); if (unchanged) return; @@ -396,10 +416,38 @@ export function createTracking({ state: layerState, services, parts, source }) { title, details, accent: '#ffd84d', + ...(anchorRadiusPx ? { anchorRadiusPx, anchorRadiusScale: null } : {}), }; refreshTrackedReadout(layerState._trackedEntity); } + /** + * The station a satellite is docked to: both orbits, propagated to one + * instant, within the station's companion radius (dots are moved at + * different moments, so their spacing cannot say). A station is docked to + * nothing, and the dense group never is. + * @param {number} noradId + * @returns {number|null} The station's NORAD number, or null. + */ + function _dockedToStation(noradId) { + if (STATIONS.some((station) => station.norad === noradId)) return null; + const sat = layerState._catalog.get(noradId); + if (!sat?.satrec || sat.group === 'dense') return null; + const date = new Date(layerState.now()); + const at = (p) => fromDegrees(p.longitude, p.latitude, p.altitude); + let own = null; + for (const station of STATIONS) { + const entry = layerState._catalog.get(station.norad); + if (!entry?.satrec) continue; + own ??= parts.orbits.propagatePosition(sat.satrec, date); + if (!own) return null; + const there = parts.orbits.propagatePosition(entry.satrec, date); + if (there && distance(at(own), at(there)) <= station.companionRadiusM) + return station.norad; + } + return null; + } + function _trackSatellite(noradId, { origin = 'programmatic' } = {}) { _clearTracking(false, { origin }); @@ -414,9 +462,18 @@ export function createTracking({ state: layerState, services, parts, source }) { // Hide the dot — the tracked dot draws it, larger and over everything. parts.rendering._hidePoint(noradId); - // Show orbital path - parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR); - if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.(); + // Show orbital path. An object docked to the ISS (Nauka, a Progress…) + // flies the station's orbit under elements of its own: its ring would + // run beside the ISS's, a second line through the same station. The + // ISS's ring stands for it instead. Another station's ring is drawn only + // while that station is tracked, so its docked objects keep their own. + layerState._trackedDockedToStation = _dockedToStation(noradId); + layerState._trackedDockedToIss = + layerState._trackedDockedToStation === ISS_NORAD; + if (!layerState._trackedDockedToIss) + parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR); + if (noradId === ISS_NORAD || layerState._trackedDockedToIss) + parts.controls._syncIssOrbit?.(); // The tracked position propagates per evaluation through the per-frame // cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame. @@ -453,6 +510,11 @@ export function createTracking({ state: layerState, services, parts, source }) { entityRecord(layerState._trackedEntity).trackedId = `satellites:${noradId}`; entityRecord(layerState._trackedEntity).displayPosition = _trackedDisplayCached; + // Up close a station is a 3D model: the card welds to where it is drawn. + // So does the card of an object docked to it, which the model stands in + // for. + entityRecord(layerState._trackedEntity).visualPosition = () => + modelFor(parts, noradId)?._visualPosition?.() ?? null; _updateTrackedSatelliteLabelModel(initialPos?.altitude ?? null); const dotPosition = parts.rendering._pointPosition(noradId); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index e524925b09..3c359ba2e7 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -7103,6 +7103,63 @@ test('models moved every frame keep their shader and pick ids: only a new look o } }); +test('a model poses its named nodes once ready, writes only what changed, and gives a dropped one its own pose back', async () => { + const { loads, restore } = fakeModelLoads(); + try { + const part = createCesiumDraw({ + scene: fakeScene(), + report: (error) => assert.fail(error), + }); + const set = part.port.models({ id: 'station' }); + const turn = (x) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1]; + const item = (nodes) => ({ + id: 'iss', + pos: { lon: 0, lat: 0, height: 400e3 }, + url: 'iss.glb', + orientation: { heading: 0, pitch: 0, roll: 0 }, + nodes, + }); + set.upsert([item({ joint: turn(1), other: turn(2), missing: turn(3) })]); + loads[0].resolve(); + await settle(); + const model = loads[0].model; + const writes = []; + const nodes = {}; + for (const name of ['joint', 'other']) + nodes[name] = { + originalMatrix: Cesium.Matrix4.fromTranslation( + new Cesium.Cartesian3(9, 9, 9), + ), + set matrix(m) { + writes.push(name); + // As Cesium's runtime node does: a copy, not the matrix handed in. + this.current = Cesium.Matrix4.clone(m); + }, + }; + model.getNode = (name) => { + assert.equal(model.ready, true, 'nodes are asked for once ready'); + return nodes[name]; + }; + loads[0].ready(); + assert.deepEqual(writes.sort(), ['joint', 'other'], 'posed when ready'); + assert.equal(nodes.joint.current[12], 1); + assert.equal(nodes.other.current[12], 2); + + writes.length = 0; + set.upsert([item({ joint: turn(1), other: turn(5), missing: turn(3) })]); + assert.deepEqual(writes, ['other'], 'only the node that moved'); + assert.equal(nodes.other.current[12], 5); + + writes.length = 0; + set.upsert([item({ other: turn(5) })]); + assert.deepEqual(writes, ['joint'], 'the dropped node, back to its pose'); + assert.equal(nodes.joint.current[12], 9); + set.dispose(); + } finally { + restore(); + } +}); + test('a model set that recedes fades its models toward the limb with their focus; focus alone dims', async () => { const { recedeFactors, recedeFrame, recedeParams, recededAlpha } = await import('../recession.js'); diff --git a/src/render/cesium/drawModels.js b/src/render/cesium/drawModels.js index 08c03ccc9c..965d331cf1 100644 --- a/src/render/cesium/drawModels.js +++ b/src/render/cesium/drawModels.js @@ -5,7 +5,7 @@ * item's `url` re-poses and restyles its model in place (position, * orientation, scale, `axisScale` and pixel bounds, `shading`, `tint`, * `colorBlend`, `maskColor`, `clip`, `environmentMap`, `displayRange`, - * `show`); only a new `url` loads again, and the old model keeps drawing + * `nodes`, `show`); only a new `url` loads again, and the old model keeps drawing * until the new one is ready, so a swap never blinks. `ready` fires once per * load, when the model has loaded and is posed. An item with its `gltf` * bytes is built from them; its url is then not fetched. @@ -78,6 +78,62 @@ export const MODEL_RETRY_MS = 5000; */ export const RECEDE_WRITE_EPSILON = 0.005; +/** + * Each model's posed nodes (`ModelItem.nodes`): name → the 16 numbers last + * written, so an update that keeps a node's matrix writes nothing. + */ +const posedNodes = new WeakMap(); +/** A posed name the model has no node for: looked up once, then skipped. */ +const NO_NODE = Symbol('no such node'); +const scratchNodeMatrix = new Cesium.Matrix4(); + +/** + * Write the item's node transforms to `model` once it is ready: changed + * ones only, and a node whose name left the map back to its authored pose. + * Names the model lacks are skipped. + */ +function poseNodes(item, model) { + if (model.ready !== true) return; + const wanted = item.nodes; + let posed = posedNodes.get(model); + if (!wanted && !posed) return; + if (!posed) posedNodes.set(model, (posed = new Map())); + for (const [name, last] of posed) { + if (wanted && Object.hasOwn(wanted, name)) continue; + posed.delete(name); + if (last === NO_NODE) continue; + const node = model.getNode(name); + if (node) node.matrix = Cesium.Matrix4.clone(node.originalMatrix); + } + if (!wanted) return; + for (const name of Object.keys(wanted)) { + const matrix = wanted[name]; + if (!matrix || matrix.length < 16) continue; + const last = posed.get(name); + if (last === NO_NODE) continue; + if (last && sameMatrix(last, matrix)) continue; + const node = model.getNode(name); + if (!node) { + posed.set(name, NO_NODE); + continue; + } + // The last matrix written, kept in one array per node, copied in place. + let kept = last; + if (!(kept instanceof Float64Array)) { + kept = new Float64Array(16); + posed.set(name, kept); + } + for (let i = 0; i < 16; i++) kept[i] = matrix[i]; + // The node copies the matrix it is given. + node.matrix = Cesium.Matrix4.fromArray(matrix, 0, scratchNodeMatrix); + } +} + +function sameMatrix(a, b) { + for (let i = 0; i < 16; i++) if (a[i] !== b[i]) return false; + return true; +} + /** Cesium's own blend amount, for a `mix` that names none. */ const DEFAULT_MIX = 0.5; @@ -1057,6 +1113,7 @@ export function createModelSets({ const hidden = range && !(range[1] > range[0]); if (entry.styled?.range !== rangeKey) entry.styled = { range: rangeKey }; entry.dynamic = needsFrame(item, record.spec); + poseNodes(item, model); apply(entry, model, entry.frame ?? STILL, hidden); } diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 85efe4569a..d09773aa53 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -82,6 +82,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.models', 'draw.shapes.lit', 'draw.models.loadFailed', + 'draw.models.nodes', 'draw.models.tint', 'draw.models.blend', 'draw.models.paint', @@ -197,6 +198,7 @@ function nextFrame() { export function createCesiumHarness({ name = 'cesium', model, + modelNode, missingModel, cameraController, } = {}) { @@ -269,6 +271,7 @@ export function createCesiumHarness({ ? { assets: { model, + ...(modelNode ? { modelNode } : {}), missingModel, // The model's bytes, for the check that a model drawn from them // never fetches its url. diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 09554e04c6..db910f8ad0 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -77,6 +77,8 @@ export function cesiumCapabilities(scene, only) { // Cesium scatters drawn models through the atmosphere wherever the // scene draws fog (its models' atmosphere stage). 'modelAtmosphere', + // A model item's nodes, written to the model's runtime nodes. + 'modelNodes', 'quads', 'meshes', // Raster shells; other field kinds are refused. diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 36602d89a9..3de8dfce4f 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -38,6 +38,7 @@ test('capabilities follow what the scene supports', () => { 'models', 'modelParts', 'modelAtmosphere', + 'modelNodes', 'quads', 'meshes', 'fields', diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 1f28742747..c40e0209fd 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -3769,6 +3769,71 @@ export function portChecks() { }, { capability: 'models' }, ), + check( + 'draw.models.nodes', + "a model item's nodes pose its named glTF nodes, live, and a node that leaves the map goes back to its authored pose", + async (h, r) => { + if (!h.assets?.model || !h.assets?.modelNode) + return { skip: 'no model with a named node in this harness' }; + const NODE = h.assets.modelNode; + await overAustin(h, r); + const set = r.draw.models({ id: 'conf:models.nodes' }); + const ready = []; + set.on('ready', (id) => ready.push(id)); + const pos = h.toEcef({ ...AUSTIN, height: 0 }); + // Far off along the node's own x axis: off the screen's centre. + const away = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 5000, 0, 0, 1]; + const model = (nodes) => ({ + id: 'm', + pos, + url: h.assets.model, + orientation: { heading: 0, pitch: 0, roll: 0 }, + minPixelSize: 160, + environmentMap: false, + shading: 'unlit', + tint: '#ff0000', + colorBlend: { mode: 'replace' }, + ...(nodes ? { nodes } : {}), + }); + try { + set.set([model(null)]); + for (let i = 0; i < 600 && !ready.length; i++) await drawn(h, r, 1); + deepEqual(ready, ['m'], 'ready'); + const s = r.query.project(pos); + // How many pixels of a patch at the model's centre are red. + const red = async () => { + await drawn(h, r, 3); + await settled(r); + r.frame.renderNow(); + const image = r.readPixels({ + crop: { + x: Math.round(s.x) - 4, + y: Math.round(s.y) - 4, + width: 9, + height: 9, + }, + }); + let n = 0; + for (let i = 0; i < image.data.length; i += 4) { + const [r0, g, b] = image.data.subarray(i, i + 3); + if (r0 > 180 && g < 70 && b < 70) n++; + } + return n; + }; + ok((await red()) >= 40, 'authored pose: at the centre'); + set.upsert([model({ [NODE]: away })]); + ok((await red()) < 10, 'the node moved away, live'); + set.upsert([model({ [NODE]: away, NO_SUCH_NODE: away })]); + ok((await red()) < 10, 'a name the model lacks changes nothing'); + set.upsert([model(null)]); + ok((await red()) >= 40, 'the node left the map: authored pose'); + deepEqual(ready, ['m'], 'without loading again'); + } finally { + set.dispose(); + } + }, + { capability: 'modelNodes', bareSky: true }, + ), check( 'draw.models.loadFailed', 'a model set says when a model fails to load, and loads it when added again', diff --git a/src/render/conformance/index.d.ts b/src/render/conformance/index.d.ts index 33407e78a1..27c5a21f63 100644 --- a/src/render/conformance/index.d.ts +++ b/src/render/conformance/index.d.ts @@ -68,6 +68,8 @@ export interface ConformanceHarness { ): void | Promise; assets?: { model?: string; + /** The name of a node `model` has, for the `nodes` check. */ + modelNode?: string; missingModel?: string; modelBytes?: () => Promise; }; diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts index 1ac6413542..123543f9e4 100644 --- a/src/render/contract/common.d.ts +++ b/src/render/contract/common.d.ts @@ -157,6 +157,8 @@ export type Capability = | 'terrain' /** Atmosphere scattering applied to drawn models. */ | 'modelAtmosphere' + /** A model item's `nodes` pose the model's named glTF nodes. */ + | 'modelNodes' /** Clouds, fog, haze, rain and snow around the view (`globe.weather`). */ | 'weather' /** Imagery draped onto 3D tiles as well as the globe. */ diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 8191d78f2a..5372aba3db 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -444,6 +444,15 @@ export interface ModelItem extends Placed { * would not hide what lies below it). Can change live. */ clip?: 'belowOrigin'; + /** + * Transforms of the model's named glTF nodes (an articulated model's + * joints): each a column-major 4×4 matrix in the node's parent frame that + * replaces the node's own transform. A node whose name leaves the map goes + * back to its authored pose; names the model lacks are ignored. Applied + * once the model is ready, on a renderer with the `modelNodes` + * capability; elsewhere the model draws as authored. Can change live. + */ + nodes?: Readonly>>; /** * Emphasis for a focused model, 0..1, 1 = none: the tint's alpha is * multiplied by it (in a set that recedes, as `RecedeSpec` says). Can diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 3accf55f71..f152552c39 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -19,6 +19,7 @@ export const CAPABILITIES = Object.freeze([ 'finestHeights', 'terrain', 'modelAtmosphere', + 'modelNodes', 'weather', 'imageryOnTiles', 'splitSwipe', diff --git a/src/render/stub/harness.js b/src/render/stub/harness.js index dc82744cbb..fbf7fa9fca 100644 --- a/src/render/stub/harness.js +++ b/src/render/stub/harness.js @@ -45,6 +45,8 @@ export function createStubHarness(name = 'stub') { // its failing scheme. assets: { model: 'stub:model.glb', + // A stub model is one node, named after its file. + modelNode: 'model', missingModel: `${STUB_FAILING_MODEL_SCHEME}model.glb`, // Any bytes: the stub parses none. modelBytes: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]), diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 7ef3bcf7c4..ab913945b4 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -10,6 +10,7 @@ * loop on a virtual clock, one frame at a time, in the contract's order. */ import { horizonFrom } from '../../geo/horizon.js'; +import { headingPitchRollFrame } from '../../geo/quaternion.js'; import { alongLength } from '../../geo/polyline.js'; import { clusterScreenPoints } from '../../geo/screenCluster.js'; import { createInputRouter } from '../input/router.js'; @@ -808,6 +809,7 @@ export function createStubRenderer(options = {}) { function itemPosition(set, item, aheadMs = 0) { if (!item.pos) return null; const base = toEcef(item.pos); + if (set.kind === 'models') return posedModelPosition(item, base); const p = set.kind === 'icons' && item.motion && capabilities.has('motionSegments') ? motionPosition(item.motion, base, motionTime(set) + aheadMs) @@ -821,6 +823,46 @@ export function createStubRenderer(options = {}) { : p; } + /** + * Where the stub draws a model. A stub model is one node, named after its + * file (`/models/c172.glb` is `c172`, `stub:model.glb` is `model`): with + * `modelNodes`, an item's + * `nodes` entry for that name moves it by the matrix's translation, on the + * model's axes and at its scale; any other name is one the model lacks. + */ + function posedModelPosition(item, base) { + if (!capabilities.has('modelNodes') || !item.nodes) return base; + const file = String(item.url ?? '') + .split(/[?#]/)[0] + .split(/[/:]/) + .pop(); + const name = file.replace(/\.[^.]*$/, ''); + const m = name ? item.nodes[name] : null; + if (!m || m.length < 16) return base; + const k = item.scale ?? 1; + const frame = headingPitchRollFrame(base, { + heading: item.orientation?.heading ?? 0, + pitch: item.orientation?.pitch ?? 0, + roll: item.orientation?.roll ?? 0, + }); + const along = (axis, t) => ({ + x: axis.x * t * k, + y: axis.y * t * k, + z: axis.z * t * k, + }); + let p = base; + for (const [axis, t] of [ + [frame.x, m[12]], + [frame.y, m[13]], + [frame.z, m[14]], + ]) + if (t) { + const d = along(axis, t); + p = { x: p.x + d.x, y: p.y + d.y, z: p.z + d.z }; + } + return p; + } + /** * The shown models as the stub draws them: a square as wide as a pick * takes (at most `maxPixelSize`, at least `minPixelSize`), far diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index 655540c924..905c2e1101 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -1,6 +1,6 @@ import { followedOf } from '../data/followed.js'; import { readEntityRecord } from '../data/entityRecords.js'; -import { nextTick } from 'vue'; +import { nextTick, watch } from 'vue'; import { resolveImageryHost } from '../layers/weather/imageryHost.js'; import { ShellFacade } from './shellFacade.js'; import { AircraftDisplay } from './aircraftDisplay.js'; @@ -25,6 +25,7 @@ import { CctvControls } from './cctv.js'; import { StreetLevelControls } from './streetLevelControls.js'; import { createWildlifeSightingCard } from './wildlifeSightingCard.js'; import { RadioControls } from './radio.js'; +import { LiveControls } from './liveControls.js'; import { LocalSdrControls } from './localSdrControls.js'; import { LocationNavigation } from './locationNavigation.js'; import { bindCameraOrientationControls } from './cameraOrientationControls.js'; @@ -62,6 +63,8 @@ import { applyLocaleChoice } from './localePicker.js'; import { PanelNavigation } from './panelNavigation.js'; import { applicationPinia, createUiRuntime } from './vueRuntime.js'; import { useContextStore } from './stores/context.js'; +import { useLiveStore } from './stores/live.js'; +import { useStationStore } from './stores/station.js'; import { useSpaceMissionsStore } from './stores/spaceMissions.js'; import { SpaceMissionsControls } from './spaceMissionsControls.js'; import { useMissionReplayStore } from './stores/missionReplay.js'; @@ -1034,8 +1037,12 @@ export class StyleManager extends ShellFacade { } _initGlobalContextPanel() { - const { radioLayer, militaryInstallationsLayer, militaryAwarenessLayer } = - this.services; + const { + radioLayer, + militaryInstallationsLayer, + militaryAwarenessLayer, + satellitesLayer, + } = this.services; const contextStore = useContextStore(applicationPinia()); this._contextControls = new ContextControls({ elements: { @@ -1075,6 +1082,39 @@ export class StyleManager extends ShellFacade { militaryAwarenessLayer?.subscribeDirectionOverlay?.((view) => awarenessDirectionStore.publish(view), ); + // The STATION section: the selected space station's moving parts, as + // the satellites layer presents them; its controls reach the layer. + const stationStore = useStationStore(applicationPinia()); + this._stationPanelUnsubscribe?.(); + if (this._stationOwner) stationStore.detach(this._stationOwner); + this._stationOwner = null; + stationStore.publish(null); + if (satellitesLayer?.getStationActions) + this._stationOwner = stationStore.connect( + satellitesLayer.getStationActions(), + ); + this._stationPanelUnsubscribe = satellitesLayer?.subscribeStationPanel?.( + (view) => stationStore.publish(view), + ); + // The LIVE section: streams attached to whatever the tracking layers + // select, in the platform's own player, loaded only once Play is pressed. + this._liveControls?.destroy(); + const liveStore = useLiveStore(applicationPinia()); + this._liveControls = new LiveControls({ + store: liveStore, + actions: { + getLayer: (layerId) => + this._dataManager?.layers?.get(layerId)?.module ?? null, + scheduleLayout: () => this._scheduleRightPanelLayout(), + }, + }); + // The Cockpit briefing offers its LIVE page while a stream is on offer. + this._liveOfferedUnwatch?.(); + this._liveOfferedUnwatch = watch( + () => liveStore.view !== null, + (offered) => this.cockpitView?.setBriefLiveOffered?.(offered), + { immediate: true }, + ); } _initSpaceMissionsPanel() { @@ -1975,6 +2015,14 @@ export class StyleManager extends ShellFacade { this.services?.streetLevelLayer?.attachNavigation?.(null); this._streetLevelControls?.destroy(); this._radioControls?.destroy(); + this._liveControls?.destroy(); + this._liveOfferedUnwatch?.(); + this._liveOfferedUnwatch = null; + this._stationPanelUnsubscribe?.(); + this._stationPanelUnsubscribe = null; + if (this._stationOwner) + useStationStore(applicationPinia()).detach(this._stationOwner); + this._stationOwner = null; this._localSdrControls?.destroy(); this._awarenessPanelUnsubscribe?.(); this._awarenessPanelUnsubscribe = null; diff --git a/src/ui/cockpitBriefPages.js b/src/ui/cockpitBriefPages.js index 9f75c83d8f..3303ca99e8 100644 --- a/src/ui/cockpitBriefPages.js +++ b/src/ui/cockpitBriefPages.js @@ -46,6 +46,48 @@ export const COCKPIT_BRIEF_PAGES = [ }, ]; +/** + * The fourth page, LIVE: the ridden subject's live video, the LIVE section + * of Context in the card. Offered only while a stream is on offer (the + * `gev-live` store's view is not null); the automatic cycle never turns to it. + */ +export const COCKPIT_LIVE_BRIEF_PAGE = Object.freeze({ + id: 'live', + kickerKey: msg('LIVE VIDEO'), + subtitleKey: msg('STREAM ATTACHED TO THE SUBJECT'), + // Attribution stays English; the page itself credits the stream's owner. + source: 'YOUTUBE EMBEDDED PLAYER · MUTED', +}); + +/** + * The pages on offer: the three fixed ones, and LIVE after them while the + * ridden subject has a stream. + * @param {boolean} liveOffered + * @returns {readonly object[]} + */ +export function cockpitBriefPages(liveOffered) { + return liveOffered + ? [...COCKPIT_BRIEF_PAGES, COCKPIT_LIVE_BRIEF_PAGE] + : COCKPIT_BRIEF_PAGES; +} + +/** + * Where the automatic cycle goes from the page at `index`: the next page + * that is not LIVE (video is never started by the cycle), wrapping; null + * while LIVE is the shown page, where the cycle waits as it does under the + * pointer. + * @param {readonly object[]} pages + * @param {number} index + * @returns {number|null} + */ +export function briefCycleTarget(pages, index) { + if (pages[index]?.id === 'live') return null; + const count = pages.length; + let next = (index + 1) % count; + if (pages[next]?.id === 'live') next = (next + 1) % count; + return next; +} + // The cycle toggle's tooltip, as literal keys for the extractor. export const CYCLE_HELP_KEYS = Object.freeze({ on: msg( diff --git a/src/ui/cockpitBriefing.js b/src/ui/cockpitBriefing.js index 85678ad1fa..c0561daea8 100644 --- a/src/ui/cockpitBriefing.js +++ b/src/ui/cockpitBriefing.js @@ -9,8 +9,9 @@ import { formatCockpitWindDirection, } from './cockpitPresentation.js'; import { - COCKPIT_BRIEF_PAGES, CYCLE_HELP_KEYS, + briefCycleTarget, + cockpitBriefPages, createBriefState, newsWindowFooter, } from './cockpitBriefPages.js'; @@ -48,11 +49,17 @@ export function publishBriefView() { }); } +/** The pages on offer now: three, or four with LIVE while a stream is. */ +function briefPages() { + return cockpitBriefPages(this.briefLiveOffered === true); +} + export function showBriefPage(index, { manual = false } = {}) { if (this.destroyed) return; - const count = COCKPIT_BRIEF_PAGES.length; + const pages = briefPages.call(this); + const count = pages.length; this.briefPageIndex = ((Number(index) % count) + count) % count; - const page = COCKPIT_BRIEF_PAGES[this.briefPageIndex]; + const page = pages[this.briefPageIndex]; Object.assign(this.brief, { pageIndex: this.briefPageIndex, pageId: page.id, @@ -101,6 +108,20 @@ export function relocalizeBrief() { this.renderRegionalBriefStatus(this.brief.news.state, this.lastSubjectInfo); } +/** + * Offer or withdraw the LIVE page, as the ridden subject's stream comes and + * goes. A LIVE page shown as its stream goes falls back to Live Signals; + * otherwise the shown page stays and its position counts the pages anew. + */ +export function setBriefLiveOffered(offered) { + if (this.destroyed) return; + const next = offered === true; + if (next === this.briefLiveOffered) return; + this.briefLiveOffered = next; + const count = cockpitBriefPages(next).length; + this.showBriefPage(this.briefPageIndex < count ? this.briefPageIndex : 0); +} + export function setBriefAutoRotate(enabled) { if (this.destroyed) return; this.briefAutoRotateEnabled = Boolean(enabled); @@ -129,7 +150,13 @@ export function startBriefRotation({ reset = false } = {}) { this.signalStream?.contains(document.activeElement) === true; const isInteracting = hasPointer || hasFocus; if (!isInteracting) { - this.showBriefPage(this.briefPageIndex + 1); + // The cycle never turns to the LIVE page, and waits while it is shown: + // video starts and stops on request only. + const target = briefCycleTarget( + briefPages.call(this), + this.briefPageIndex, + ); + if (target !== null) this.showBriefPage(target); } this.startBriefRotation(); }, COCKPIT_BRIEF_ROTATE_MS); diff --git a/src/ui/cockpitBriefing.test.mjs b/src/ui/cockpitBriefing.test.mjs index 78f2cbdaeb..3f9423af14 100644 --- a/src/ui/cockpitBriefing.test.mjs +++ b/src/ui/cockpitBriefing.test.mjs @@ -8,18 +8,24 @@ import { fileURLToPath } from 'node:url'; import { createPinia } from 'pinia'; import { createApp, nextTick } from 'vue'; import { setLocale } from '../i18n/index.js'; -import { createBriefState } from './cockpitBriefPages.js'; +import { + briefCycleTarget, + cockpitBriefPages, + createBriefState, +} from './cockpitBriefPages.js'; import { maybeRefreshRegionalBrief, publishBriefView, renderRegionalBrief, renderRegionalBriefStatus, setBriefAutoRotate, + setBriefLiveOffered, showBriefPage, updateLocalPosition, } from './cockpitBriefing.js'; import { setSignalCollapsed } from './cockpitLayout.js'; import { useCockpitStore } from './stores/cockpit.js'; +import { useLiveStore } from './stores/live.js'; import CockpitBriefing from './views/panels/CockpitBriefing.vue'; function fixture(t) { @@ -35,9 +41,11 @@ function fixture(t) { destroyed: false, briefPageIndex: 0, briefAutoRotateEnabled: false, + briefLiveOffered: false, brief: createBriefState(), publishBrief: (view) => store.publishBrief(view), publishBriefView, + showBriefPage, scheduleContextLayout() {}, startBriefRotation() {}, stopBriefRotation() {}, @@ -49,11 +57,50 @@ function fixture(t) { [...document.querySelectorAll('[data-cockpit-brief-page]')] .filter((page) => !page.hidden) .map((page) => page.dataset.cockpitBriefPage); + // The tabs on offer: the LIVE tab is in the markup but hidden without a stream. const current = () => - [...document.querySelectorAll('[data-cockpit-brief-index]')].map((tab) => - tab.getAttribute('aria-current'), + [...document.querySelectorAll('[data-cockpit-brief-index]')] + .filter((tab) => !tab.hidden) + .map((tab) => tab.getAttribute('aria-current')); + // A stream on offer for the ridden subject, as LiveControls publishes it; + // the briefing then offers its LIVE page. + const liveStore = useLiveStore(pinia); + const liveActed = []; + liveStore.connect({ + cycleLive: (direction) => liveActed.push(['cycle', direction]), + playLive: () => liveActed.push(['play']), + stopLive: () => liveActed.push(['stop']), + retryLive: () => liveActed.push(['retry']), + hideLive: (where) => liveActed.push(['hide', where]), + }); + const offerLive = async (view) => { + liveStore.publish( + view && { + label: 'ISS (ZARYA)', + streams: [ + { id: 'iss-exterior', title: 'Exterior cameras', owner: 'NASA' }, + { id: 'iss-crew', title: 'Live video and audio', owner: 'NASA' }, + ], + index: 0, + count: 2, + current: { + id: 'iss-exterior', + title: 'Exterior cameras', + owner: 'NASA', + ownerUrl: 'https://www.youtube.com/@NASA', + note: 'NASA video, via YouTube', + watchUrl: 'https://www.youtube.com/watch?v=ROboUHfPUrU', + }, + state: 'idle', + reason: null, + ...view, + }, ); - return { $, text, owner, visiblePages, current }; + setBriefLiveOffered.call(owner, view !== null); + await nextTick(); + await nextTick(); + }; + return { $, text, owner, visiblePages, current, offerLive, liveActed }; } const INFO = { latitude: 30.25, longitude: -97.75 }; @@ -111,6 +158,157 @@ test('pages, the cycle toggle and the source follow the controller', async (t) = assert.match(auto.title, /^Stop automatic page cycling/); }); +test('without a stream the briefing keeps its three pages and hides the LIVE tab', async (t) => { + const { $, text, owner, visiblePages } = fixture(t); + const liveTab = $('[data-cockpit-brief-index="3"]'); + assert.equal(liveTab.hidden, true); + assert.equal(liveTab.textContent, 'LIVE'); + assert.equal(liveTab.getAttribute('aria-label'), 'Show Live Video'); + assert.equal( + $('[data-cockpit-brief-page="live"]').querySelector('*'), + null, + 'no page body without a stream', + ); + // Next from Local wraps to Live Signals, past the page not on offer. + showBriefPage.call(owner, 3); + await nextTick(); + assert.deepEqual(visiblePages(), ['signals']); + assert.equal(text('#cockpit-brief-position'), '1 / 3'); +}); + +test('with a stream the LIVE page is the fourth, reached by the arrows and its tab', async (t) => { + const { $, text, owner, visiblePages, current, offerLive } = fixture(t); + await offerLive({}); + assert.equal(text('#cockpit-brief-position'), '1 / 4'); + const liveTab = $('[data-cockpit-brief-index="3"]'); + assert.equal(liveTab.hidden, false); + assert.deepEqual(current(), ['true', 'false', 'false', 'false']); + showBriefPage.call(owner, 2); + showBriefPage.call(owner, owner.briefPageIndex + 1); + await nextTick(); + assert.deepEqual(visiblePages(), ['live']); + assert.deepEqual(current(), ['false', 'false', 'false', 'true']); + assert.equal(text('#cockpit-brief-kicker'), 'LIVE VIDEO'); + assert.equal( + text('#cockpit-brief-subtitle'), + 'STREAM ATTACHED TO THE SUBJECT', + ); + assert.equal(text('#cockpit-brief-position'), '4 / 4'); + assert.equal( + text('#cockpit-brief-source'), + 'YOUTUBE EMBEDDED PLAYER · MUTED', + ); + assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'live'); + // The page shows what the LIVE section shows, with the player's own screen. + const page = $('[data-cockpit-brief-page="live"]'); + assert.equal( + page.querySelector('.cockpit-live-subject strong').textContent, + 'ISS (ZARYA)', + ); + assert.equal(text('#cockpit-live-stream-title'), 'Exterior cameras · 1/2'); + assert.ok($('#cockpit-live-player-host')); + assert.ok($('#cockpit-live-previous')); + assert.ok($('#cockpit-live-next')); + assert.equal(text('#cockpit-live-badge-text'), 'OFF'); + assert.equal(text('#cockpit-live-status'), 'Click to play'); + assert.ok($('#cockpit-live-play'), 'Play, under the IP notice'); + assert.match( + page.querySelector('.cockpit-live-privacy').textContent, + /sees your IP address/, + ); + assert.equal( + $('#cockpit-live-watch-link').getAttribute('href'), + 'https://www.youtube.com/watch?v=ROboUHfPUrU', + ); + // Next from LIVE wraps to Live Signals. + showBriefPage.call(owner, owner.briefPageIndex + 1); + await nextTick(); + assert.deepEqual(visiblePages(), ['signals']); + assert.equal(text('#cockpit-brief-position'), '1 / 4'); +}); + +test('the LIVE page loads the stream only on Play, stops it when left, and its controls reach LiveControls', async (t) => { + const { $, owner, offerLive, liveActed } = fixture(t); + await offerLive({}); + assert.deepEqual(liveActed, [], 'riding the station loads no player'); + showBriefPage.call(owner, 3); + await nextTick(); + $('#cockpit-live-play').click(); + assert.deepEqual(liveActed, [['play']]); + await offerLive({ state: 'playing' }); + const page = $('[data-cockpit-brief-page="live"]'); + assert.equal($('#cockpit-live-badge-text').textContent, 'ON AIR'); + assert.equal( + page.querySelector('.live-dot').classList.contains('on-air'), + true, + ); + assert.equal( + page.querySelector('.live-screen').classList.contains('active'), + true, + ); + assert.equal($('#cockpit-live-status').textContent, 'Live'); + $('#cockpit-live-next').click(); + $('#cockpit-live-previous').click(); + assert.deepEqual(liveActed, [['play'], ['cycle', 1], ['cycle', -1]]); + // Leaving the page stops what plays there. + showBriefPage.call(owner, 0); + await nextTick(); + assert.deepEqual(liveActed.at(-1), ['hide', 'cockpit']); + showBriefPage.call(owner, 3); + await nextTick(); + await offerLive({ state: 'offline', reason: 'timeout' }); + const card = page.querySelector('.live-card'); + assert.equal(card.classList.contains('offline'), true); + assert.equal(card.querySelector('strong').textContent, 'Stream is offline'); + $('#cockpit-live-retry').click(); + assert.deepEqual(liveActed.at(-1), ['retry']); + await offerLive({ state: 'unavailable', reason: 'error-150' }); + assert.equal($('#cockpit-live-retry'), null); + assert.equal( + $('#cockpit-live-status').textContent, + 'This stream cannot play here', + ); +}); + +test('the stream going while LIVE is shown falls back to Live Signals with three pages', async (t) => { + const { $, text, owner, visiblePages, offerLive } = fixture(t); + await offerLive({}); + showBriefPage.call(owner, 3); + await nextTick(); + assert.deepEqual(visiblePages(), ['live']); + await offerLive(null); + assert.deepEqual(visiblePages(), ['signals']); + assert.equal(text('#cockpit-brief-position'), '1 / 3'); + assert.equal($('[data-cockpit-brief-index="3"]').hidden, true); + // Going on another page, the page stays and only the count changes. + showBriefPage.call(owner, 1); + await offerLive({}); + assert.deepEqual(visiblePages(), ['news']); + assert.equal(text('#cockpit-brief-position'), '2 / 4'); + // Offering what is already offered changes nothing. + const views = []; + owner.publishBrief = (view) => views.push(view); + setBriefLiveOffered.call(owner, true); + assert.equal(views.length, 0); +}); + +test('the automatic cycle never turns to the LIVE page and waits while it is shown', () => { + const three = cockpitBriefPages(false); + assert.deepEqual( + [0, 1, 2].map((index) => briefCycleTarget(three, index)), + [1, 2, 0], + ); + const four = cockpitBriefPages(true); + assert.equal(four.length, 4); + assert.equal(four[3].id, 'live'); + assert.deepEqual( + [0, 1, 2].map((index) => briefCycleTarget(four, index)), + [1, 2, 0], + 'Local goes back to Live Signals, past LIVE', + ); + assert.equal(briefCycleTarget(four, 3), null, 'shown by hand, LIVE stays'); +}); + test('regional news and local conditions render what the region returned', async (t) => { const { $, text, owner } = fixture(t); renderRegionalBriefStatus.call(owner, 'loading', INFO); diff --git a/src/ui/cockpitController.js b/src/ui/cockpitController.js index 6bdd97f5f0..d7af6fc036 100644 --- a/src/ui/cockpitController.js +++ b/src/ui/cockpitController.js @@ -26,10 +26,12 @@ import { import { update } from './cockpitCamera.js'; import { beginOrbital, + orbitalViewSignal, endOrbital, resetOrbitalLook, jumpToSensorSwath, onOrbitalWheel, + stepOrbitalMount, stepOrbitalZoom, turnOrbitalLook, updateOrbital, @@ -77,6 +79,7 @@ import { publishBriefView, showBriefPage, setBriefAutoRotate, + setBriefLiveOffered, startBriefRotation, stopBriefRotation, updateLocalPosition, @@ -273,6 +276,8 @@ export class CockpitViewController { this.signalSignatures = new Map(); this.briefPageIndex = 0; this.briefAutoRotateEnabled = false; + /** Whether the briefing offers its LIVE page (the subject has a stream). */ + this.briefLiveOffered = false; // Cockpit's views render what these receive. this.publishPresence = publish.presence ?? (() => {}); this.publishBrief = publish.brief ?? (() => {}); @@ -403,6 +408,10 @@ export class CockpitViewController { else if (target?.closest?.('#cockpit-orbital-zoom-out')) this.stepOrbitalZoom(-1); else if (target?.closest?.('#cockpit-orbital-nadir')) this.orbitalNadir(); + else if (target?.closest?.('#cockpit-orbital-view-next')) + this.nextOrbitalView(); + else if (target?.closest?.('#cockpit-orbital-view-previous')) + this.previousOrbitalView(); else if (target?.closest?.('#cockpit-orbital-sensor')) this.jumpToSensorSwath(); }); @@ -456,6 +465,26 @@ export class CockpitViewController { beginOrbital() { return beginOrbital.call(this); } + + orbitalViewSignal(info) { + return orbitalViewSignal.call(this, info); + } + + /** + * The station view's right arrow: step to the station's next view. + * @returns {boolean} True when the view changed. + */ + nextOrbitalView() { + return stepOrbitalMount.call(this, 1); + } + + /** + * The station view's left arrow: step back to the view before. + * @returns {boolean} True when the view changed. + */ + previousOrbitalView() { + return stepOrbitalMount.call(this, -1); + } endOrbital() { return endOrbital.call(this); } @@ -713,6 +742,9 @@ export class CockpitViewController { setBriefAutoRotate(enabled) { return setBriefAutoRotate.call(this, enabled); } + setBriefLiveOffered(offered) { + return setBriefLiveOffered.call(this, offered); + } startBriefRotation(options) { return startBriefRotation.call(this, options); } diff --git a/src/ui/cockpitOrbitalFocus.js b/src/ui/cockpitOrbitalFocus.js index a7790ab102..e921ffd36d 100644 --- a/src/ui/cockpitOrbitalFocus.js +++ b/src/ui/cockpitOrbitalFocus.js @@ -116,8 +116,19 @@ function sitePosition(site) { : null; } -/** The mapped site a canvas position shows, through the layer's picks. */ +/** + * The mapped site a canvas position shows: through the layer's own lookup + * where it has one (`findAt`: the dot, the site entity or the label box the + * overlay paints, which is what a click lands on from orbit), else through + * its pick ids. + */ function siteAt(controller, position) { + try { + const found = sitesLayer(controller)?.findAt?.(position) ?? null; + if (found) return found; + } catch { + // Fall through to the pick ids. + } let picked = null; try { picked = findQuery(controller.viewer)?.pick(position.x, position.y) ?? null; @@ -289,8 +300,9 @@ export function routeSceneClick() { } return input.onClick((event) => { // Another layer's card or label painted on top takes the click: the site - // under it does not focus, and the click does not end a held focus. - if (isUnderOtherCard(event)) return; + // under it does not focus, and the click does not end a held focus. A + // site's own label is not another layer's: it focuses that site. + if (isUnderOtherCard(event, [SITES_LAYER_ID])) return; this.onOrbitalClick(event?.position); }); } @@ -303,15 +315,26 @@ export function routeSceneClick() { * held from its last record). Also rebuilds * the orbital Live Signals rows on their own clock. * @param {object} state The orbital session. - * @param {{direction: object, up: object, right: object}} nadir This - * frame's nadir frame. - * @param {{x: number, y: number, z: number}} position The satellite, ECEF. + * @param {{direction: object, up: object, right: object}} nadir The frame + * the look turns about this frame: the nadir one, or a station view's. + * @param {{x: number, y: number, z: number}} position Where the camera is, + * ECEF: the satellite, or the station view's point on it. * @param {number} nowMs + * @param {{direction: object, up: object, right: object}|null} [trueNadir] + * The nadir frame when `nadir` is a station view's: the rows still word + * their angles from straight down. * @returns {boolean} True when it placed `state.lookView` itself. */ -export function updateOrbitalFocus(state, nadir, position, nowMs) { +export function updateOrbitalFocus( + state, + nadir, + position, + nowMs, + trueNadir = null, +) { state.focusFrame = { nadir, + trueNadir, position: { x: position.x, y: position.y, z: position.z }, }; // After a satellite switch the first frame on the new satellite (the hop @@ -465,13 +488,21 @@ export function orbitalSitesInReach(info) { }); state.listedSites = remembered; const focusKey = state.focus?.key ?? null; + const positions = new Map(candidates.map((c) => [c.key, c.position])); + // Reach is measured about the frame the look turns in; the angle shown + // is always from straight down, also from a station view. + const shownOffNadir = (key, offNadirDeg) => { + if (!frame.trueNadir) return offNadirDeg; + const look = focusLook(frame.trueNadir, frame.position, positions.get(key)); + return Number.isFinite(look?.offNadirDeg) ? look.offNadirDeg : offNadirDeg; + }; return { entries: pointsInReach(candidates, { nadir: frame.nadir, satellite: frame.position, }).map(({ key, offNadirDeg }) => ({ site: byId.get(key), - offNadirDeg, + offNadirDeg: shownOffNadir(key, offNadirDeg), focused: key === focusKey, })), }; diff --git a/src/ui/cockpitOrbitalFocus.test.mjs b/src/ui/cockpitOrbitalFocus.test.mjs index 0677ec1f98..45c873fb37 100644 --- a/src/ui/cockpitOrbitalFocus.test.mjs +++ b/src/ui/cockpitOrbitalFocus.test.mjs @@ -41,10 +41,34 @@ const FRAME_MS = 16; /** Satellites the layer knows, by NORAD id: the ridden one and its neighbours. */ const SATELLITES = Object.freeze({ - 25544: { name: 'ISS (ZARYA)', lat: 30, lon: -97, alt: 420_000, cls: 'stations' }, - 49260: { name: 'LANDSAT 9', lat: 31.5, lon: -95, alt: 705_000, cls: 'imaging' }, - 40697: { name: 'SENTINEL-2A', lat: 26, lon: -99, alt: 786_000, cls: 'imaging' }, - 99001: { name: 'DEB FRAGMENT', lat: 30.2, lon: -97.1, alt: 430_000, cls: 'debris' }, + 25544: { + name: 'ISS (ZARYA)', + lat: 30, + lon: -97, + alt: 420_000, + cls: 'stations', + }, + 49260: { + name: 'LANDSAT 9', + lat: 31.5, + lon: -95, + alt: 705_000, + cls: 'imaging', + }, + 40697: { + name: 'SENTINEL-2A', + lat: 26, + lon: -99, + alt: 786_000, + cls: 'imaging', + }, + 99001: { + name: 'DEB FRAGMENT', + lat: 30.2, + lon: -97.1, + alt: 430_000, + cls: 'debris', + }, }); /** Mapped sites as the installations layer keeps them. */ @@ -58,6 +82,8 @@ const SITES = Object.freeze({ lon: -96.5, memberNames: ['North Field'], at: { x: 100, y: 100 }, + // Where the overlay paints its label box: nothing picks there. + labelAt: { x: 140, y: 70 }, }, bravo: { id: 'osm:military:way/202', @@ -102,7 +128,11 @@ function installationsLayer() { withPosition(record) { return { ...record, - position: Cesium.Cartesian3.fromDegrees(record.longitude, record.latitude, 0), + position: Cesium.Cartesian3.fromDegrees( + record.longitude, + record.latitude, + 0, + ), }; }, // As the layer's own: loaded installations within `rangeM` of @@ -119,7 +149,10 @@ function installationsLayer() { from, Cesium.Cartographic.fromDegrees(record.longitude, record.latitude), ); - return { ...layer.withPosition(record), distanceM: geodesic.surfaceDistance }; + return { + ...layer.withPosition(record), + distanceM: geodesic.surfaceDistance, + }; }) .filter((record) => record.distanceM <= rangeM) .sort((a, b) => a.distanceM - b.distanceM) @@ -135,6 +168,17 @@ function installationsLayer() { const id = hit?.meta?.installationId ?? null; return id ? layer.getById(id) : null; }, + // As the layer's: the label box the overlay paints, where no primitive + // picks (the dot is left to the pick ids here). + findAt(position) { + const site = Object.values(SITES).find( + (s) => + s.labelAt && + s.labelAt.x === position?.x && + s.labelAt.y === position?.y, + ); + return site ? layer.getById(site.id) : null; + }, }; return layer; } @@ -192,7 +236,11 @@ function satellitesLayer(viewer) { }, // As the layer's: the nearest shown satellites, bounded, with the // asked-for ids and classes left out. - getNearestPositions(center, maxCount = 8, { excludeIds = [], excludeClasses = [] } = {}) { + getNearestPositions( + center, + maxCount = 8, + { excludeIds = [], excludeClasses = [] } = {}, + ) { layer.calls.push(['nearest']); const skip = new Set(excludeIds.map(String)); return layer @@ -216,7 +264,9 @@ function satellitesLayer(viewer) { if (!positions.has(id)) return false; layer.calls.push(['track', id]); layer.tracked = id; - followEntity(viewer, { position: { getValue: () => layer.position(id) } }); + followEntity(viewer, { + position: { getValue: () => layer.position(id) }, + }); return true; }, setCockpitSubject(noradId) { @@ -236,7 +286,11 @@ function fixture(t, { reducedMotion = false } = {}) { const host = document.body.appendChild(document.createElement('div')); const pinia = createPinia(); const app = createApp( - defineComponent(() => () => [h(ContextView), h(IntelHudView), h(CockpitView)]), + defineComponent(() => () => [ + h(ContextView), + h(IntelHudView), + h(CockpitView), + ]), ).use(pinia); app.mount(host); useHudStore(pinia); @@ -278,7 +332,10 @@ function fixture(t, { reducedMotion = false } = {}) { handler.stockDouble = ({ position }) => { handler.stockDoubleClicks += 1; const picked = picks.get(`${position.x},${position.y}`); - followEntity(viewer, picked ? { position: { getValue: () => null } } : null); + followEntity( + viewer, + picked ? { position: { getValue: () => null } } : null, + ); }; // The viewer's stock handler holds them, so the scene's input has them to // hold off. @@ -376,7 +433,11 @@ function fixture(t, { reducedMotion = false } = {}) { globalThis.matchMedia = previousMatchMedia; performance.now = originalNow; Date.now = originalDateNow; - document.body.classList.remove('cockpit-mode', 'cockpit-bridge', 'cockpit-orbit'); + document.body.classList.remove( + 'cockpit-mode', + 'cockpit-bridge', + 'cockpit-orbit', + ); }); const frame = () => { @@ -456,7 +517,10 @@ function missDeg(shot, key) { /** The camera's angle from nadir, degrees. */ function offNadir(shot) { - const toCentre = Cesium.Cartesian3.negate(shot.destination, new Cesium.Cartesian3()); + const toCentre = Cesium.Cartesian3.negate( + shot.destination, + new Cesium.Cartesian3(), + ); return angleDeg(shot.direction, toCentre); } @@ -467,7 +531,10 @@ function siteOffNadir(shot, key) { shot.destination, new Cesium.Cartesian3(), ); - const toCentre = Cesium.Cartesian3.negate(shot.destination, new Cesium.Cartesian3()); + const toCentre = Cesium.Cartesian3.negate( + shot.destination, + new Cesium.Cartesian3(), + ); return angleDeg(line, toCentre); } @@ -522,7 +589,9 @@ test('in orbit Live Signals lists the sites getNearby finds and the nearest sate assert.ok(shown.length <= 5, 'five rows at most'); assert.equal(shown[0].title, 'TRACK ACQUIRED', 'the track row stays first'); // Two site rows, nearest to nadir first, then the satellites (debris out). - const sitesShown = shown.filter((row) => row.target?.layerId === 'military-installations'); + const sitesShown = shown.filter( + (row) => row.target?.layerId === 'military-installations', + ); assert.deepEqual( sitesShown.map((row) => row.target.id).sort(), [SITES.alpha.id, SITES.bravo.id].sort(), @@ -531,16 +600,33 @@ test('in orbit Live Signals lists the sites getNearby finds and the nearest sate assert.match(row.detail, /^(BASE|AIRFIELD) · OFF-NADIR \d+\.\d°$/); assert.match(row.className, /nearby actionable/); } - const satellitesShown = shown.filter((row) => row.target?.layerId === 'satellites'); - assert.deepEqual(satellitesShown.map((row) => row.title), ['LANDSAT 9', 'SENTINEL-2A']); - assert.match(satellitesShown[0].detail, /^SATELLITE · (AHEAD|[LR] \d{3}°) · [\d,.]+\s+KM$/); + const satellitesShown = shown.filter( + (row) => row.target?.layerId === 'satellites', + ); + assert.deepEqual( + satellitesShown.map((row) => row.title), + ['LANDSAT 9', 'SENTINEL-2A'], + ); + assert.match( + satellitesShown[0].detail, + /^SATELLITE · (AHEAD|[LR] \d{3}°) · [\d,.]+\s+KM$/, + ); // Each row names its own action. - assert.equal(siteRow(scene, 'alpha').getAttribute('aria-label'), 'Keep the camera on Camp Alpha'); - assert.equal(satelliteRow(scene, 49260).getAttribute('aria-label'), 'Ride LANDSAT 9'); + assert.equal( + siteRow(scene, 'alpha').getAttribute('aria-label'), + 'Keep the camera on Camp Alpha', + ); + assert.equal( + satelliteRow(scene, 49260).getAttribute('aria-label'), + 'Ride LANDSAT 9', + ); // Rebuilt on the clock, rows keep their keys and times. const before = shown.map((row) => [row.key, row.time]); await refreshRows(scene); - assert.deepEqual(rows(scene).map((row) => [row.key, row.time]), before); + assert.deepEqual( + rows(scene).map((row) => [row.key, row.time]), + before, + ); }); test('a site row turns the camera onto it, holds it, and reads its off-nadir angle', async (t) => { @@ -552,11 +638,17 @@ test('a site row turns the camera onto it, holds it, and reads its off-nadir ang // The first frames turn part of the way: no jump onto the site. assert.ok(missDeg(scene.frame(), 'alpha') > 5, 'still turning'); const largest = run(scene, LAND_FRAMES); - assert.ok(largest > 0.1 && largest < MAX_TURN_PER_FRAME_DEG, `turned ${largest}° in a frame`); + assert.ok( + largest > 0.1 && largest < MAX_TURN_PER_FRAME_DEG, + `turned ${largest}° in a frame`, + ); for (let i = 0; i < 20; i += 1) { scene.satellites.move(0.002, 0.002); const shot = scene.frame(); - assert.ok(missDeg(shot, 'alpha') < 1e-5, `frame ${i}: ${missDeg(shot, 'alpha')}°`); + assert.ok( + missDeg(shot, 'alpha') < 1e-5, + `frame ${i}: ${missDeg(shot, 'alpha')}°`, + ); } for (let i = 0; i < 8; i += 1) scene.frame(); await settle(); @@ -566,14 +658,20 @@ test('a site row turns the camera onto it, holds it, and reads its off-nadir ang `OFF-NADIR ${siteOffNadir(shot, 'alpha').toFixed(1)}°`, ); assert.equal($('#cockpit-orbital-focus').textContent, 'FOCUS · Camp Alpha'); - assert.equal($('#cockpit-orbital-look-readout').getAttribute('aria-live'), 'off'); + assert.equal( + $('#cockpit-orbital-look-readout').getAttribute('aria-live'), + 'off', + ); assert.equal(store.orbital.footprintKm, null); assert.match($('.cockpit-orbital-swath').textContent, /^SWATH ≈ [\d.]+ KM$/); // The held site's row reads as the subject does, first among the sites. const held = rows(scene).find((row) => row.target?.id === SITES.alpha.id); assert.match(held.className, /^track actionable$/); assert.match(held.detail, /^FOCUS · BASE · OFF-NADIR/); - assert.equal(siteRow(scene, 'alpha').getAttribute('aria-label'), 'Release the camera from Camp Alpha'); + assert.equal( + siteRow(scene, 'alpha').getAttribute('aria-label'), + 'Release the camera from Camp Alpha', + ); // The held site's FOCUS is a status, worded apart from the FOCUS command. t.after(() => setLocale('en')); setLocale('es'); @@ -600,7 +698,10 @@ test('another site row switches the focus; the held site row ends it', async (t) assert.ok(largest < MAX_TURN_PER_FRAME_DEG, `turned ${largest}° in a frame`); assert.ok(missDeg(scene.shots.at(-1), 'bravo') < 1e-5); await settle(); - assert.match(rows(scene).find((row) => row.target?.id === SITES.alpha.id).className, /^nearby/); + assert.match( + rows(scene).find((row) => row.target?.id === SITES.alpha.id).className, + /^nearby/, + ); siteRow(scene, 'bravo').click(); assert.equal(cockpit.orbital.focus, null); const back = run(scene, LAND_FRAMES, { drift: 0 }); @@ -617,7 +718,11 @@ test('a click on a site marker focuses it through the layer; a click elsewhere e run(scene, LAND_FRAMES); assert.ok(missDeg(scene.shots.at(-1), 'alpha') < 1e-5); scene.click(SITES.alpha.at); - assert.equal(cockpit.orbital.focus.key, SITES.alpha.id, 'kept on a second click'); + assert.equal( + cockpit.orbital.focus.key, + SITES.alpha.id, + 'kept on a second click', + ); const focused = offNadir(scene.shots.at(-1)); scene.click(EMPTY_GROUND); assert.equal(cockpit.orbital.focus, null); @@ -640,18 +745,26 @@ test('a click a tool owns is left alone', async (t) => { const lease = claimPointer('draw'); t.after(() => releasePointer(lease)); scene.click(SITES.alpha.at); - assert.equal(scene.cockpit.orbital.focus ?? null, null, 'no focus while drawing'); + assert.equal( + scene.cockpit.orbital.focus ?? null, + null, + 'no focus while drawing', + ); releasePointer(lease); scene.click(SITES.alpha.at); const again = claimPointer('draw'); t.after(() => releasePointer(again)); scene.click(EMPTY_GROUND); - assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing'); + assert.equal( + scene.cockpit.orbital.focus.key, + SITES.alpha.id, + 'kept while drawing', + ); }); // The card or label painted on top takes the click: a site under another // layer's card does not focus, and a click there does not end a held focus. -test('another layer\'s card over the orbital view keeps the click', async (t) => { +test("another layer's card over the orbital view keeps the click", async (t) => { const scene = await inOrbit(t); let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }; setClickCardHitTest(() => top); @@ -663,7 +776,11 @@ test('another layer\'s card over the orbital view keeps the click', async (t) => assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id); top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }; scene.click(EMPTY_GROUND); - assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept'); + assert.equal( + scene.cockpit.orbital.focus.key, + SITES.alpha.id, + 'covered: kept', + ); }); test('a double-click on a site focuses it and keeps the orbital view', async (t) => { @@ -678,7 +795,11 @@ test('a double-click on a site focuses it and keeps the orbital view', async (t) scene.doubleClick(SITES.bravo.at); assert.equal(cockpit.orbital.focus.key, SITES.bravo.id); scene.doubleClick(SITES.far.at); - assert.equal(handler.stockDoubleClicks, 0, 'beyond reach: not focused, not tracked'); + assert.equal( + handler.stockDoubleClicks, + 0, + 'beyond reach: not focused, not tracked', + ); scene.frame(); assert.equal(cockpit.active, true); scene.doubleClick(EMPTY_GROUND); @@ -720,8 +841,15 @@ test('turning the layer off ends the focus and says why; a reload around the sit assert.ok(status, 'a status row says why no site is listed'); assert.equal(status.detail, 'ENABLE MAPPED INSTALLATIONS FOR SITE PINGS'); assert.equal(status.className, 'warning'); - assert.ok(!rows(scene).some((row) => row.target?.layerId === 'military-installations')); - assert.equal(rows(scene).filter((row) => row.target?.layerId === 'satellites').length, 2); + assert.ok( + !rows(scene).some( + (row) => row.target?.layerId === 'military-installations', + ), + ); + assert.equal( + rows(scene).filter((row) => row.target?.layerId === 'satellites').length, + 2, + ); scene.sites.enabled = true; await refreshRows(scene); assert.ok(!rows(scene).some((row) => row.title === 'SITES STANDBY')); @@ -732,7 +860,11 @@ test('turning the layer off ends the focus and says why; a reload around the sit const loaded = scene.sites.records; scene.sites.records = loaded.filter((r) => r.id !== SITES.bravo.id); run(scene, 10); - assert.equal(scene.cockpit.orbital.focus.key, SITES.bravo.id, 'kept through a reload'); + assert.equal( + scene.cockpit.orbital.focus.key, + SITES.bravo.id, + 'kept through a reload', + ); assert.ok(missDeg(scene.shots.at(-1), 'bravo') < 1e-5, 'still centred'); scene.sites.records = loaded; // A row the list shows works even if the layer just dropped its site. @@ -745,7 +877,10 @@ test('turning the layer off ends the focus and says why; a reload around the sit test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) => { const scene = await inOrbit(t); const { cockpit, satellites, viewer, modeEvents } = scene; - assert.ok(!rows(scene).some((row) => row.title.startsWith('RETURN')), 'no history yet'); + assert.ok( + !rows(scene).some((row) => row.title.startsWith('RETURN')), + 'no history yet', + ); siteRow(scene, 'alpha').click(); run(scene, 5); const before = Cesium.Cartesian3.clone(scene.shots.at(-1).destination); @@ -755,21 +890,36 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) = satelliteRow(scene, 49260).click(); const newTrack = cockpit.signalItems.filter((item) => item.key === 'track'); assert.equal(newTrack.length, 1); - assert.ok(newTrack[0].timestamp > firstTrack.timestamp, 'the new ride’s own time'); - assert.deepEqual(satellites.calls.slice(-2), [['track', 49260], ['subject', 49260]]); + assert.ok( + newTrack[0].timestamp > firstTrack.timestamp, + 'the new ride’s own time', + ); + assert.deepEqual(satellites.calls.slice(-2), [ + ['track', 49260], + ['subject', 49260], + ]); assert.equal(followedOf(viewer), null, 'the Cockpit keeps the camera'); assert.equal(cockpit.subjectId, 49260); assert.equal(cockpit.orbital.focus, null, 'the focus is reset'); assert.equal(modeEvents.at(-1)?.active, true); await settle(); const shown = rows(scene); - assert.deepEqual([shown[0].title, shown[0].detail], ['TRACK ACQUIRED', 'LANDSAT 9 · NADIR VIEW']); + assert.deepEqual( + [shown[0].title, shown[0].detail], + ['TRACK ACQUIRED', 'LANDSAT 9 · NADIR VIEW'], + ); assert.equal(shown.filter((row) => row.title === 'TRACK ACQUIRED').length, 1); const back = shown.find((row) => row.title === 'RETURN · ISS (ZARYA)'); assert.ok(back, 'a RETURN row while there is history'); assert.equal(back.detail, 'PREVIOUS SATELLITE'); - assert.equal(satelliteRow(scene, 25544).getAttribute('aria-label'), 'Return to ISS (ZARYA)'); - assert.ok(!shown.some((row) => row.title === 'ISS (ZARYA)'), 'listed once, as RETURN'); + assert.equal( + satelliteRow(scene, 25544).getAttribute('aria-label'), + 'Return to ISS (ZARYA)', + ); + assert.ok( + !shown.some((row) => row.title === 'ISS (ZARYA)'), + 'listed once, as RETURN', + ); // The camera hops along the way, never in one jump. const target = satellites.position(49260); @@ -779,11 +929,20 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) = for (let i = 0; i < Math.ceil(ORBITAL_HOP_MS / FRAME_MS) + 2; i += 1) { const shot = scene.frame(); assert.equal(cockpit.active, true, `still in orbit at frame ${i}`); - largestStep = Math.max(largestStep, Cesium.Cartesian3.distance(previous, shot.destination)); + largestStep = Math.max( + largestStep, + Cesium.Cartesian3.distance(previous, shot.destination), + ); previous = shot.destination; } - assert.ok(largestStep < hopM * 0.1, `largest step ${largestStep} m of ${hopM} m`); - assert.ok(Cesium.Cartesian3.distance(previous, target) < 1, 'landed on the satellite'); + assert.ok( + largestStep < hopM * 0.1, + `largest step ${largestStep} m of ${hopM} m`, + ); + assert.ok( + Cesium.Cartesian3.distance(previous, target) < 1, + 'landed on the satellite', + ); run(scene, LAND_FRAMES, { drift: 0 }); assert.ok(offNadir(scene.shots.at(-1)) < 1e-6, 'looking at nadir'); @@ -799,10 +958,16 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) = satelliteRow(scene, 25544).click(); assert.equal(cockpit.subjectId, 25544); await settle(); - assert.ok(!rows(scene).some((row) => row.title.startsWith('RETURN')), 'back at the start'); + assert.ok( + !rows(scene).some((row) => row.title.startsWith('RETURN')), + 'back at the start', + ); scene.frame(); assert.equal(cockpit.active, true); - assert.ok(!satellites.calls.some(([, id]) => id === 99001), 'debris never offered'); + assert.ok( + !satellites.calls.some(([, id]) => id === 99001), + 'debris never offered', + ); }); test('while the camera hops, no stale rows; on landing, rows measured from the new satellite', async (t) => { @@ -821,15 +986,32 @@ test('while the camera hops, no stale rows; on landing, rows measured from the n scene.refreshCard(); await settle(); assert.ok(cockpit.orbital.hop, 'still hopping'); - assert.deepEqual(rows(scene).map((row) => row.title), ['TRACK ACQUIRED', 'RETURN · ISS (ZARYA)']); + assert.deepEqual( + rows(scene).map((row) => row.title), + ['TRACK ACQUIRED', 'RETURN · ISS (ZARYA)'], + ); // Landed: the first frame on the satellite rebuilds them at once. - for (let i = 0; i < Math.ceil(ORBITAL_HOP_MS / FRAME_MS) + 2; i += 1) scene.frame(); + for (let i = 0; i < Math.ceil(ORBITAL_HOP_MS / FRAME_MS) + 2; i += 1) + scene.frame(); await settle(); shown = rows(scene); - assert.ok(shown.some((row) => row.target?.layerId === 'military-installations'), 'sites back'); - const satellitesShown = shown.filter((row) => row.title !== 'TRACK ACQUIRED' && row.target?.layerId === 'satellites'); - assert.ok(!satellitesShown.some((row) => row.title === 'LANDSAT 9'), 'never the ridden one'); - assert.equal(satellitesShown.filter((row) => row.target.id === '25544').length, 1, 'ISS only as RETURN'); + assert.ok( + shown.some((row) => row.target?.layerId === 'military-installations'), + 'sites back', + ); + const satellitesShown = shown.filter( + (row) => + row.title !== 'TRACK ACQUIRED' && row.target?.layerId === 'satellites', + ); + assert.ok( + !satellitesShown.some((row) => row.title === 'LANDSAT 9'), + 'never the ridden one', + ); + assert.equal( + satellitesShown.filter((row) => row.target.id === '25544').length, + 1, + 'ISS only as RETURN', + ); }); test('RETURN to a satellite that left the catalogue offers the one before it', async (t) => { @@ -846,7 +1028,10 @@ test('RETURN to a satellite that left the catalogue offers the one before it', a satelliteRow(scene, 49260).click(); assert.equal(cockpit.subjectId, 40697, 'still on the same satellite'); await settle(); - assert.ok(rows(scene).some((row) => row.title === 'RETURN · ISS (ZARYA)'), 'the one before'); + assert.ok( + rows(scene).some((row) => row.title === 'RETURN · ISS (ZARYA)'), + 'the one before', + ); satelliteRow(scene, 25544).click(); assert.equal(cockpit.subjectId, 25544); }); @@ -858,7 +1043,11 @@ test('with Installations off no site is offered, by row, list or click', async ( sites.enabled = false; await refreshRows(scene); assert.ok(rows(scene).some((row) => row.title === 'SITES STANDBY')); - assert.equal(cockpit.orbital.listedSites.size, 0, 'nothing kept to focus from'); + assert.equal( + cockpit.orbital.listedSites.size, + 0, + 'nothing kept to focus from', + ); assert.equal(cockpit.toggleOrbitalFocus(SITES.alpha.id), false); scene.click(SITES.alpha.at); assert.equal(cockpit.orbital.focus ?? null, null); @@ -873,7 +1062,10 @@ test('an arrow during the ease back from a focus turns on the arrows’ clock', scene.frame(); assert.equal(cockpit.orbital.focusReleasing, true); const view = { ...cockpit.orbital.lookView }; - assert.ok(Math.abs(view.pitchDeg) > 1 || Math.abs(view.yawDeg) > 1, 'still turned'); + assert.ok( + Math.abs(view.pitchDeg) > 1 || Math.abs(view.yawDeg) > 1, + 'still turned', + ); cockpit.onKeyDown({ key: 'ArrowUp', target: document.body, @@ -886,7 +1078,10 @@ test('an arrow during the ease back from a focus turns on the arrows’ clock', Math.abs(cockpit.orbital.lookTarget.yawDeg - view.yawDeg) < 1e-6, 'across kept', ); - assert.ok(cockpit.orbital.lookTarget.pitchDeg > view.pitchDeg, 'tilted on up'); + assert.ok( + cockpit.orbital.lookTarget.pitchDeg > view.pitchDeg, + 'tilted on up', + ); }); test('leaving orbit leaves no orbital rows to act on', async (t) => { @@ -901,7 +1096,10 @@ test('leaving orbit leaves no orbital rows to act on', async (t) => { assert.equal(scene.cockpit.toggleOrbitalFocus(SITES.bravo.id), false); assert.equal(scene.cockpit.onOrbitalClick(SITES.bravo.at), false); assert.equal(scene.cockpit.rideOrbitalSatellite(49260), false); - assert.equal(scene.cockpit.handleOrbitalSignalClick('satellites', '49260'), false); + assert.equal( + scene.cockpit.handleOrbitalSignalClick('satellites', '49260'), + false, + ); }); test('NADIR and Home end a focus; an arrow takes the view over where it is', async (t) => { @@ -944,7 +1142,12 @@ test('reduced motion cuts onto the site, back, and between satellites', async (t assert.ok(offNadir(scene.frame()) < 1e-6, 'back at once'); satelliteRow(scene, 49260).click(); const shot = scene.frame(); - assert.ok(Cesium.Cartesian3.distance(shot.destination, scene.satellites.position(49260)) < 1); + assert.ok( + Cesium.Cartesian3.distance( + shot.destination, + scene.satellites.position(49260), + ) < 1, + ); }); test('stopping the Cockpit leaves both clicks to the renderer', async (t) => { @@ -975,11 +1178,21 @@ test('the focused site keeps its row after nearer sites push it down', async (t) sources: [], }); await refreshRows(scene); - const sitesShown = rows(scene).filter((row) => row.target?.layerId === 'military-installations'); + const sitesShown = rows(scene).filter( + (row) => row.target?.layerId === 'military-installations', + ); assert.equal(sitesShown.length, 2); - assert.equal(sitesShown[0].target.id, SITES.alpha.id, 'the focused site is kept, first'); + assert.equal( + sitesShown[0].target.id, + SITES.alpha.id, + 'the focused site is kept, first', + ); siteRow(scene, 'alpha').click(); - assert.equal(scene.cockpit.orbital.focus, null, 'its row still ends the focus'); + assert.equal( + scene.cockpit.orbital.focus, + null, + 'its row still ends the focus', + ); }); test('a site the layer drops in a reload keeps its row, and its row still focuses it', async (t) => { @@ -990,13 +1203,24 @@ test('a site the layer drops in a reload keeps its row, and its row still focuse // The thinned view reloads without Camp Alpha for a moment. scene.sites.records = loaded.filter((r) => r.id !== SITES.alpha.id); await refreshRows(scene); - assert.deepEqual(rows(scene).map((row) => row.key), before, 'the rows hold still'); + assert.deepEqual( + rows(scene).map((row) => row.key), + before, + 'the rows hold still', + ); siteRow(scene, 'alpha').click(); - assert.equal(scene.cockpit.orbital.focus?.key, SITES.alpha.id, 'focused from its row'); + assert.equal( + scene.cockpit.orbital.focus?.key, + SITES.alpha.id, + 'focused from its row', + ); siteRow(scene, 'alpha').click(); // Gone for good: after a while it leaves the rows. for (let i = 0; i < 12; i += 1) await refreshRows(scene); - assert.ok(!rows(scene).some((row) => row.target?.id === SITES.alpha.id), 'forgotten later'); + assert.ok( + !rows(scene).some((row) => row.target?.id === SITES.alpha.id), + 'forgotten later', + ); }); test('shown rows keep their places while they still qualify', async (t) => { @@ -1021,12 +1245,174 @@ test('shown rows keep their places while they still qualify', async (t) => { const sitesAfter = rows(scene) .filter((row) => row.target?.layerId === 'military-installations') .map((row) => row.target.id); - assert.deepEqual(sitesAfter, sitesBefore, 'no row moves while its site is in reach'); + assert.deepEqual( + sitesAfter, + sitesBefore, + 'no row moves while its site is in reach', + ); // Once a shown site leaves the list, the nearer one takes its slot. - scene.sites.records = scene.sites.records.filter((r) => r.id !== SITES.bravo.id); + scene.sites.records = scene.sites.records.filter( + (r) => r.id !== SITES.bravo.id, + ); for (let i = 0; i < 12; i += 1) await refreshRows(scene); assert.ok( rows(scene).some((row) => row.target?.id === 'osm:military:way/999'), 'the nearer site fills the freed slot', ); }); + +/** + * A view from the station: its camera 20 m above the satellite, looking 65° + * below level toward the north, as the satellites layer gives it. Camp Alpha, + * about 120 km to the north-east of a satellite 420 km up, is some 74° + * below level from it: within the view's reach. + */ +function stationMount(scene) { + const position = scene.satellites.position(25544); + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position); + const axis = (x, y, z) => + Cesium.Cartesian3.normalize( + Cesium.Matrix4.multiplyByPointAsVector( + enu, + new Cesium.Cartesian3(x, y, z), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + const down = (65 * Math.PI) / 180; + const direction = axis(0, Math.cos(down), -Math.sin(down)); + const up = axis(0, Math.sin(down), Math.cos(down)); + return { + position: Cesium.Cartesian3.add( + position, + Cesium.Cartesian3.multiplyByScalar( + axis(0, 0, 1), + 20, + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ), + direction, + up, + right: Cesium.Cartesian3.cross(direction, up, new Cesium.Cartesian3()), + key: 'zarya', + label: 'ZARYA', + noradId: 25544, + card: null, + views: [ + { key: 'zarya', label: 'ZARYA', noradId: 25544, card: null }, + { key: 'cupola', label: 'CUPOLA', noradId: 25544, card: null }, + ], + }; +} + +test('from a station view, a site row turns the camera onto it from the view’s own point and holds it', async (t) => { + const scene = await inOrbit(t); + const { cockpit, satellites } = scene; + satellites.getCockpitMount = () => stationMount(scene); + scene.frame(); + await refreshRows(scene); + const mount = stationMount(scene); + // Camp Alpha lies below and to the north-east, within 45° of the view. + assert.ok(missDeg(scene.shots.at(-1), 'alpha') > 5, 'not centred yet'); + siteRow(scene, 'alpha').click(); + assert.equal(cockpit.orbital.focus.key, SITES.alpha.id); + run(scene, LAND_FRAMES, { drift: 0 }); + for (let i = 0; i < 10; i += 1) { + const shot = scene.frame(); + // From the view's camera point on the station, not the satellite's. + assert.ok( + Cesium.Cartesian3.distance( + shot.destination, + stationMount(scene).position, + ) < 1e-6, + ); + assert.ok( + missDeg(shot, 'alpha') < 1e-4, + `frame ${i}: ${missDeg(shot, 'alpha')}°`, + ); + } + // The same site from straight down would be off the view's direction. + assert.ok(angleDeg(mount.direction, scene.shots.at(-1).direction) > 1); + // Its row still words the angle from straight down, not from the view. + await refreshRows(scene); + const held = rows(scene).find((row) => row.target?.id === SITES.alpha.id); + const fromNadir = siteOffNadir(scene.shots.at(-1), 'alpha'); + const shown = Number(/OFF-NADIR ([\d.]+)°/.exec(held.detail)[1]); + assert.ok(Math.abs(shown - fromNadir) < 0.2, `${shown}° vs ${fromNadir}°`); + + // Switching views ends the focus: the new view looks its own way. + cockpit.nextOrbitalView(); + assert.ok(!cockpit.orbital.focus); +}); + +test('from a station view, a site beyond 45° of where the view looks is not focused', async (t) => { + const scene = await inOrbit(t); + const { cockpit, satellites } = scene; + // The view looks south; Camp Alpha is to the north-east, behind it. + satellites.getCockpitMount = () => { + const mount = stationMount(scene); + const flip = (v) => Cesium.Cartesian3.negate(v, new Cesium.Cartesian3()); + const enu = Cesium.Transforms.eastNorthUpToFixedFrame( + scene.satellites.position(25544), + ); + const south = Cesium.Cartesian3.normalize( + Cesium.Matrix4.multiplyByPointAsVector( + enu, + new Cesium.Cartesian3(0, -0.87, -0.5), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.normalize( + Cesium.Matrix4.multiplyByPointAsVector( + enu, + new Cesium.Cartesian3(0, -0.5, 0.87), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + return { + ...mount, + direction: south, + up, + right: Cesium.Cartesian3.cross(south, up, new Cesium.Cartesian3()), + unused: flip, + }; + }; + scene.frame(); + await refreshRows(scene); + const row = siteRow(scene, 'alpha'); + if (row) row.click(); + else cockpit.toggleOrbitalFocus?.(SITES.alpha.id); + assert.ok(!cockpit.orbital.focus); +}); + +test("a click on a site's label box focuses it, as one on its dot does", async (t) => { + const scene = await inOrbit(t); + const { cockpit, handler, sites } = scene; + // No dot is drawn at the label's place: the layer's own lookup is what + // finds the site there, through the label box the overlay paints. + assert.equal(sites.findByPick(null), null, 'no draw item at the label'); + assert.equal(sites.findAt(SITES.alpha.labelAt)?.id, SITES.alpha.id); + // The overlay reports the label box as the card on top there, as it does + // for an interactive entry: the site's own label is not another layer's. + const labels = [SITES.alpha.labelAt]; + setClickCardHitTest((x, y) => + labels.some((at) => at.x === x && at.y === y) + ? { sourceId: 'military-installations', entryId: SITES.alpha.id } + : null, + ); + t.after(() => setClickCardHitTest(null)); + scene.click(SITES.alpha.labelAt); + assert.equal(cockpit.orbital.focus.key, SITES.alpha.id); + assert.equal(handler.stockClicks, 1, 'Cesium still gets the click'); + run(scene, LAND_FRAMES); + assert.ok(missDeg(scene.shots.at(-1), 'alpha') < 1e-5); + // The label of the focused site again keeps it; another site's dot + // switches. + scene.click(SITES.alpha.labelAt); + assert.equal(cockpit.orbital.focus.key, SITES.alpha.id); + scene.click(SITES.bravo.at); + assert.equal(cockpit.orbital.focus.key, SITES.bravo.id); +}); diff --git a/src/ui/cockpitOrbitalSatellites.js b/src/ui/cockpitOrbitalSatellites.js index 29aadc65ae..129d43b008 100644 --- a/src/ui/cockpitOrbitalSatellites.js +++ b/src/ui/cockpitOrbitalSatellites.js @@ -159,7 +159,7 @@ export function switchOrbitalSatellite(noradId) { 'track', 'track', t('TRACK ACQUIRED'), - t('{label} · NADIR VIEW', { label: info.name }), + this.orbitalViewSignal(info), ); this.updateOrbitalHud(info); this.refreshOrbitalSignals?.(); diff --git a/src/ui/cockpitOrbitalView.js b/src/ui/cockpitOrbitalView.js index 039e6aca05..b29cacd540 100644 --- a/src/ui/cockpitOrbitalView.js +++ b/src/ui/cockpitOrbitalView.js @@ -1,5 +1,6 @@ /** The orbital (satellite) view of the Cockpit controller: camera, zoom, look and HUD. */ import { isFollowing } from '../data/followed.js'; +import { clone } from '../geo/vector.js'; import { cameraOf, canvasOf, findGlobe } from '../render/rendererOf.js'; import { formatNumber, msg, t } from '../i18n/index.js'; import { @@ -34,6 +35,10 @@ import { import { cockpitUiUpdateDue } from '../cockpitMath.js'; import { createPlaceTracker, nearPlaceRadiusKm } from '../data/placeBelow.js'; import { isPointerFree } from '../data/inputOwnership.js'; +import { + issNextMountView, + issPreviousMountView, +} from '../layers/satellites/issMounts.js'; import { zoomableSwathKm } from '../layers/satellites/sensors.js'; import { easeOrbitalLook, @@ -41,7 +46,10 @@ import { releaseOrbitalFocus, updateOrbitalFocus, } from './cockpitOrbitalFocus.js'; -import { orbitalEyePosition } from './cockpitOrbitalSatellites.js'; +import { + orbitalEyePosition, + switchOrbitalSatellite, +} from './cockpitOrbitalSatellites.js'; import { COCKPIT_CONTEXT_UPDATE_MS, COCKPIT_HUD_UPDATE_MS, @@ -84,6 +92,15 @@ export function beginOrbital() { // A zoom step in flight: the magnification it started from and when. transition: null, previousUp: null, + // The station's view shown (its key and name) and the views on offer; + // null and none for any other satellite. The key is kept while the + // model is away, so the same view comes back with it. + mountKey: null, + mount: null, + mountViews: [], + // A view of a module with no catalog entry (the Cupola) carries the + // card shown in place of the entry it rides; null otherwise. + mountCard: null, altitudeM: null, verticalFov: null, lastBriefMs: 0, @@ -270,8 +287,49 @@ export function updateOrbital(nowMs) { ); if (!position) return; const state = this.orbital; + // The station is ridden from a point on its 3D model, looking along it, + // in place of the straight-down picture (the satellites layer says where). + const mount = + this.services.satellitesLayer?.getCockpitMount?.(state.mountKey) ?? null; + if (mount?.key) state.mountKey = mount.key; + state.mountViews = mount?.views ?? []; + state.mountCard = mount?.card ?? null; + // Each view belongs to an entry of its own (Nauka, the ISS, Poisk, the + // docked vehicle). The Cockpit rides that entry, so the readout, the TLE + // and the signals describe the module the view is from, not the one first + // selected. The switch lands on the next frame; one that fails is not + // retried until the view changes. + if ( + mount?.noradId !== null && + mount?.noradId !== undefined && + String(mount.noradId) !== String(this.subjectId) && + state.mountSwitchFailed !== mount.key + ) { + if (switchOrbitalSatellite.call(this, mount.noradId)) return; + state.mountSwitchFailed = mount.key; + } + // The model can load after entry, and the picture then changes under the + // TRACK ACQUIRED line that named it: say which it is now. + const riding = mount !== null; + const changed = state.riding !== undefined && state.riding !== riding; + state.riding = riding; + if (changed) { + this.signalItems = (this.signalItems ?? []).filter( + (item) => item.key !== 'track', + ); + this.signalSignatures?.delete('track'); + this.pushCockpitSignal( + 'track', + 'track', + t('TRACK ACQUIRED'), + this.orbitalViewSignal(info), + ); + } + state.mount = mount ? mount.label || '' : null; // On the satellite, or on the way to it after Previous/Next. - const eye = orbitalEyePosition(state, position, nowMs); + const eye = mount + ? clone(mount.position) + : orbitalEyePosition(state, position, nowMs); // Track-up: the ground track at the top, so the picture scrolls along it. // A geostationary satellite has no track and stays north-up. const nadir = nadirOrientation(eye, { @@ -291,15 +349,28 @@ export function updateOrbital(nowMs) { this.lastSubjectInfo = info; goToZoom.call(this, maxZoom); } - // A ground focus aims the look itself (src/ui/cockpitOrbitalFocus.js). - if (!updateOrbitalFocus.call(this, state, nadir, eye, nowMs)) + // A ground focus aims the look itself (src/ui/cockpitOrbitalFocus.js), + // in the frame the arrows turn: from a station view, its own, from its + // camera point on the station. The same ±45° reach holds about it. + if ( + !updateOrbitalFocus.call( + this, + state, + mount ?? nadir, + eye, + nowMs, + mount ? nadir : null, + ) + ) state.lookView = easeOrbitalLook( state, nowMs - (state.lookLastMs || nowMs), { immediate: prefersReducedMotion() }, ); state.lookLastMs = nowMs; - const view = offNadirOrientation(nadir, { + // The arrows tilt the view about its own frame: the nadir one, or the + // mount's. + const view = offNadirOrientation(mount ?? nadir, { northDeg: state.lookView.pitchDeg, eastDeg: state.lookView.yawDeg, }); @@ -470,9 +541,19 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) { northDeg: state.lookView?.pitchDeg ?? 0, eastDeg: state.lookView?.yawDeg ?? 0, }); + // Riding the station from a mount on its model: the view's name, and no + // ground readings, which describe the nadir picture. + const mount = state.mount ?? null; + // A module with no catalog entry of its own shows its own card: its name, + // what it is and a few facts, in place of the entry's identity and TLE. + const card = mount !== null ? (state.mountCard ?? null) : null; this.publishOrbital({ - name: info.name, - classLabel: info.classLabel || '', + name: card ? card.name : info.name, + mount, + facts: card ? card.facts.map((fact) => t(fact)) : null, + // How many views the station offers: the arrows show with two or more. + mountViews: mount === null ? 0 : (state.mountViews?.length ?? 0), + classLabel: card ? t(card.classLabel) : info.classLabel || '', altitudeM: info.altitudeM, velocityMps: Number.isFinite(info.velocityMps) ? info.velocityMps : null, latitude: info.latitude, @@ -480,12 +561,12 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) { zoom: state.zoom, zoomSteps: ORBITAL_ZOOM_LADDER.filter((step) => step <= maxZoom), maxZoom, - footprintKm: offset ? null : footprintKm, + footprintKm: offset || mount !== null ? null : footprintKm, // The imaging sensor's swath, drawn to scale; null without one. The // SENSOR step's zoom is null when the swath lies outside 1x..maxZoom. // Looking past the limb there is no ground for it to cover: no sensor. sensor: - swathKm === null || !seesEarth + swathKm === null || !seesEarth || mount !== null ? null : { label: info.sensor?.label ?? null, @@ -503,18 +584,22 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) { transition: { ...transition }, look: { offset, - readout: focus - ? wordFocusOffNadir(focus) - : offset - ? wordOffNadir(state.lookTarget, { trackUp }) - : '', + // From a mount the tilt is about the mount's frame, not the nadir. + readout: + mount !== null + ? '' + : focus + ? wordFocusOffNadir(focus) + : offset + ? wordOffNadir(state.lookTarget, { trackUp }) + : '', // The mapped point the view is held on, or null. focus: focus ? { key: focus.key, label: focus.label } : null, // Off nadir, the ground width at the view's centre, approximated from // the nadir footprint (`offNadirSwathScale`); 1 and null at nadir. swathScale, swathKm: - offset && seesEarth && Number.isFinite(footprintKm) + mount === null && offset && seesEarth && Number.isFinite(footprintKm) ? footprintKm * swathScale : null, }, @@ -523,23 +608,45 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) { trackUp, northDeg: trackUp ? (360 - info.groundTrackDeg) % 360 : 0, place: state.place, - noradId: info.noradId ?? null, - cosparId: info.cosparId ?? null, - tle: info.tle ?? null, + noradId: card ? null : (info.noradId ?? null), + cosparId: card ? null : (info.cosparId ?? null), + tle: card ? null : (info.tle ?? null), // Read on the HUD's cadence, so the age stays current without a timer. // The gap between the TLE's epoch and the time the satellite is shown // at (the world clock's), either side: SGP4 drifts both ways. - tleAgeMs: Number.isFinite(info.tle?.epochMs) - ? Math.abs( - (Number.isFinite(info.atMs) ? info.atMs : Date.now()) - - info.tle.epochMs, - ) - : null, - owner: info.owner ?? null, - operator: info.operator ?? null, + tleAgeMs: + !card && Number.isFinite(info.tle?.epochMs) + ? Math.abs( + (Number.isFinite(info.atMs) ? info.atMs : Date.now()) - + info.tle.epochMs, + ) + : null, + owner: card ? null : (info.owner ?? null), + operator: card ? t(card.operator) : (info.operator ?? null), }); } +/** + * The TRACK ACQUIRED line for a satellite subject: which picture it gets. + * The station is ridden from a mount on its 3D model (once that is loaded); + * every other satellite looks straight down. + * @param {object} info Satellite subject. + * @returns {string} + */ +export function orbitalViewSignal(info) { + // A running session knows; on entry, before its first frame, the layer does. + const riding = + this.orbital?.riding ?? + Boolean( + this.services.satellitesLayer?.getCockpitMount?.( + this.orbital?.mountKey ?? null, + ), + ); + return riding + ? t('{label} · STATION VIEW', { label: info.name }) + : t('{label} · NADIR VIEW', { label: info.name }); +} + /** * Present the orbital view on entry and after a language switch: the HUD, * the local page and a regional brief for the sub-satellite point. @@ -556,6 +663,38 @@ export function updateOrbitalHud(info, nowMs = performance.now()) { updateOrbitalContext.call(this, info, nowMs, true); } +/** + * The station view's arrows: move to its next view (from Nauka, from Zarya, + * from Poisk, from the Cupola, from Kibo, from a docked vehicle) or the one + * before, wrapping round, looking the way that view looks. + * @param {number} [direction] 1 for the next view, -1 for the one before. + * @returns {boolean} True when the view changed. + */ +export function stepOrbitalMount(direction = 1) { + if (!this.active || this.subjectKind !== 'satellite' || !this.orbital) + return false; + const state = this.orbital; + const step = direction < 0 ? issPreviousMountView : issNextMountView; + const next = + state.mount === null ? null : step(state.mountViews, state.mountKey); + if (!next) return false; + state.mountKey = next.key; + state.mount = next.label || ''; + state.mountCard = next.card ?? null; + state.mountSwitchFailed = null; + // A ground focus was aimed from the old view: it ends with it. + if (state.focus) { + state.focus = null; + state.focusReleasing = false; + this.refreshOrbitalSignals?.(); + } + // Each view has its own way of looking: the look goes back to it. + state.lookTarget = { ...NADIR_LOOK }; + state.lookView = { ...NADIR_LOOK }; + presentNow.call(this); + return true; +} + /** Re-apply the field of view and publish after a zoom or look change. */ function presentNow() { const state = this.orbital; diff --git a/src/ui/cockpitOrbitalView.test.mjs b/src/ui/cockpitOrbitalView.test.mjs index bd48d624a2..5bea5b33d4 100644 --- a/src/ui/cockpitOrbitalView.test.mjs +++ b/src/ui/cockpitOrbitalView.test.mjs @@ -1466,3 +1466,535 @@ test('back to nadir from past the limb, the sensor waits for the view', async (t await settle(); assert.ok(store.orbital.sensor, 'back on the Earth'); }); + +/** A mount on the station: 20 m from the satellite's position, looking along the track. */ +function stationMount() { + const centre = satellitePosition(); + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(centre); + const axis = (x, y, z) => + Cesium.Matrix4.multiplyByPointAsVector( + enu, + new Cesium.Cartesian3(x, y, z), + new Cesium.Cartesian3(), + ); + const direction = axis(0, 1, 0); + const up = axis(0, 0, 1); + return { + position: Cesium.Cartesian3.add( + centre, + Cesium.Cartesian3.multiplyByScalar(up, 20, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ), + direction, + up, + right: Cesium.Cartesian3.cross(direction, up, new Cesium.Cartesian3()), + label: 'ZARYA', + }; +} + +test('the station is ridden from its mount: the camera sits there and looks along it', async (t) => { + const { $, cockpit, satellites, shots, store, clock } = await orbitAt(t); + const mount = stationMount(); + satellites.getCockpitMount = () => mount; + clock.advance(16); + cockpit.update(); + await settle(); + const shot = shots.at(-1); + assert.ok( + Cesium.Cartesian3.equalsEpsilon(shot.destination, mount.position, 1e-9), + 'the camera is at the mount, not at the satellite', + ); + near( + angleDeg(shot.direction, mount.direction), + 0, + 'looks along the mount', + 1e-9, + ); + near(angleDeg(shot.up, mount.up), 0, 'the mount is upright', 1e-9); + + // The HUD names the view and drops what describes the nadir picture. + assert.equal(store.orbital.mount, 'ZARYA'); + assert.equal(store.orbital.footprintKm, null); + assert.equal(store.orbital.sensor, null); + assert.equal( + $('.cockpit-orbital-kicker').textContent, + 'STATION VIEW · ZARYA', + ); + assert.equal($('.cockpit-orbital-reticle'), null); + assert.equal($('.cockpit-orbital-north'), null); + assert.match($('.cockpit-help').textContent, /ARROWS LOOK/); + assert.match($('.cockpit-help').textContent, /HOME RESET/); + assert.doesNotMatch($('.cockpit-help').textContent, /NADIR/); + + // The arrows turn the view about the mount's own frame, and Home returns. + press(cockpit, 'ArrowRight'); + clock.advance(16); + cockpit.update(); + await settle(); + const turned = shots.at(-1); + near(angleDeg(turned.direction, mount.direction), 5, 'one step is 5°', 1e-6); + assert.ok( + Cesium.Cartesian3.dot(turned.direction, mount.right) > 0, + 'right turns toward the mount’s right', + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon(turned.destination, mount.position, 1e-9), + ); + assert.equal($('#cockpit-orbital-nadir').textContent, 'RESET'); + assert.equal($('#cockpit-orbital-look-readout').textContent, ''); + press(cockpit, 'Home'); + clock.advance(16); + cockpit.update(); + near(angleDeg(shots.at(-1).direction, mount.direction), 0, 'Home', 1e-9); +}); + +test('without a mount the same satellite keeps the nadir picture, and gets it back', async (t) => { + const { $, cockpit, satellites, shots, store, clock } = await orbitAt(t); + const position = satellitePosition(); + const toCentre = Cesium.Cartesian3.negate( + Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const signals = []; + cockpit.pushCockpitSignal = (key, kind, title, detail) => + signals.push(detail); + // The model has not loaded yet: straight down, as for any satellite. + satellites.getCockpitMount = () => null; + clock.advance(16); + cockpit.update(); + await settle(); + assert.deepEqual(signals, [], 'nothing changed: nothing to say'); + near(angleDeg(shots.at(-1).direction, toCentre), 0, 'nadir', 1e-9); + assert.equal(store.orbital.mount, null); + assert.equal( + $('.cockpit-orbital-kicker').textContent, + 'ORBITAL VIEW · NADIR', + ); + assert.ok($('.cockpit-orbital-reticle')); + + // It loads: the view moves to the mount. It goes again: back to nadir. + const mount = stationMount(); + satellites.getCockpitMount = () => mount; + clock.advance(1000); + cockpit.update(); + await settle(); + assert.equal(store.orbital.mount, 'ZARYA'); + near(angleDeg(shots.at(-1).direction, mount.direction), 0, 'mount', 1e-9); + // The TRACK ACQUIRED line follows the picture, once per change. + cockpit.update(); + assert.deepEqual(signals, ['ISS (ZARYA) · STATION VIEW']); + satellites.getCockpitMount = () => null; + clock.advance(1000); + cockpit.update(); + await settle(); + assert.deepEqual(signals, [ + 'ISS (ZARYA) · STATION VIEW', + 'ISS (ZARYA) · NADIR VIEW', + ]); + assert.equal(store.orbital.mount, null); + near(angleDeg(shots.at(-1).direction, toCentre), 0, 'nadir again', 1e-9); + assert.ok( + Cesium.Cartesian3.equalsEpsilon(shots.at(-1).destination, position, 1e-6), + ); +}); + +/** The station's views as the satellites layer offers them, by key. */ +function stationViews({ docked = true } = {}) { + const views = [ + { key: 'nauka', label: 'NAUKA' }, + { key: 'zarya', label: 'ZARYA' }, + ...(docked ? [{ key: 'docked', label: 'PROGRESS-MS 34' }] : []), + ]; + const base = stationMount(); + // Each view sits a different distance above the satellite's position. + const heights = { nauka: 10, zarya: 20, docked: 30 }; + const asked = []; + return { + asked, + views, + heightOf(shot) { + return Math.round( + Cesium.Cartesian3.distance(shot.destination, satellitePosition()), + ); + }, + getCockpitMount(key) { + asked.push(key); + const view = views.find((entry) => entry.key === key) ?? views[0]; + return { + ...base, + position: Cesium.Cartesian3.add( + satellitePosition(), + Cesium.Cartesian3.multiplyByScalar( + base.up, + heights[view.key], + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ), + key: view.key, + label: view.label, + views, + }; + }, + }; +} + +test('the station opens on its first view and the arrows step through the rest', async (t) => { + const { $, cockpit, satellites, shots, store, clock } = await orbitAt(t); + const station = stationViews(); + satellites.getCockpitMount = station.getCockpitMount; + const frame = async () => { + clock.advance(16); + cockpit.update(); + await settle(); + }; + await frame(); + // Nothing was chosen: the layer is asked for its first view, Nauka's, + // though the entry ridden is ISS (ZARYA). + assert.equal(station.asked[0], null); + assert.equal(store.orbital.mount, 'NAUKA'); + assert.equal(store.orbital.mountViews, 3); + assert.equal(station.heightOf(shots.at(-1)), 10); + assert.equal( + $('.cockpit-orbital-kicker').textContent, + 'STATION VIEW · NAUKA', + ); + assert.equal( + $('#cockpit-orbital-view-next').getAttribute('aria-label'), + 'Next station view', + ); + assert.equal( + $('#cockpit-orbital-view-previous').getAttribute('aria-label'), + 'Previous station view', + ); + assert.equal($('#cockpit-orbital-view-name').textContent, 'NAUKA'); + + // A look off to one side is dropped by the step: each view looks its own way. + press(cockpit, 'ArrowRight'); + await frame(); + assert.equal(store.orbital.look.offset, true); + + // The button, as a click anywhere inside it. + $('#cockpit-orbital-view-next').dispatchEvent( + new Event('click', { bubbles: true }), + ); + await settle(); + assert.equal(store.orbital.mount, 'ZARYA', 'named at once, before a frame'); + await frame(); + assert.equal(station.asked.at(-1), 'zarya'); + assert.equal(station.heightOf(shots.at(-1)), 20); + assert.equal(store.orbital.look.offset, false); + near( + angleDeg(shots.at(-1).direction, stationMount().direction), + 0, + 'reset', + 1e-9, + ); + assert.equal( + $('.cockpit-orbital-kicker').textContent, + 'STATION VIEW · ZARYA', + ); + + assert.equal(cockpit.nextOrbitalView(), true); + await frame(); + assert.equal(store.orbital.mount, 'PROGRESS-MS 34'); + assert.equal(station.heightOf(shots.at(-1)), 30); + // Round again to the first. + assert.equal(cockpit.nextOrbitalView(), true); + await frame(); + assert.equal(store.orbital.mount, 'NAUKA'); + assert.equal(station.heightOf(shots.at(-1)), 10); +}); + +test('the chosen view is kept while the model is away, and one view has no arrows', async (t) => { + const { $, cockpit, satellites, store, clock } = await orbitAt(t); + const station = stationViews({ docked: false }); + satellites.getCockpitMount = station.getCockpitMount; + // A second per frame: the HUD republishes on its own cadence. + const frame = async () => { + clock.advance(1000); + cockpit.update(); + await settle(); + }; + await frame(); + assert.equal(store.orbital.mountViews, 2); + cockpit.nextOrbitalView(); + await frame(); + assert.equal(store.orbital.mount, 'ZARYA'); + // The model goes: nadir, no control, nothing to step. + satellites.getCockpitMount = () => null; + await frame(); + assert.equal(store.orbital.mount, null); + assert.equal(store.orbital.mountViews, 0); + assert.equal($('#cockpit-orbital-view-next'), null); + assert.equal($('#cockpit-orbital-view-previous'), null); + assert.equal(cockpit.nextOrbitalView(), false); + // It comes back: the same view is asked for again. + satellites.getCockpitMount = station.getCockpitMount; + await frame(); + assert.equal(station.asked.at(-1), 'zarya'); + assert.equal(store.orbital.mount, 'ZARYA'); + + // A station offering a single view shows no control. + station.views.length = 1; + await frame(); + assert.equal(store.orbital.mount, 'NAUKA', 'the view on offer'); + assert.equal(store.orbital.mountViews, 1); + assert.equal($('#cockpit-orbital-view-next'), null); + assert.equal($('#cockpit-orbital-view-previous'), null); + assert.equal(cockpit.nextOrbitalView(), false); +}); + +test('the view arrows do nothing outside a station view', async (t) => { + const { cockpit, clock } = await orbitAt(t); + clock.advance(16); + cockpit.update(); + assert.equal(cockpit.nextOrbitalView(), false); + assert.equal(cockpit.previousOrbitalView(), false); + cockpit.exit(); + assert.equal(cockpit.nextOrbitalView(), false); + assert.equal(cockpit.previousOrbitalView(), false); +}); + +test('each station view rides its own entry, so the card describes that module', async (t) => { + const { $, cockpit, satellites, store, clock } = await orbitAt(t); + // The layer, as it behaves: tracking another entry makes it the subject. + const names = { + 25544: 'ISS (ZARYA)', + 49044: 'ISS (NAUKA)', + 36086: 'POISK', + 68837: 'PROGRESS-MS 34', + }; + let subject = { ...ISS, noradId: 68837, id: '68837', name: names[68837] }; + const tracked = []; + satellites.getCockpitSubject = () => ({ ...subject }); + satellites.trackById = (noradId) => { + tracked.push(Number(noradId)); + const id = Number(noradId); + subject = { ...ISS, noradId: id, id: String(id), name: names[id] }; + return true; + }; + cockpit.subjectId = 68837; + const base = stationMount(); + const views = [ + { key: 'nauka', label: 'NAUKA', noradId: 49044 }, + { key: 'zarya', label: 'ZARYA', noradId: 25544 }, + { key: 'poisk', label: 'POISK', noradId: 36086 }, + { key: 'docked', label: 'PROGRESS-MS 34', noradId: 68837 }, + ]; + satellites.getCockpitMount = (key) => { + const view = views.find((entry) => entry.key === key) ?? views[0]; + return { ...base, ...view, views }; + }; + const frame = async () => { + clock.advance(1000); + cockpit.update(); + await settle(); + }; + // Entered on the Progress; the view opens on Nauka and rides Nauka. + await frame(); + await frame(); + assert.deepEqual(tracked, [49044]); + assert.equal(cockpit.subjectId, 49044); + assert.equal(store.orbital.name, 'ISS (NAUKA)'); + assert.equal($('.cockpit-orbital-name').textContent, 'ISS (NAUKA)'); + assert.equal(store.orbital.mount, 'NAUKA'); + + // Each step rides the next view's entry. + for (const [noradId, name] of [ + [25544, 'ISS (ZARYA)'], + [36086, 'POISK'], + [68837, 'PROGRESS-MS 34'], + [49044, 'ISS (NAUKA)'], + ]) { + assert.equal(cockpit.nextOrbitalView(), true); + await frame(); + await frame(); + assert.equal(cockpit.subjectId, noradId); + assert.equal(store.orbital.name, name); + assert.equal($('.cockpit-orbital-name').textContent, name); + } + assert.deepEqual(tracked, [49044, 25544, 36086, 68837, 49044]); +}); + +test('a view with no entry, or one that cannot be ridden, keeps the subject', async (t) => { + const { cockpit, satellites, store, clock } = await orbitAt(t); + const base = stationMount(); + let views = [ + { key: 'nauka', label: 'NAUKA', noradId: null }, + { key: 'zarya', label: 'ZARYA', noradId: 25544 }, + ]; + satellites.getCockpitMount = (key) => { + const view = views.find((entry) => entry.key === key) ?? views[0]; + return { ...base, ...view, views }; + }; + let asked = 0; + satellites.trackById = () => { + asked += 1; + return false; + }; + const frame = async () => { + clock.advance(1000); + cockpit.update(); + await settle(); + }; + // No entry for Nauka: the ISS stays the subject, and nothing is tracked. + await frame(); + assert.equal(asked, 0); + assert.equal(cockpit.subjectId, 25544); + assert.equal(store.orbital.mount, 'NAUKA'); + // An entry the layer will not track: asked once, not every frame. + views = [ + { key: 'nauka', label: 'NAUKA', noradId: 49044 }, + { key: 'zarya', label: 'ZARYA', noradId: 25544 }, + ]; + await frame(); + await frame(); + await frame(); + assert.equal(asked, 1); + assert.equal(cockpit.subjectId, 25544); + assert.equal(document.body.classList.contains('cockpit-orbit'), true); +}); + +const CUPOLA_CARD = Object.freeze({ + name: 'CUPOLA', + classLabel: 'OBSERVATION MODULE · ISS', + operator: 'European Space Agency (ESA)', + facts: ['7 WINDOWS', 'LAUNCHED 8 FEB 2010 · STS-130'], +}); + +test('a view with a card of its own shows it in place of the entry’s identity', async (t) => { + const { $, cockpit, satellites, store, clock } = await orbitAt(t); + const base = stationMount(); + const views = [ + { key: 'zarya', label: 'ZARYA', noradId: 25544, card: null }, + { key: 'cupola', label: 'CUPOLA', noradId: 25544, card: CUPOLA_CARD }, + ]; + satellites.getCockpitMount = (key) => { + const view = views.find((entry) => entry.key === key) ?? views[0]; + return { ...base, ...view, views }; + }; + const frame = async () => { + clock.advance(1000); + cockpit.update(); + await settle(); + }; + await frame(); + assert.equal(store.orbital.name, 'ISS (ZARYA)'); + assert.equal(store.orbital.noradId, 25544); + assert.equal(store.orbital.facts, null); + + cockpit.nextOrbitalView(); + await frame(); + // Same entry ridden (nothing to switch), the Cupola's own card shown. + assert.equal(cockpit.subjectId, 25544); + assert.equal(store.orbital.mount, 'CUPOLA'); + assert.equal(store.orbital.name, 'CUPOLA'); + assert.equal($('.cockpit-orbital-name').textContent, 'CUPOLA'); + assert.equal(store.orbital.classLabel, 'OBSERVATION MODULE · ISS'); + assert.equal(store.orbital.operator, 'European Space Agency (ESA)'); + assert.equal(store.orbital.noradId, null); + assert.equal(store.orbital.tle, null); + assert.equal(store.orbital.owner, null); + assert.equal( + $('.cockpit-orbital-ident-text').textContent, + '7 WINDOWS · LAUNCHED 8 FEB 2010 · STS-130', + ); + assert.equal($('#cockpit-orbital-tle-toggle'), null); + // Altitude, velocity and the sub-satellite point are the station's still. + assert.ok($('.cockpit-orbital-altitude').textContent.length > 0); + + // Back round to Zarya: the entry's own card again. + cockpit.nextOrbitalView(); + await frame(); + assert.equal(store.orbital.name, 'ISS (ZARYA)'); + assert.equal(store.orbital.noradId, 25544); + assert.equal(store.orbital.facts, null); +}); + +test('leaving a station view selects Nauka; leaving any other keeps the satellite', async (t) => { + const { cockpit, satellites, clock } = await orbitAt(t); + const names = { 25544: 'ISS (ZARYA)', 49044: 'ISS (NAUKA)' }; + let subject = { ...ISS }; + const tracked = []; + satellites.getCockpitSubject = () => ({ ...subject }); + satellites.trackById = (noradId) => { + const id = Number(noradId); + tracked.push(id); + subject = { ...ISS, noradId: id, id: String(id), name: names[id] }; + return true; + }; + const base = stationMount(); + const views = [ + { key: 'nauka', label: 'NAUKA', noradId: 49044, card: null }, + { key: 'cupola', label: 'CUPOLA', noradId: 25544, card: CUPOLA_CARD }, + ]; + satellites.getCockpitMount = (key) => { + const view = views.find((entry) => entry.key === key) ?? views[0]; + return { ...base, ...view, views }; + }; + const frame = async () => { + clock.advance(1000); + cockpit.update(); + await settle(); + }; + await frame(); + await frame(); + // On the Cupola, riding the ISS's entry, when the Cockpit is left. + cockpit.nextOrbitalView(); + await frame(); + await frame(); + assert.equal(cockpit.subjectId, 25544); + satellites.calls.length = 0; + tracked.length = 0; + assert.equal(cockpit.exit(), true); + assert.deepEqual(tracked, [49044], 'Nauka is selected'); + assert.deepEqual(satellites.calls, [ + ['subject', null], + ['refocus', 49044], + ]); +}); + +test('leaving the plain orbital view refocuses the satellite ridden', async (t) => { + const { cockpit, satellites } = await orbitAt(t); + const tracked = []; + satellites.trackById = (noradId) => { + tracked.push(noradId); + return true; + }; + satellites.calls.length = 0; + assert.equal(cockpit.exit(), true); + assert.deepEqual(tracked, []); + assert.deepEqual(satellites.calls, [ + ['subject', null], + ['refocus', 25544], + ]); +}); + +test('the left arrow steps back through the views, wrapping round', async (t) => { + const { $, cockpit, satellites, shots, store, clock } = await orbitAt(t); + const station = stationViews(); + satellites.getCockpitMount = station.getCockpitMount; + const frame = async () => { + clock.advance(16); + cockpit.update(); + await settle(); + }; + await frame(); + assert.equal(store.orbital.mount, 'NAUKA'); + // From the first view back to the last. + $('#cockpit-orbital-view-previous').dispatchEvent( + new Event('click', { bubbles: true }), + ); + await settle(); + assert.equal(store.orbital.mount, 'PROGRESS-MS 34'); + await frame(); + // The camera is at the docked vehicle's view (30 m up in this stand-in). + assert.equal(station.heightOf(shots.at(-1)), 30); + assert.equal(cockpit.previousOrbitalView(), true); + await frame(); + assert.equal(store.orbital.mount, 'ZARYA'); + assert.equal(cockpit.nextOrbitalView(), true); + await frame(); + assert.equal(store.orbital.mount, 'PROGRESS-MS 34'); +}); diff --git a/src/ui/cockpitTrackingController.js b/src/ui/cockpitTrackingController.js index 54ff27d670..a39042232b 100644 --- a/src/ui/cockpitTrackingController.js +++ b/src/ui/cockpitTrackingController.js @@ -678,7 +678,7 @@ export function enter({ kind = null } = {}) { 'track', 'track', t('TRACK ACQUIRED'), - t('{label} · NADIR VIEW', { label: info.name }), + this.orbitalViewSignal(info), ); } else if (vessel) { this.pushCockpitSignal( @@ -739,6 +739,14 @@ export function exit({ restoreTracking = true } = {}) { const vesselSubject = this.subjectKind === 'vessel' ? this.subjectId : null; const satelliteSubject = this.subjectKind === 'satellite' ? this.subjectId : null; + // Leaving a view from a station selects the station's home entry (the + // ISS's Nauka, Tiangong's Tianhe), whichever view or entry it ended on: + // the station's first view, and the one it opens on. + const station = this.orbital; + const stationHome = + satelliteSubject !== null && station && station.mount != null + ? (station.mountViews?.[0]?.noradId ?? null) + : null; this.active = false; this.subjectKind = null; this.subjectProvider = null; @@ -810,8 +818,20 @@ export function exit({ restoreTracking = true } = {}) { // Back to the selected vessel's map view, through the layer's own focus. this.services.aisLiveVesselsLayer?.focusSelectedVessel?.(); } else if (restoreTracking && satelliteSubject !== null) { - // Back to the satellite's follow camera, through the layer's own refocus. - this.services.satellitesLayer?.refocusTrackedById?.(satelliteSubject); + // Back to the satellite's follow camera, through the layer's own refocus; + // from a station, on its home entry. + const layer = this.services.satellitesLayer; + let subject = satelliteSubject; + if (stationHome !== null && String(stationHome) !== String(subject)) { + let tracked = false; + try { + tracked = Boolean(layer?.trackById?.(stationHome, { origin: 'user' })); + } catch { + tracked = false; + } + if (tracked) subject = stationHome; + } + layer?.refocusTrackedById?.(subject); } this.syncEntry(); // Return to the card or readout control that opened Cockpit. diff --git a/src/ui/contextPanel.test.mjs b/src/ui/contextPanel.test.mjs index 1ce7eceb6d..2b2eb33ecd 100644 --- a/src/ui/contextPanel.test.mjs +++ b/src/ui/contextPanel.test.mjs @@ -153,3 +153,21 @@ test('the nearby sites search is busy, without native disable, until it settles' assert.equal(button.getAttribute('aria-busy'), 'false'); assert.equal(button.getAttribute('aria-disabled'), 'false'); }); + +test('with Context closed, the collapsible sections are already in the page for PanelChrome', (t) => { + // PanelChrome finds collapsible panels once, at startup, by their collapse + // buttons; Context starts closed, so a section that mounts only while it + // is open would never be registered and its +/- would do nothing. + fixture(t); + assert.equal( + document + .getElementById('global-context-panel') + .classList.contains('collapsed'), + true, + ); + const targets = [ + ...document.querySelectorAll('.panel-collapse-btn[data-collapse-target]'), + ].map((button) => button.dataset.collapseTarget); + for (const id of ['station-panel', 'live-panel', 'radio-panel']) + assert.ok(targets.includes(id), `${id} is there to be registered`); +}); diff --git a/src/ui/kit/bhoteKoshiControls.test.mjs b/src/ui/kit/bhoteKoshiControls.test.mjs index 3f84b89919..84d069decf 100644 --- a/src/ui/kit/bhoteKoshiControls.test.mjs +++ b/src/ui/kit/bhoteKoshiControls.test.mjs @@ -98,10 +98,10 @@ test('the media cards are drawn by their view, not built in script', () => { const source = read('data/bhoteKoshiEmbeddedMedia.js'); assert.doesNotMatch(source, /innerHTML|insertAdjacentHTML|createElementNS/); // Provider scripts and preconnects, the overlay root, and the Facebook - // embed node and its warm host. + // embed node and its warm host. The YouTube API's script is youtubeApi.js's. assert.deepEqual( [...source.matchAll(/createElement\('(\w+)'\)/g)].map((m) => m[1]), - ['script', 'script', 'script', 'link', 'div', 'div', 'div'], + ['script', 'script', 'link', 'div', 'div', 'div'], ); assert.match(source, /renderVue\(\s*h\(BhoteKoshiMediaCards,/); const cards = template(CARDS); diff --git a/src/ui/kit/cockpitControls.test.mjs b/src/ui/kit/cockpitControls.test.mjs index 2d9d20af46..44057c01a3 100644 --- a/src/ui/kit/cockpitControls.test.mjs +++ b/src/ui/kit/cockpitControls.test.mjs @@ -28,16 +28,20 @@ const views = { // Display's and Radio's collapse and launcher buttons, Radio's Enable, // Previous, Play and Next, and the desktop rail's two items and glyphs. 'panels/CockpitUtilityControls.vue': { buttons: 10, icons: 2 }, - // Previous, Next, Auto, the card's collapse and the three page tabs; the - // first, second and fourth draw a glyph. - 'panels/CockpitBriefing.vue': { buttons: 7, icons: 3 }, + // Previous, Next, Auto, the card's collapse and the four page tabs (LIVE + // shows only with a stream); the first, second and fourth draw a glyph. + 'panels/CockpitBriefing.vue': { buttons: 8, icons: 3 }, // Previous, Next, the card's collapse and Weather; three of them draw a // glyph, and the nearest contact's arrow is the fourth. 'panels/CockpitContext.vue': { buttons: 4, icons: 4 }, // A signal row's target and its chevron. 'panels/CockpitSignalList.vue': { buttons: 1, icons: 1 }, - // TLE, Nadir, Zoom out, Zoom in and Sensor. - 'panels/CockpitOrbital.vue': { buttons: 5, icons: 0 }, + // TLE, Nadir, Zoom out, Zoom in and Sensor, and a station's Previous and + // Next view, which draw the two glyphs. + 'panels/CockpitOrbital.vue': { buttons: 7, icons: 2 }, + // The LIVE page's Previous, Next, Play and Try again; the first three draw + // a glyph. + 'panels/CockpitLivePage.vue': { buttons: 4, icons: 3 }, // The range step. 'panels/CockpitRadar.vue': { buttons: 1, icons: 0 }, // The flight plan's arrow. diff --git a/src/ui/liveControls.js b/src/ui/liveControls.js new file mode 100644 index 0000000000..903037aee9 --- /dev/null +++ b/src/ui/liveControls.js @@ -0,0 +1,374 @@ +import { + LIVE_STREAMS, + liveStreamsFor, + youtubeWatchUrl, +} from '../data/liveStreams.js'; +import { createYouTubeLivePlayer } from '../data/youtubeLivePlayer.js'; +import { useLiveStore } from './stores/live.js'; +import { applicationPinia } from './vueRuntime.js'; + +/** The element the LIVE section in Context keeps for the player. */ +export const LIVE_PLAYER_HOST_ID = 'live-player-host'; + +/** + * The element the Cockpit briefing's LIVE page keeps for the player; the one + * used while the Cockpit is on, since the right rail is hidden there. + */ +export const COCKPIT_LIVE_PLAYER_HOST_ID = 'cockpit-live-player-host'; + +/** + * A layer's selected subject can be judged again as it settles (a satellite + * is docked to the station once both orbits have been compared): the keys + * are read again this often while something is selected. + */ +export const LIVE_SUBJECT_REFRESH_MS = 2000; + +/** + * Own the live video: which object is selected (the tracking layers' + * `gev:awareness-subject-selected`), which streams the list attaches to it, + * and the one player. The views (the LIVE section in Context and the Cockpit + * briefing's LIVE page) render what this publishes, and the player is built + * only when the viewer presses Play in one of them (`playLive`): YouTube sees + * the viewer's IP address, so selecting a station by click, a link, a scene + * or voice never loads it. The player is built into the view that is shown, + * the section's outside the Cockpit and the page's inside it, and goes when + * that view is hidden (the section collapsed, Context closed, the Cockpit + * page left: `hideLive`), when the Cockpit is entered or left, and when the + * selection moves to an object without that stream or clears. + */ +export class LiveControls { + /** + * @param {{store?: object, actions: {getLayer: (layerId: string) => object|null, + * scheduleLayout?: () => void}, documentRef?: Document, globalRef?: object, + * createPlayer?: typeof createYouTubeLivePlayer, + * streams?: readonly object[], refreshMs?: number}} options + */ + constructor({ + store = useLiveStore(applicationPinia()), + actions, + documentRef = globalThis.document, + globalRef = globalThis, + createPlayer = createYouTubeLivePlayer, + streams = LIVE_STREAMS, + refreshMs = LIVE_SUBJECT_REFRESH_MS, + }) { + this.store = store; + this.actions = actions; + this.documentRef = documentRef; + this.globalRef = globalRef; + this.createPlayer = createPlayer; + this.streams = streams; + this.refreshMs = refreshMs; + this.destroyed = false; + /** The selected object: its layer, id and label; null for none. */ + this.subject = null; + /** The streams on offer for it, and the chosen one's id. */ + this.offered = []; + this.currentId = null; + /** The player, the element and stream it was built for, and its state. */ + this.player = null; + this.playerHost = null; + this.playerStreamId = null; + this.playback = { state: 'idle', reason: null }; + /** Whether the Cockpit is on, which decides the host the player goes in. */ + this.cockpitActive = + documentRef?.body?.classList?.contains?.('cockpit-mode') === true; + this.timer = null; + /** The view last published, as text: the 2 s refresh resends nothing new. */ + this.publishedKey = undefined; + /** The stop held back for one tick after a clear (see `_onCleared`). */ + this.clearGrace = null; + this.listeners = new AbortController(); + const { signal } = this.listeners; + const target = globalRef.addEventListener ? globalRef : null; + target?.addEventListener( + 'gev:awareness-subject-selected', + (event) => this._onSelected(event.detail), + { signal }, + ); + target?.addEventListener( + 'gev:awareness-subject-cleared', + (event) => this._onCleared(event.detail), + { signal }, + ); + target?.addEventListener( + 'gev:cockpit-mode-changed', + (event) => this._onCockpitMode(event.detail?.active === true), + { signal }, + ); + this.owner = store.connect({ + cycleLive: (direction) => this.cycle(direction), + playLive: () => this.play(), + stopLive: () => this.stop(), + retryLive: () => this.play({ restart: true }), + hideLive: (where) => this.hide(where), + }); + store.publish(null); + } + + /** + * A new selection. A player that is on keeps playing when the new subject + * offers the same stream (another entry of the same station: a module, a + * docked vehicle, the Cockpit stepping between views on it); otherwise it + * goes. + */ + _onSelected(detail) { + if (this.destroyed || !detail?.layerId || detail.id == null) return; + this._cancelClearGrace(); + this.subject = { + layerId: detail.layerId, + id: detail.id, + label: String(detail.label ?? detail.id), + }; + if (this.player) { + const offered = liveStreamsFor(this._subjectKeys(), this.streams); + if (offered.some((stream) => stream.id === this.playerStreamId)) + this.currentId = this.playerStreamId; + else this.stop(); + } + this._refresh(); + this._arm(); + } + + /** + * The selection cleared. With a player on, the stop waits one tick: the + * Cockpit stepping between views on a station clears the selection and + * selects the next entry at once, and a player for the same stream should + * not be torn down and rebuilt between the two. + */ + _onCleared(detail) { + if (this.destroyed || !this.subject) return; + if (detail?.layerId && detail.layerId !== this.subject.layerId) return; + this.subject = null; + this._disarm(); + if (this.player && this.globalRef.setTimeout) { + this._cancelClearGrace(); + this.clearGrace = this.globalRef.setTimeout(() => { + this.clearGrace = null; + if (this.destroyed || this.subject) return; + this.stop(); + this._refresh(); + }, 0); + return; + } + this.stop(); + this._refresh(); + } + + _cancelClearGrace() { + if (this.clearGrace !== null) + this.globalRef.clearTimeout?.(this.clearGrace); + this.clearGrace = null; + } + + /** + * The Cockpit went on or off: the view the player was in is hidden now, + * so the player goes. The view now shown offers Play again. + */ + _onCockpitMode(active) { + if (this.destroyed || active === this.cockpitActive) return; + this.cockpitActive = active; + this.stop(); + } + + /** + * A view was hidden (`section`: the LIVE section collapsed or Context + * closed; `cockpit`: the briefing left its LIVE page or went): the player + * goes if it was in that view's screen, so nothing plays unseen. + * @param {'section'|'cockpit'} where + * @returns {boolean} True when a player was removed. + */ + hide(where) { + const id = + where === 'cockpit' ? COCKPIT_LIVE_PLAYER_HOST_ID : LIVE_PLAYER_HOST_ID; + if (!this.player || this.playerHost?.id !== id) return false; + return this.stop(); + } + + /** The element the player belongs in now: the Cockpit page's, or the section's. */ + _host() { + const id = this.cockpitActive + ? COCKPIT_LIVE_PLAYER_HOST_ID + : LIVE_PLAYER_HOST_ID; + return this.documentRef?.getElementById?.(id) ?? null; + } + + /** Read the selected subject's keys again on a timer, while one is selected. */ + _arm() { + this._disarm(); + if (!this.subject || !(this.refreshMs > 0)) return; + this.timer = this.globalRef.setInterval( + () => this._refresh(), + this.refreshMs, + ); + this.timer?.unref?.(); + } + + _disarm() { + if (this.timer !== null) this.globalRef.clearInterval(this.timer); + this.timer = null; + } + + /** The keys the selected subject is known by, from its layer. */ + _subjectKeys() { + if (!this.subject) return []; + const { layerId, id } = this.subject; + const keys = [`${layerId}:${id}`]; + let layer = null; + try { + layer = this.actions.getLayer?.(layerId) ?? null; + } catch { + layer = null; + } + try { + for (const key of layer?.getLiveSubjectKeys?.() ?? []) + if (typeof key === 'string') keys.push(key); + } catch { + // A layer that cannot say keeps its plain key. + } + return keys; + } + + /** Work out the streams on offer and publish. */ + _refresh() { + if (this.destroyed) return; + const offered = liveStreamsFor(this._subjectKeys(), this.streams); + const changed = + offered.length !== this.offered.length || + offered.some((stream, index) => stream.id !== this.offered[index]?.id); + this.offered = offered; + if (!offered.some((stream) => stream.id === this.currentId)) { + // The chosen stream went with the selection: nothing plays on. + if (this.player) this.stop(); + this.currentId = offered[0]?.id ?? null; + } + this._publish(); + if (changed) this.actions.scheduleLayout?.(); + } + + /** Publish `view` unless it is the one published last. */ + _send(view) { + const key = JSON.stringify(view); + if (key === this.publishedKey) return; + this.publishedKey = key; + this.store.publish(view); + } + + _publish() { + if (this.destroyed) return; + if (!this.subject || !this.offered.length) { + this._send(null); + return; + } + const index = Math.max( + 0, + this.offered.findIndex((stream) => stream.id === this.currentId), + ); + const current = this.offered[index]; + this._send({ + label: this.subject.label, + streams: this.offered.map((stream) => ({ + id: stream.id, + title: stream.title, + owner: stream.owner, + })), + index, + count: this.offered.length, + current: { + id: current.id, + title: current.title, + owner: current.owner, + ownerUrl: current.ownerUrl, + note: current.note, + watchUrl: youtubeWatchUrl(current.videoId), + }, + state: this.playback.state, + reason: this.playback.reason, + }); + } + + /** + * Step to the next (+1) or previous (-1) stream on offer, wrapping. A + * playing stream hands over to the new one. + * @returns {boolean} True when the stream changed. + */ + cycle(direction = 1) { + if (this.offered.length < 2) return false; + const index = this.offered.findIndex((s) => s.id === this.currentId); + const next = + (Math.max(index, 0) + (direction < 0 ? -1 : 1) + this.offered.length) % + this.offered.length; + this.currentId = this.offered[next].id; + const wasPlaying = this.player !== null; + this.stop(); + if (wasPlaying) this.play(); + else this._publish(); + return true; + } + + /** + * Start the chosen stream in the host now shown: the one call that loads + * the player, made only by the viewer's Play (or Try again). A player + * already loading or playing that stream in that host is left alone; + * `restart` (Try again) builds a fresh one regardless. + * @returns {boolean} True when a player is loading or playing afterwards. + */ + play({ restart = false } = {}) { + if (this.destroyed) return false; + const stream = this.offered.find((s) => s.id === this.currentId); + const host = this._host(); + if (!stream || !host) return false; + const running = + this.playback.state === 'loading' || this.playback.state === 'playing'; + if ( + !restart && + this.player && + running && + this.playerHost === host && + this.playerStreamId === stream.id + ) + return true; + this.stop(); + this.playback = { state: 'loading', reason: null }; + this.playerHost = host; + this.playerStreamId = stream.id; + this.player = this.createPlayer({ + host, + videoId: stream.videoId, + documentRef: this.documentRef, + globalRef: this.globalRef, + onChange: ({ state, reason }) => { + if (this.destroyed) return; + this.playback = { state, reason }; + this._publish(); + }, + }); + this._publish(); + return true; + } + + /** Remove the player; the screen goes dark. */ + stop() { + const had = this.player !== null; + this.player?.destroy(); + this.player = null; + this.playerHost = null; + this.playerStreamId = null; + if (had || this.playback.state !== 'idle') { + this.playback = { state: 'idle', reason: null }; + this._publish(); + } + return had; + } + + destroy() { + if (this.destroyed) return; + this._cancelClearGrace(); + this.stop(); + this.destroyed = true; + this._disarm(); + this.listeners.abort(); + this.store.detach(this.owner); + this.store.publish(null); + } +} diff --git a/src/ui/liveControls.test.mjs b/src/ui/liveControls.test.mjs new file mode 100644 index 0000000000..1c374a61ff --- /dev/null +++ b/src/ui/liveControls.test.mjs @@ -0,0 +1,442 @@ +// src/ui/liveControls.test.mjs — LiveControls owns the live video: the +// selected object's streams, the one player, which screen it is built into, +// and when it goes. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + COCKPIT_LIVE_PLAYER_HOST_ID, + LIVE_PLAYER_HOST_ID, + LiveControls, +} from './liveControls.js'; +import { createOwners } from './stores/owners.js'; + +const STREAMS = Object.freeze([ + { + id: 'one', + platform: 'youtube', + videoId: 'AAAAAAAAAAA', + title: 'First', + owner: 'Owner', + ownerUrl: 'https://www.youtube.com/@owner', + subjects: ['station:test'], + note: 'note', + }, + { + id: 'two', + platform: 'youtube', + videoId: 'BBBBBBBBBBB', + title: 'Second', + owner: 'Owner', + ownerUrl: 'https://www.youtube.com/@owner', + subjects: ['station:test'], + note: 'note', + }, + { + id: 'other', + platform: 'youtube', + videoId: 'CCCCCCCCCCC', + title: 'Elsewhere', + owner: 'Owner', + ownerUrl: 'https://www.youtube.com/@owner', + subjects: ['station:other'], + note: 'note', + }, +]); + +function fixture({ + withHost = true, + withCockpitHost = true, + cockpitMode = false, +} = {}) { + const globalRef = new EventTarget(); + const intervals = []; + globalRef.setInterval = (callback, ms) => { + const id = intervals.length + 1; + intervals.push({ id, callback, ms, cleared: false }); + return id; + }; + globalRef.clearInterval = (id) => { + const timer = intervals.find((entry) => entry.id === id); + if (timer) timer.cleared = true; + }; + const timeouts = []; + globalRef.setTimeout = (callback, ms) => { + timeouts.push({ callback, ms, done: false }); + return timeouts.length; + }; + globalRef.clearTimeout = (id) => { + if (timeouts[id - 1]) timeouts[id - 1].done = true; + }; + /** Run the timeouts due now, as the next tick would. */ + const tick = () => { + for (const timeout of timeouts.splice(0)) + if (!timeout.done) timeout.callback(); + }; + const host = { id: LIVE_PLAYER_HOST_ID }; + const cockpitHost = { id: COCKPIT_LIVE_PLAYER_HOST_ID }; + const documentRef = { + getElementById: (id) => { + if (id === LIVE_PLAYER_HOST_ID) return withHost ? host : null; + if (id === COCKPIT_LIVE_PLAYER_HOST_ID) + return withCockpitHost ? cockpitHost : null; + return null; + }, + body: { + classList: { contains: (name) => cockpitMode && name === 'cockpit-mode' }, + }, + }; + const published = []; + const store = { + ...createOwners(), + publish: (view) => published.push(view), + }; + let keys = []; + const layer = { getLiveSubjectKeys: () => keys }; + const layouts = []; + const players = []; + const createPlayer = (options) => { + const player = { + options, + destroyed: 0, + destroy: () => (player.destroyed += 1), + }; + players.push(player); + return player; + }; + const controls = new LiveControls({ + store, + actions: { + getLayer: (layerId) => (layerId === 'satellites' ? layer : null), + scheduleLayout: () => layouts.push(1), + }, + documentRef, + globalRef, + createPlayer, + streams: STREAMS, + refreshMs: 2000, + }); + const dispatch = (type, detail) => + globalRef.dispatchEvent(new CustomEvent(type, { detail })); + const select = (detail) => + dispatch('gev:awareness-subject-selected', { + layerId: 'satellites', + id: 25544, + label: 'ISS (ZARYA)', + ...detail, + }); + const view = () => published.at(-1); + const running = () => intervals.filter((timer) => !timer.cleared); + return { + controls, + store, + published, + view, + dispatch, + select, + setKeys: (next) => (keys = next), + players, + layouts, + intervals, + running, + tick, + host, + cockpitHost, + }; +} + +test('nothing selected publishes no section; a selection with streams publishes them', () => { + const f = fixture(); + assert.equal(f.view(), null); + f.setKeys(['station:test']); + f.select(); + const view = f.view(); + assert.equal(view.label, 'ISS (ZARYA)'); + assert.equal(view.count, 2); + assert.equal(view.index, 0); + assert.deepEqual( + view.streams.map((stream) => stream.id), + ['one', 'two'], + ); + assert.equal(view.current.id, 'one'); + assert.equal( + view.current.watchUrl, + 'https://www.youtube.com/watch?v=AAAAAAAAAAA', + ); + assert.equal(view.state, 'idle'); + assert.equal( + f.layouts.length, + 1, + 'the rail is laid out once the section appears', + ); + assert.equal(f.running().length, 1, 'the subject is re-read on a timer'); + assert.equal(f.running()[0].ms, 2000); +}); + +test('a selection no stream names keeps the section away; the plain key counts too', () => { + const f = fixture(); + f.select(); + assert.equal(f.view(), null); + assert.equal(f.layouts.length, 0); + // A stream attached to a layer's own `:` key needs no layer help. + const g = fixture(); + g.setKeys([]); + g.select({ layerId: 'satellites', id: 'x' }); + assert.equal(g.view(), null); +}); + +test('the layer is asked again on the timer: an entry that settles as docked gains the streams', () => { + const f = fixture(); + f.select(); + assert.equal(f.view(), null); + f.setKeys(['station:test']); + f.running()[0].callback(); + assert.equal(f.view()?.count, 2); + assert.equal(f.layouts.length, 1); + // Unchanged keys do not lay out again. + f.running()[0].callback(); + assert.equal(f.layouts.length, 1); +}); + +test('playLive builds the player for the chosen stream in the section, once; Try again builds it anew', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + assert.equal( + f.players.length, + 0, + 'the views ask; selection alone builds nothing', + ); + assert.equal(f.store.act('playLive'), true); + assert.equal(f.players.length, 1); + assert.equal(f.players[0].options.videoId, 'AAAAAAAAAAA'); + assert.equal(f.players[0].options.host, f.host); + assert.equal(f.view().state, 'loading'); + // Asked again while loading or playing, the same player stays. + assert.equal(f.store.act('playLive'), true); + f.players[0].options.onChange({ state: 'playing', reason: null }); + assert.equal(f.store.act('playLive'), true); + assert.equal(f.players.length, 1, 'no second player for the same stream'); + assert.equal(f.players[0].destroyed, 0); + assert.equal(f.view().state, 'playing'); + f.players[0].options.onChange({ state: 'offline', reason: 'ended' }); + assert.equal(f.view().state, 'offline'); + assert.equal(f.view().reason, 'ended'); + assert.equal(f.store.act('stopLive'), true); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.view().state, 'idle'); + // Try again builds a fresh player. + assert.equal(f.store.act('retryLive'), true); + assert.equal(f.players.length, 2); +}); + +test('Play without the host element in the page, or without a selection, does nothing', () => { + const noHost = fixture({ withHost: false }); + noHost.setKeys(['station:test']); + noHost.select(); + assert.equal(noHost.store.act('playLive'), false); + assert.equal(noHost.players.length, 0); + const idle = fixture(); + assert.equal(idle.store.act('playLive'), false); +}); + +test('the arrows step through the streams, wrapping, and a playing stream hands over', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + assert.equal(f.store.act('cycleLive', 1), true); + assert.equal(f.view().current.id, 'two'); + assert.equal(f.store.act('cycleLive', 1), true); + assert.equal(f.view().current.id, 'one', 'wraps forward'); + assert.equal(f.store.act('cycleLive', -1), true); + assert.equal(f.view().current.id, 'two', 'wraps backward'); + assert.equal(f.players.length, 0, 'stepping while idle loads nothing'); + f.store.act('playLive'); + f.store.act('cycleLive', 1); + assert.equal(f.players.length, 2); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.players[1].options.videoId, 'AAAAAAAAAAA'); + assert.equal(f.view().state, 'loading'); +}); + +test('with one stream there is nothing to cycle', () => { + const f = fixture(); + f.setKeys(['station:other']); + f.select(); + assert.equal(f.view().count, 1); + assert.equal(f.store.act('cycleLive', 1), false); + assert.equal(f.view().current.id, 'other'); +}); + +test('a new selection stops the stream; the same entry selected again keeps it', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + f.select({ origin: 'pick' }); + assert.equal(f.players[0].destroyed, 0, 'the same subject plays on'); + f.setKeys(['station:other']); + f.select({ id: 99999, label: 'OTHER' }); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.view().label, 'OTHER'); + assert.equal(f.view().current.id, 'other'); + assert.equal(f.view().state, 'idle'); +}); + +test('clearing the selection takes the section down; another layer clearing does not', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + f.dispatch('gev:awareness-subject-cleared', { layerId: 'flights' }); + assert.equal(f.view().count, 2, 'another layer clearing is not ours'); + f.dispatch('gev:awareness-subject-cleared', { layerId: 'satellites' }); + assert.equal(f.running().length, 0, 'the timer stops with the selection'); + // The stop waits a tick, for a selection that moves straight on. + assert.equal(f.players[0].destroyed, 0); + f.tick(); + assert.equal(f.view(), null); + assert.equal(f.players[0].destroyed, 1); +}); + +test('a selection that moves straight on to an entry with the same stream keeps the player', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + // The Cockpit stepping to the next view on the station: cleared, then the + // next entry selected, in one go. + f.dispatch('gev:awareness-subject-cleared', { layerId: 'satellites' }); + f.select({ id: 49044, label: 'ISS (NAUKA)' }); + f.tick(); + assert.equal(f.players.length, 1, 'not rebuilt'); + assert.equal(f.players[0].destroyed, 0); + assert.equal(f.view().label, 'ISS (NAUKA)'); + assert.equal(f.view().current.id, 'one'); + // One without that stream stops it. + f.dispatch('gev:awareness-subject-cleared', { layerId: 'satellites' }); + f.setKeys(['station:other']); + f.select({ id: 99999, label: 'OTHER' }); + f.tick(); + assert.equal(f.players[0].destroyed, 1); +}); + +test('entering or leaving the Cockpit removes the player: the view now shown offers Play again', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + f.players[0].options.onChange({ state: 'playing', reason: null }); + f.dispatch('gev:cockpit-mode-changed', { active: true }); + assert.equal(f.players[0].destroyed, 1, 'the rail is hidden in the Cockpit'); + assert.equal(f.players.length, 1, 'nothing is built by itself'); + assert.equal(f.view().state, 'idle'); + // The same state again changes nothing. + f.dispatch('gev:cockpit-mode-changed', { active: true }); + assert.equal(f.players.length, 1); + // Play in the Cockpit's page builds it in that page's screen. + assert.equal(f.store.act('playLive'), true); + assert.equal(f.players[1].options.host, f.cockpitHost); + f.dispatch('gev:cockpit-mode-changed', { active: false }); + assert.equal(f.players[1].destroyed, 1); + assert.equal(f.players.length, 2); +}); + +test('a view that is hidden removes the player only when it is in that view', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + assert.equal(f.store.act('hideLive', 'cockpit'), false, 'not in the page'); + assert.equal(f.players[0].destroyed, 0); + assert.equal(f.store.act('hideLive', 'section'), true); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.view().state, 'idle'); + assert.equal(f.store.act('hideLive', 'section'), false, 'nothing left'); +}); + +test('selecting a station with streams builds no player until Play', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.select({ origin: 'pick' }); + f.dispatch('gev:cockpit-mode-changed', { active: true }); + f.dispatch('gev:cockpit-mode-changed', { active: false }); + assert.equal(f.players.length, 0); + assert.equal(f.view().state, 'idle'); + f.store.act('playLive'); + assert.equal(f.players.length, 1); +}); + +test('the Cockpit going on or off with nothing playing builds nothing', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.dispatch('gev:cockpit-mode-changed', { active: true }); + f.dispatch('gev:cockpit-mode-changed', { active: false }); + assert.equal(f.players.length, 0); + assert.equal(f.view().state, 'idle'); +}); + +test("entering the Cockpit without the page's screen in the page removes the player", () => { + const f = fixture({ withCockpitHost: false }); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + f.dispatch('gev:cockpit-mode-changed', { active: true }); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.players.length, 1); + assert.equal( + f.view().state, + 'idle', + 'the view starts it once its screen is there', + ); + assert.equal(f.store.act('playLive'), false, 'still no screen'); +}); + +test("constructed with the Cockpit already on, playLive uses the page's screen", () => { + const f = fixture({ cockpitMode: true }); + f.setKeys(['station:test']); + f.select(); + assert.equal(f.store.act('playLive'), true); + assert.equal(f.players[0].options.host, f.cockpitHost); +}); + +test('the chosen stream going from the list stops it and picks the first that remains', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('cycleLive', 1); + f.store.act('playLive'); + f.setKeys(['station:other']); + f.running()[0].callback(); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.view().current.id, 'other'); + assert.equal(f.view().state, 'idle'); +}); + +test('destroy stops the stream, detaches the actions and publishes nothing', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + f.store.act('playLive'); + f.controls.destroy(); + assert.equal(f.players[0].destroyed, 1); + assert.equal(f.view(), null); + assert.equal(f.store.act('playLive'), undefined, 'no owner answers'); + assert.equal(f.running().length, 0); + const before = f.published.length; + f.select(); + assert.equal(f.published.length, before, 'events after destroy are ignored'); +}); + +test('the 2 s refresh publishes nothing when nothing changed', () => { + const f = fixture(); + f.setKeys(['station:test']); + f.select(); + const count = f.published.length; + for (const timer of f.running()) timer.callback(); + for (const timer of f.running()) timer.callback(); + assert.equal(f.published.length, count, 'the same view is not sent again'); + f.store.act('playLive'); + assert.ok(f.published.length > count, 'a change is'); +}); diff --git a/src/ui/livePanel.test.mjs b/src/ui/livePanel.test.mjs new file mode 100644 index 0000000000..7ea50af895 --- /dev/null +++ b/src/ui/livePanel.test.mjs @@ -0,0 +1,261 @@ +// src/ui/livePanel.test.mjs — the LIVE panel renders what LiveControls +// publishes, over happy-dom; it starts the stream as soon as one is chosen, +// collapsed or not, and its controls reach the store's owner. +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createPinia } from 'pinia'; +import { createApp, nextTick } from 'vue'; +import { useLiveStore } from './stores/live.js'; +import { usePanelChromeStore } from './stores/panelChrome.js'; +import LivePanel from './views/panels/LivePanel.vue'; + +const settle = async () => { + await nextTick(); + await nextTick(); +}; + +function fixture(t) { + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const pinia = createPinia(); + const app = createApp(LivePanel).use(pinia); + app.mount(host); + t.after(() => app.unmount()); + const store = useLiveStore(pinia); + const acted = []; + store.connect({ + cycleLive: (direction) => acted.push(['cycle', direction]), + playLive: () => acted.push(['play']), + stopLive: () => acted.push(['stop']), + retryLive: () => acted.push(['retry']), + hideLive: (where) => acted.push(['hide', where]), + }); + const chrome = usePanelChromeStore(pinia); + const token = chrome.connect({ toggle() {}, pin() {} }); + const setOpen = async (open) => { + chrome.publish(token, 'live-panel', { collapsed: !open }); + await settle(); + }; + const $ = (id) => document.getElementById(id); + const publish = async (view) => { + store.publish( + view && { + label: 'ISS (ZARYA)', + streams: [ + { id: 'iss-exterior', title: 'Exterior cameras', owner: 'NASA' }, + { + id: 'iss-crew', + title: 'Live video and space-to-ground audio', + owner: 'NASA', + }, + ], + index: 0, + count: 2, + current: { + id: 'iss-exterior', + title: 'Exterior cameras', + owner: 'NASA', + ownerUrl: 'https://www.youtube.com/@NASA', + note: 'NASA video, via YouTube', + watchUrl: 'https://www.youtube.com/watch?v=ROboUHfPUrU', + }, + state: 'idle', + reason: null, + ...view, + }, + ); + await settle(); + }; + return { $, publish, acted, setOpen, chrome, token }; +} + +test('without a view the section is hidden and shows OFF', (t) => { + const { $, acted } = fixture(t); + assert.equal($('live-panel').hidden, true); + assert.equal($('live-badge-text').textContent, 'OFF'); + assert.equal( + $('live-player-host'), + null, + 'no screen until a stream is offered', + ); + assert.deepEqual(acted, [], 'nothing to start'); +}); + +test('a view shows the subject, the stream and Play under the IP notice, and loads nothing by itself', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({}); + const panel = $('live-panel'); + assert.equal(panel.hidden, false); + assert.equal(panel.querySelector('.live-subject').textContent, 'ISS (ZARYA)'); + assert.equal($('live-stream-title').textContent, 'Exterior cameras · 1/2'); + assert.ok($('live-previous-btn')); + assert.ok($('live-next-btn')); + assert.ok($('live-player-host'), 'the screen is in the page for the player'); + assert.equal( + $('live-watch-link').getAttribute('href'), + 'https://www.youtube.com/watch?v=ROboUHfPUrU', + ); + assert.equal($('live-watch-link').getAttribute('rel'), 'noopener noreferrer'); + assert.deepEqual(acted, [], 'selecting the station loads no player'); + // The notice that YouTube sees the viewer's IP address comes before Play. + const notice = panel.querySelector('.live-privacy'); + const play = $('live-play-btn'); + assert.ok(notice && play); + assert.match(notice.textContent, /sees your IP address/); + assert.equal( + notice.compareDocumentPosition(play) & Node.DOCUMENT_POSITION_FOLLOWING, + Node.DOCUMENT_POSITION_FOLLOWING, + 'the notice is above Play', + ); + assert.equal($('live-status').textContent, 'Click to play'); + play.click(); + assert.deepEqual(acted, [['play']], 'Play is what loads the player'); + // Loading and playing hide Play and ask for nothing more. + await publish({ state: 'loading' }); + assert.equal($('live-play-btn'), null); + await publish({ state: 'playing' }); + assert.deepEqual(acted, [['play']]); +}); + +test('a different stream chosen while idle waits for Play too', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({}); + await publish({ + current: { + id: 'iss-crew', + title: 'Live video and space-to-ground audio', + owner: 'NASA', + ownerUrl: 'https://www.youtube.com/@NASA', + note: '', + watchUrl: 'https://www.youtube.com/watch?v=M3HKLzjvKPc', + }, + index: 1, + }); + assert.deepEqual(acted, []); + assert.ok($('live-play-btn')); +}); + +test('collapsing the section, or Context, stops the player; opening it starts nothing', async (t) => { + const { $, publish, acted, setOpen, chrome, token } = fixture(t); + await setOpen(true); + await publish({ state: 'playing' }); + assert.deepEqual(acted, [], 'already playing: nothing to start'); + await setOpen(false); + assert.deepEqual(acted, [['hide', 'section']], 'nothing plays unseen'); + assert.ok($('live-player-host'), 'the screen keeps its element'); + await setOpen(true); + assert.deepEqual(acted, [['hide', 'section']], 'opening starts nothing'); + chrome.publish(token, 'global-context-panel', { collapsed: true }); + await settle(); + assert.deepEqual(acted, [ + ['hide', 'section'], + ['hide', 'section'], + ]); +}); + +test('while playing the badge says ON AIR with the blinking dot, and there is no card', async (t) => { + const { $, publish } = fixture(t); + await publish({ state: 'playing' }); + const panel = $('live-panel'); + assert.equal(panel.classList.contains('live-on-air'), true); + assert.equal($('live-badge-text').textContent, 'ON AIR'); + assert.equal( + panel.querySelector('.live-dot').classList.contains('on-air'), + true, + ); + assert.equal( + panel.querySelector('.live-screen').classList.contains('active'), + true, + ); + assert.equal(panel.querySelector('.live-card'), null); + assert.equal($('live-status').textContent, 'Live'); +}); + +test('starting shows the waiting dot and says LOADING', async (t) => { + const { $, publish } = fixture(t); + await publish({ state: 'loading' }); + assert.equal($('live-badge-text').textContent, 'LOADING'); + assert.equal( + $('live-panel').querySelector('.live-dot').classList.contains('waiting'), + true, + ); + assert.equal($('live-status').textContent, 'Starting…'); +}); + +test('an offline stream shows the fallback card with Try again, and is not restarted by itself', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({ state: 'offline', reason: 'timeout' }); + const card = $('live-panel').querySelector('.live-card'); + assert.equal(card.classList.contains('offline'), true); + assert.equal(card.querySelector('strong').textContent, 'Stream is offline'); + assert.equal($('live-status').textContent, 'Stream is offline'); + assert.deepEqual(acted, [], 'offline is left to Try again'); + $('live-retry-btn').click(); + assert.deepEqual(acted, [['retry']]); +}); + +test('a stream that cannot be embedded says so, without Try again', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({ state: 'unavailable', reason: 'error-150' }); + const card = $('live-panel').querySelector('.live-card'); + assert.equal(card.classList.contains('unavailable'), true); + assert.equal( + card.querySelector('strong').textContent, + 'This stream cannot play here', + ); + assert.equal($('live-retry-btn'), null); + assert.equal($('live-status').textContent, 'This stream cannot play here'); + assert.deepEqual(acted, []); +}); + +test('the arrows step through the streams', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({ state: 'playing' }); + $('live-next-btn').click(); + $('live-previous-btn').click(); + assert.deepEqual(acted, [ + ['cycle', 1], + ['cycle', -1], + ]); +}); + +test('with one stream there are no arrows and no counter', async (t) => { + const { $, publish } = fixture(t); + await publish({ + count: 1, + streams: [{ id: 'iss-exterior', title: 'Exterior cameras', owner: 'NASA' }], + }); + assert.equal($('live-previous-btn'), null); + assert.equal($('live-next-btn'), null); + assert.equal($('live-stream-title').textContent, 'Exterior cameras'); +}); + +test('publishing null hides the section again', async (t) => { + const { $, publish } = fixture(t); + await publish({}); + await publish(null); + assert.equal($('live-panel').hidden, true); +}); + +test('a language change keeps the same screen element and neither stops nor restarts the stream', async (t) => { + // The player is built into #live-player-host by LiveControls, outside Vue. + // A locale change re-renders the panel's words; the screen must be the + // same element afterwards, with nothing asked of the owner, or the stream + // would be torn down and rebuilt with every language switch. + const { getLocale, setLocale } = await import('../i18n/index.js'); + const originalLocale = getLocale(); + t.after(() => setLocale(originalLocale)); + const { $, publish, acted } = fixture(t); + await publish({ state: 'playing' }); + const screen = $('live-player-host'); + assert.ok(screen, 'the screen is in the page while a stream is offered'); + const marker = screen.appendChild(document.createElement('span')); + const askedBefore = acted.length; + setLocale(originalLocale === 'fr' ? 'es' : 'fr'); + await settle(); + assert.equal($('live-player-host'), screen, 'the same screen element'); + assert.equal(marker.parentNode, screen, 'what LiveControls put in it stays'); + assert.equal(acted.length, askedBefore, 'no play, stop or retry asked'); + assert.equal($('live-panel').hidden, false); +}); diff --git a/src/ui/liveScreen.js b/src/ui/liveScreen.js new file mode 100644 index 0000000000..3d941a817d --- /dev/null +++ b/src/ui/liveScreen.js @@ -0,0 +1,53 @@ +import { storeToRefs } from 'pinia'; +import { computed } from 'vue'; +import { t } from '../i18n/index.js'; +import { useLiveStore } from './stores/live.js'; + +/** + * What the LIVE section in Context and the Cockpit briefing's LIVE page + * share: the live store's view and its state read as words. Each view calls + * this from its setup and renders the result; the controls call LiveControls + * through `act`. Nothing here starts the stream: the views show Play while + * it is `idle`, and the player is loaded only when the viewer presses it. + */ +export function useLiveScreen() { + const store = useLiveStore(); + const { act } = store; + const { view } = storeToRefs(store); + const playing = computed(() => view.value?.state === 'playing'); + const loading = computed(() => view.value?.state === 'loading'); + const offline = computed(() => view.value?.state === 'offline'); + const unavailable = computed(() => view.value?.state === 'unavailable'); + const idle = computed( + () => Boolean(view.value) && view.value.state === 'idle', + ); + const badgeText = computed(() => + playing.value ? t('ON AIR') : loading.value ? t('LOADING') : t('OFF'), + ); + const statusText = computed(() => { + switch (view.value?.state) { + case 'playing': + return t('Live'); + case 'offline': + return t('Stream is offline'); + case 'unavailable': + return t('This stream cannot play here'); + case 'loading': + return t('Starting…'); + default: + return t('Click to play'); + } + }); + + return { + view, + act, + idle, + playing, + loading, + offline, + unavailable, + badgeText, + statusText, + }; +} diff --git a/src/ui/stationPanel.test.mjs b/src/ui/stationPanel.test.mjs new file mode 100644 index 0000000000..30408595b9 --- /dev/null +++ b/src/ui/stationPanel.test.mjs @@ -0,0 +1,215 @@ +// src/ui/stationPanel.test.mjs — the STATION panel renders what the +// satellites layer publishes, over happy-dom; its controls reach the owner. +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createPinia } from 'pinia'; +import { createApp, nextTick } from 'vue'; +import { useStationStore } from './stores/station.js'; +import StationPanel from './views/panels/StationPanel.vue'; + +function fixture(t) { + document.body.replaceChildren(); + const host = document.body.appendChild(document.createElement('div')); + const pinia = createPinia(); + const app = createApp(StationPanel).use(pinia); + app.mount(host); + t.after(() => app.unmount()); + const store = useStationStore(pinia); + const acted = []; + store.connect({ + setStationMode: (mode) => acted.push(['mode', mode]), + chooseStation: (group, choice) => acted.push(['choose', group, choice]), + slideStation: (slider, value) => acted.push(['slide', slider, value]), + resumeStationArm: (group) => acted.push(['resume', group]), + zoomStation: () => acted.push(['zoom']), + }); + const $ = (id) => document.getElementById(id); + const publish = async (view) => { + store.publish( + view && { + key: 'iss', + title: 'ISS', + subject: 'ISS (ZARYA)', + mode: 'automatic', + telemetry: { state: 'live', poseAgeMs: 4200, liveUntilMs: null }, + sunlit: true, + note: 'Computed, not live telemetry.', + groups: [ + { + id: 'sun', + label: 'Sun position', + note: null, + kind: 'choices', + choices: [ + { id: 'follow', label: 'Follow the Sun', active: true }, + { id: 'ahead', label: 'Ahead', active: false }, + ], + }, + { + id: 'arm', + label: 'Canadarm2 (degrees)', + note: null, + kind: 'sliders', + resume: 'Resume sway', + sliders: [ + { + id: 'shoulder', + label: 'Shoulder roll', + min: -120, + max: 120, + value: 15, + }, + ], + }, + ], + zoom: { offered: false, label: 'Zoom to the ISS' }, + ...view, + }, + ); + await nextTick(); + }; + const telemetryText = () => $('station-telemetry').textContent.trim(); + return { $, publish, acted, telemetryText }; +} + +test('without a view the section is hidden', (t) => { + const { $ } = fixture(t); + assert.equal($('station-panel').hidden, true); + assert.equal($('station-badge').textContent, ''); +}); + +test('Automatic shows the subject, the live telemetry age, the Sun line and the note', async (t) => { + const { $, publish, telemetryText } = fixture(t); + await publish({}); + const panel = $('station-panel'); + assert.equal(panel.hidden, false); + assert.equal($('station-badge').textContent, 'ISS'); + assert.equal( + panel.querySelector('.station-subject').textContent, + 'ISS (ZARYA)', + ); + assert.equal($('station-automatic-btn').getAttribute('aria-checked'), 'true'); + assert.equal( + $('station-automatic-btn').classList.contains('is-active'), + true, + ); + assert.equal($('station-manual-btn').getAttribute('aria-checked'), 'false'); + assert.equal(telemetryText(), 'Telemetry · updated 4 s ago'); + assert.equal($('station-telemetry').dataset.tone, 'live'); + assert.equal($('station-sun').textContent, 'Now: in sunlight'); + assert.equal( + panel.querySelectorAll('.station-group').length, + 0, + 'no controls in Automatic', + ); + assert.equal($('station-zoom-btn'), null); +}); + +test('the status line words each telemetry state, with ages in seconds or minutes', async (t) => { + const { $, publish, telemetryText } = fixture(t); + await publish({ + telemetry: { state: 'live', poseAgeMs: 95_000, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'Telemetry · updated 2 min ago'); + await publish({ + telemetry: { state: 'no-signal', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'No signal · computed values'); + assert.equal($('station-telemetry').dataset.tone, 'waiting'); + await publish({ + telemetry: { + state: 'no-signal', + poseAgeMs: 30_000, + liveUntilMs: Date.UTC(2026, 10, 13, 12, 0), + }, + }); + assert.match(telemetryText(), /^No signal since \S.* · computed values$/); + await publish({ + telemetry: { state: 'unavailable', poseAgeMs: 50_000, liveUntilMs: null }, + }); + assert.equal( + telemetryText(), + 'Telemetry unavailable · last update 50 s ago · computed values', + ); + assert.equal($('station-telemetry').dataset.tone, 'off'); + await publish({ + telemetry: { state: 'unavailable', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'Telemetry unavailable · computed values'); + await publish({ + telemetry: { state: 'disabled', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal( + telemetryText(), + 'Telemetry not enabled on this server · computed values', + ); + // A station with no feed at all (Tiangong). + await publish({ + telemetry: { state: 'none', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'No public telemetry · computed values'); + assert.equal($('station-telemetry').dataset.tone, 'off'); + await publish({ + telemetry: { state: 'pending', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'Connecting to telemetry…'); + assert.equal($('station-telemetry').dataset.tone, 'waiting'); + await publish({ + telemetry: { state: 'idle', poseAgeMs: null, liveUntilMs: null }, + }); + assert.equal(telemetryText(), 'Telemetry reads while the model is on screen'); + assert.equal($('station-telemetry').dataset.tone, 'off'); + await publish({ sunlit: false }); + assert.equal($('station-sun').textContent, "Now: in the Earth's shadow"); +}); + +test('Manual shows the groups with the active choice, the sliders and the resume button', async (t) => { + const { $, publish, telemetryText, acted } = fixture(t); + await publish({ mode: 'manual', sunlit: null }); + const panel = $('station-panel'); + assert.equal(panel.classList.contains('station-manual'), true); + assert.equal($('station-manual-btn').getAttribute('aria-checked'), 'true'); + assert.equal(telemetryText(), 'Manual · telemetry paused'); + assert.equal($('station-telemetry').dataset.tone, 'manual'); + assert.equal($('station-sun'), null); + assert.equal(panel.querySelectorAll('.station-group').length, 2); + const follow = panel.querySelector('[data-station-choice="sun:follow"]'); + const ahead = panel.querySelector('[data-station-choice="sun:ahead"]'); + assert.equal(follow.getAttribute('aria-pressed'), 'true'); + assert.equal(follow.classList.contains('is-active'), true); + assert.equal(ahead.getAttribute('aria-pressed'), 'false'); + ahead.click(); + const slider = $('station-slider-shoulder'); + assert.ok(slider, 'the slider is in the page'); + assert.equal( + panel.querySelector('.station-slider output').textContent, + '15°', + ); + panel.querySelector('[data-station-resume="arm"]').click(); + assert.deepEqual(acted, [ + ['choose', 'sun', 'ahead'], + ['resume', 'arm'], + ]); +}); + +test('the mode buttons and the zoom button call the owner', async (t) => { + const { $, publish, acted } = fixture(t); + await publish({ zoom: { offered: true, label: 'Zoom to the ISS' } }); + $('station-manual-btn').click(); + $('station-automatic-btn').click(); + assert.equal($('station-zoom-btn').textContent, 'Zoom to the ISS'); + $('station-zoom-btn').click(); + assert.deepEqual(acted, [ + ['mode', 'manual'], + ['mode', 'automatic'], + ['zoom'], + ]); +}); + +test('publishing null hides the section again', async (t) => { + const { $, publish } = fixture(t); + await publish({}); + await publish(null); + assert.equal($('station-panel').hidden, true); +}); diff --git a/src/ui/stores/live.js b/src/ui/stores/live.js new file mode 100644 index 0000000000..cd177190fb --- /dev/null +++ b/src/ui/stores/live.js @@ -0,0 +1,23 @@ +import { defineStore } from 'pinia'; +import { markRaw, shallowRef } from 'vue'; +import { createOwners } from './owners.js'; + +/** + * The LIVE section in Context as its view renders it: the streams on offer + * for the selected object, the one chosen and the player's state. + * LiveControls presents it (`gev-live` store) and answers the section's + * controls through act(): `cycleLive`, `playLive`, `stopLive`, `retryLive`. + */ +export const useLiveStore = defineStore('gev-live', () => { + /** The presented section; null while nothing selected has a stream. */ + const view = shallowRef(null); + + /** @param {?object} next A fresh presentation; every publish re-renders. */ + function publish(next) { + view.value = next && markRaw(next); + } + + const { connect, detach, act } = createOwners(); + + return { view, publish, connect, detach, act }; +}); diff --git a/src/ui/stores/station.js b/src/ui/stores/station.js new file mode 100644 index 0000000000..732feab518 --- /dev/null +++ b/src/ui/stores/station.js @@ -0,0 +1,25 @@ +import { defineStore } from 'pinia'; +import { markRaw, shallowRef } from 'vue'; +import { createOwners } from './owners.js'; + +/** + * The STATION section in Context as its view renders it: the selected + * station's controls (Automatic or Manual, the moving parts by hand), where + * its joint angles come from right now, and a zoom to it. The satellites + * layer's station panel presents it (`gev-station` store) and answers its + * controls through act(): `setStationMode`, `chooseStation`, `slideStation`, + * `resumeStationArm`, `zoomStation`. + */ +export const useStationStore = defineStore('gev-station', () => { + /** The presented section; null while no station is selected. */ + const view = shallowRef(null); + + /** @param {?object} next A fresh presentation; every publish re-renders. */ + function publish(next) { + view.value = next && markRaw(next); + } + + const { connect, detach, act } = createOwners(); + + return { view, publish, connect, detach, act }; +}); diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index 96f9b39fd4..b644526966 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -1956,6 +1956,61 @@ html:not([lang='en']) .cockpit-brief-tabs button { color: #fff; outline: none; } +/* The LIVE tab is in the markup whether or not a stream is on offer. */ +.cockpit-brief-tabs button[hidden] { + display: none; +} + +/* The briefing's LIVE page: the LIVE section's parts (live.css) in the + card's measure. */ +.cockpit-live-subject { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + color: #fff; + font-size: 9px; + letter-spacing: 0.1em; +} +.cockpit-live-subject strong { + overflow: hidden; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} +.cockpit-live-subject .live-badge { + flex: none; + font-size: 7px; +} +.cockpit-live-pick { + display: flex; + align-items: center; + gap: 5px; + margin: 5px 0 6px; +} +.cockpit-live-pick .live-stream-title { + font-size: 8px; +} +.cockpit-live-pick .live-step .material-symbols-outlined { + font-size: 14px; +} +.cockpit-live-status { + margin: 5px 0 0; + color: rgba(244, 251, 255, 0.7); + font-size: 7px; + letter-spacing: 0.1em; + text-transform: uppercase; +} +.cockpit-live-credit { + margin: 4px 0 0; + color: rgba(182, 226, 241, 0.72); + font: 600 7px/1.2 var(--font-mono); + letter-spacing: 0.08em; + text-transform: uppercase; +} +.cockpit-live-credit a { + color: inherit; +} .cockpit-signal-window[data-layout-mode='rail-right-constrained'] { gap: 5px; } diff --git a/src/ui/styles/cockpitOrbital.css b/src/ui/styles/cockpitOrbital.css index 1b916a9730..4a7aafd502 100644 --- a/src/ui/styles/cockpitOrbital.css +++ b/src/ui/styles/cockpitOrbital.css @@ -482,6 +482,21 @@ color: #fff; outline: none; } +/* A station view's arrows either side of its name. */ +.cockpit-orbital-views .cockpit-orbital-look-readout { + flex: 1; + text-align: center; +} +.cockpit-orbital-view-step { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 1px 4px; + line-height: 1; +} +.cockpit-orbital-view-step .material-symbols-outlined { + font-size: 18px; +} /* The Cockpit HUD in orbit (#cockpit-hud[data-subject='satellite']): the orbital readout names the satellite, so the topline keeps only the diff --git a/src/ui/styles/live.css b/src/ui/styles/live.css new file mode 100644 index 0000000000..c7776b4a1b --- /dev/null +++ b/src/ui/styles/live.css @@ -0,0 +1,238 @@ +/* The LIVE section inside Context: a live stream in the platform's player. */ + +#live-panel[hidden] { + display: none !important; +} + +/* A section inside Context, laid out as the Radio section is: its +/- + hides and shows the body, and it goes with the Context panel. */ +#live-panel { + position: relative; + width: 100%; + min-height: 0; + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid rgba(65, 220, 231, 0.16); +} +.live-panel-inner { + position: relative; + display: flex; + min-height: 0; + flex-direction: column; + gap: 8px; + padding: 10px; + border: 1px solid rgba(65, 220, 231, 0.18); + border-radius: 8px; + background: rgba(2, 15, 20, 0.42); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035); +} +#live-panel .panel-header { + margin-bottom: 0; +} +#right-context-rail #global-context-panel:not(.collapsed) #live-panel { + flex: 0 0 auto; +} +#live-panel.collapsed .live-panel-inner > :not(.panel-header), +#global-context-panel.collapsed #live-panel { + display: none !important; +} + +.live-badge { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 10px; + letter-spacing: 0.12em; +} +.live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.28); + box-shadow: none; + flex: none; +} +.live-dot.waiting { + background: #ffb547; +} +.live-dot.on-air { + background: #ff3b3b; + box-shadow: 0 0 6px rgba(255, 59, 59, 0.9); + animation: live-blink 1.2s ease-in-out infinite; +} +@keyframes live-blink { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.25; + } +} +@media (prefers-reduced-motion: reduce) { + .live-dot.on-air { + animation: none; + } +} + +.live-subject { + font-size: 11px; + letter-spacing: 0.08em; + opacity: 0.85; + margin: 2px 0 6px; +} +.live-pick { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 8px; +} +.live-stream-title { + flex: 1; + text-align: center; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.06em; +} +.live-stream-title small { + font-weight: 400; + opacity: 0.7; +} +.live-step { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 1px 4px; + border: 1px solid rgba(255, 255, 255, 0.25); + border-radius: 2px; + background: rgba(0, 7, 12, 0.6); + color: inherit; + cursor: pointer; + line-height: 1; +} +.live-step .material-symbols-outlined { + font-size: 18px; +} +@media (pointer: coarse) { + .live-step { + min-width: 44px; + min-height: 44px; + } +} +.live-step:hover, +.live-step:focus-visible { + border-color: var(--cockpit-accent, #00dcff); + outline: none; +} + +/* The screen keeps a 16:9 box whether a player is in it or not. */ +.live-screen { + position: relative; + width: 100%; + aspect-ratio: 16 / 9; + background: #000; + border: 1px solid rgba(255, 255, 255, 0.18); + border-radius: 2px; + overflow: hidden; +} +.live-player-host, +.live-player-host iframe { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border: 0; +} +.live-screen:not(.active) .live-player-host { + display: none; +} +/* The poster's Play: the only way the player is loaded. */ +.live-play { + position: absolute; + inset: 0; + margin: auto; + width: max-content; + height: max-content; + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 44px; + min-height: 44px; + padding: 8px 18px; + border: 1px solid rgba(255, 255, 255, 0.45); + border-radius: 4px; + background: rgba(0, 7, 12, 0.72); + color: #f4fbff; + font: inherit; + font-size: 12px; + letter-spacing: 0.1em; + cursor: pointer; +} +.live-play:hover, +.live-play:focus-visible { + border-color: #ff3b3b; + outline: none; +} +.live-play .material-symbols-outlined { + font-size: 20px; +} +.live-card { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px; + text-align: center; + font-size: 11px; + letter-spacing: 0.08em; + background: + radial-gradient( + circle at 50% 40%, + rgba(0, 220, 255, 0.08), + transparent 60% + ), + #050a0f; +} +.live-card-dot { + width: 10px; + height: 10px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.3); +} +.live-card.offline .live-card-dot { + background: #ff3b3b; + opacity: 0.6; +} +.live-card button { + padding: 3px 10px; + border: 1px solid rgba(255, 255, 255, 0.35); + border-radius: 2px; + background: rgba(0, 7, 12, 0.7); + color: #f4fbff; + font: inherit; + letter-spacing: 0.12em; + cursor: pointer; +} +.live-card button:hover, +.live-card button:focus-visible { + border-color: var(--cockpit-accent, #00dcff); + outline: none; +} + +.live-status { + margin: 6px 0 0; + font-size: 11px; + opacity: 0.85; +} +.live-credit, +.live-privacy { + margin: 6px 0 0; + font-size: 10px; + opacity: 0.75; +} +.live-credit a { + color: inherit; +} diff --git a/src/ui/styles/station.css b/src/ui/styles/station.css new file mode 100644 index 0000000000..154098fca1 --- /dev/null +++ b/src/ui/styles/station.css @@ -0,0 +1,147 @@ +/* The STATION section inside Context: a space station's moving parts. */ + +#station-panel[hidden] { + display: none !important; +} + +/* A section inside Context, laid out as the Radio section is: its +/- + hides and shows the body, and it goes with the Context panel. */ +#station-panel { + position: relative; + width: 100%; + min-height: 0; + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid rgba(65, 220, 231, 0.16); +} +.station-panel-inner { + position: relative; + display: flex; + min-height: 0; + flex-direction: column; + gap: 8px; + padding: 10px; + border: 1px solid rgba(65, 220, 231, 0.18); + border-radius: 8px; + background: rgba(2, 15, 20, 0.42); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035); +} +#station-panel .panel-header { + margin-bottom: 0; +} +#right-context-rail #global-context-panel:not(.collapsed) #station-panel { + flex: 0 0 auto; +} +#station-panel.collapsed .station-panel-inner > :not(.panel-header), +#global-context-panel.collapsed #station-panel { + display: none !important; +} + +.station-badge { + font-size: 10px; + letter-spacing: 0.12em; +} +.station-subject { + font-size: 11px; + letter-spacing: 0.08em; + opacity: 0.85; + margin: 2px 0 8px; +} +.station-modes { + display: flex; + gap: 6px; + margin-bottom: 8px; +} +.station-mode, +.station-button { + padding: 3px 10px; + border: 1px solid rgba(255, 255, 255, 0.3); + border-radius: 2px; + background: rgba(0, 7, 12, 0.6); + color: #f4fbff; + font: inherit; + font-size: 10px; + letter-spacing: 0.12em; + cursor: pointer; +} +.station-mode { + flex: 1; + font-weight: 700; +} +.station-mode.is-active, +.station-button.is-active { + border-color: var(--cockpit-accent, #00dcff); + color: var(--cockpit-accent, #00dcff); +} +.station-mode:focus-visible, +.station-button:focus-visible { + outline: 1px solid var(--cockpit-accent, #00dcff); + outline-offset: 1px; +} + +.station-telemetry { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 6px; + font-size: 11px; + letter-spacing: 0.04em; +} +.station-telemetry-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.3); + flex: none; +} +.station-telemetry[data-tone='live'] .station-telemetry-dot { + background: #3bff7a; + box-shadow: 0 0 6px rgba(59, 255, 122, 0.8); +} +.station-telemetry[data-tone='waiting'] .station-telemetry-dot { + background: #ffb547; +} +.station-telemetry[data-tone='manual'] .station-telemetry-dot { + background: var(--cockpit-accent, #00dcff); +} +.station-note { + margin: 0 0 6px; + font-size: 10px; + opacity: 0.75; +} + +.station-group { + margin: 8px 0 0; + padding-top: 8px; + border-top: 1px solid rgba(255, 255, 255, 0.12); +} +.station-label { + font-size: 10px; + letter-spacing: 0.12em; + opacity: 0.85; + margin-bottom: 4px; +} +.station-row { + display: flex; + flex-wrap: wrap; + gap: 4px; +} +.station-sliders { + display: grid; + gap: 4px; +} +.station-slider { + display: grid; + grid-template-columns: 7em 1fr 3.5em; + align-items: center; + gap: 6px; + font-size: 10px; +} +.station-slider output { + text-align: right; + font-variant-numeric: tabular-nums; +} +.station-zoom { + margin-top: 8px; + width: 100%; +} diff --git a/src/ui/views/CockpitView.vue b/src/ui/views/CockpitView.vue index eaed775568..ebccfbe4b9 100644 --- a/src/ui/views/CockpitView.vue +++ b/src/ui/views/CockpitView.vue @@ -25,8 +25,14 @@ import UiIcon from '../kit/UiIcon.vue'; // does, they show the state they start in. The controller also publishes // which surfaces are shown and the utility strip's measured layout; the // layout pass stays with it, and the controls keep its listeners. -const { presence, instruments, route, vision, utilityLayout } = - storeToRefs(useCockpitStore()); +const { + presence, + instruments, + route, + vision, + utilityLayout, + orbital: orbitalView, +} = storeToRefs(useCockpitStore()); const active = computed(() => Boolean(presence.value?.active)); // A vessel subject swaps the aviation readouts for bridge ones. const bridge = computed(() => presence.value?.subjectKind === 'vessel'); @@ -36,6 +42,9 @@ const orbital = computed(() => presence.value?.subjectKind === 'satellite'); // window view whose readouts, labels and texts the provider words. const generic = computed(() => presence.value?.subjectGeneric === true); const labels = computed(() => presence.value?.subjectLabels ?? null); +// The station is ridden from a mount on its 3D model: the arrows look about +// it and Home returns to it, where the nadir picture tilts and returns to nadir. +const stationView = computed(() => (orbitalView.value?.mount ?? null) !== null); const subject = computed(() => generic.value ? presence.value.subjectKind @@ -272,7 +281,7 @@ const tickStyle = (tick) => -
{{ t('ESC EXIT') }}
+
{{ t('ESC EXIT') }}
diff --git a/src/ui/views/panels/CockpitLivePage.vue b/src/ui/views/panels/CockpitLivePage.vue new file mode 100644 index 0000000000..c4bbe20149 --- /dev/null +++ b/src/ui/views/panels/CockpitLivePage.vue @@ -0,0 +1,65 @@ + + + diff --git a/src/ui/views/panels/CockpitOrbital.vue b/src/ui/views/panels/CockpitOrbital.vue index 09b6817fba..461e381975 100644 --- a/src/ui/views/panels/CockpitOrbital.vue +++ b/src/ui/views/panels/CockpitOrbital.vue @@ -15,6 +15,7 @@ import { } from '../../ownerFlag.js'; import { useCockpitStore } from '../../stores/cockpit.js'; import UiButton from '../../kit/UiButton.vue'; +import UiIcon from '../../kit/UiIcon.vue'; // The orbital view's HUD: a nadir reticle over the picture, the satellite's // identity and orbit, and the optical zoom. The Cockpit controller presents @@ -222,6 +223,8 @@ const shownMark = computed(() => const identParts = computed(() => { const o = orbital.value; if (!o) return []; + // A module with no catalog entry (the Cupola) shows its facts instead. + if (Array.isArray(o.facts) && o.facts.length) return [...o.facts]; const parts = []; if (o.noradId !== null && o.noradId !== undefined && o.noradId !== '') parts.push(t('NORAD {id}', { id: String(o.noradId) })); @@ -252,6 +255,11 @@ watch( // The off-nadir tilt; an untilted view shows no readout or reset. const look = computed(() => orbital.value?.look || { offset: false }); +// Riding the station from a mount on its 3D model: the view's name, or null +// for the straight-down picture every other satellite has. +const mount = computed(() => orbital.value?.mount ?? null); +// The station offers several views; with two or more, the arrows step through them. +const mountViews = computed(() => orbital.value?.mountViews ?? 0); // A ground focus names its target in a polite live region; the angle, // which changes every update, is left out of it. const focusText = computed(() => { @@ -272,7 +280,8 @@ const lensStyle = computed(() => {