Merge branch 'main' into feat/paraguay-acaray-yacyreta

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-20 12:19:38 +04:00
commit 17cec5a8bb
167 files changed
+10140 -890

No files matched your search

+12 -1
View File
@@ -432,7 +432,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
| **Yale Bright Star Catalogue** (9,096 stars, sky background) | `sky/` | **Public domain** | ✅ (no restrictions) | "Yale Bright Star Catalogue (Hoffleit & Warren, via CDS)" (courtesy credit) |
| **ESO Milky Way panorama** (eso0932a, blurred cube map, sky background) | `sky/` | **CC BY 4.0** | ✅ (attribution; changes stated) | "ESO/S. Brunier" |
| **CCTV ground heights** (3,445 cameras) | `cctv_ground_heights/` | Precomputed camera placement heights, aligned to work with Google Photorealistic 3D Tiles (folder README) | — | — |
| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 camera-model records) | `src/layers/cctv/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) |
| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 CCTV and 15 ALPR camera-model records) | `src/layers/cctv/modelSpecs.js`, `src/layers/alpr/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) |
### ⚠️ TeleGeography is bundled but NonCommercial
@@ -458,6 +458,17 @@ commercial use with attribution and applicable database share-alike/access
obligations; it does not license the application code. Trimmed test-only tile
fixtures retain their provenance in `src/data/fixtures/README.md`.
A mapped `model` tag that names datasheet hardware adds a spec line to the
selected card. The specs are 16 CC0-1.0 records from the CCTV Camera Database
model-enrichment extract (v2.29.0): 15 compiled into
`src/layers/alpr/modelSpecs.js`, with the bare product codes mappers tag added
as aliases and the SharpV G3 and SharpX XGA titles naming their variant, plus
the CCTV layer's Bosch MIC-7522-Z30 record. Nothing is fetched at runtime, and
an unrecognised tag is never displayed. The default hourly extract does not
carry `model` yet, so the line appears only with a source that supplies it: an
Overpass-backed source or a custom adapter whose records include the optional
`model` field.
### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`)
The CCTV layer's hardware-model specs are a small extract (v2.26.0, plus the Bosch MIC
+7
View File
@@ -0,0 +1,7 @@
- Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware
(Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show
a datasheet spec line on their card, from 16 vendored CCTV Camera Database
records, when their source supplies `model` (an Overpass-backed source or an
integration adapter; the default hourly extract does not yet); unknown,
generation-ambiguous or mis-attributed models show nothing
(bassem chagra, @ch-bas, #1360).
+8
View File
@@ -0,0 +1,8 @@
- Zoomed out, a CCTV ground cell with two or more cameras is now one round
marker with a camera icon and the count (`999`, `1.7K`, `12K` in every
language). It grows with the count, merges with markers it would overlap,
takes in a lone camera right beside it, and zooms in on click until the
group splits. Idle cameras and markers are green. The active camera stays
amber and video cameras violet. Cameras on one mount draw side by side, and
a camera the terrain height service never answered for stands on the drawn
terrain (gekh, #1808).
@@ -0,0 +1,3 @@
- Wheel and trackpad zoom no longer freeze below 150 km while an aircraft or
vessel icon is under the centre of the view: icons drawn over depth write a
depth of exactly 0, which the camera's depth pick ignores (asturksever, #1857).
@@ -0,0 +1,4 @@
- Opening the bare address starts with the default layers again, instead of
bringing back the last session's: a link still restores everything it
carries, so clearing the address always resets the view (samehkhamis,
#1861).
+2
View File
@@ -0,0 +1,2 @@
- The AI chat panel's and voice control's buttons and glyphs are now kit
controls (manjunath22466, samehkhamis, #1862).
+2
View File
@@ -0,0 +1,2 @@
- Draw's and Import's buttons and glyphs are now kit controls
(manjunath22466, samehkhamis, #1863).
@@ -0,0 +1,2 @@
- Space Missions', Contacts', Radio's, the RTL-SDR card's and key setup's
buttons and glyphs are now kit controls (manjunath22466, samehkhamis, #1864).
@@ -0,0 +1,3 @@
- The Bhote Koshi panel's buttons are kit controls, CINEMATIC's pressed
state is Vue state, and its media cards are a Vue view (manjunath22466,
samehkhamis, #1865).
+3
View File
@@ -0,0 +1,3 @@
- Tapping the search box or any other text field on an iPhone no longer leaves
the page zoomed in: the page stays at its own scale and the map does the
zooming (samehkhamis, #1866).
+4
View File
@@ -0,0 +1,4 @@
- An application can name the layers a bare address starts with
(`startLayers` on `createApplicationControls`; none by default): they turn on
without being saved as the user's own choice, and a link's own layers always
win (samehkhamis, #1867).
@@ -0,0 +1,3 @@
- Street Level's photo viewer is a Vue view with kit step buttons, and a
provider switch always gets a fresh panorama canvas (manjunath22466,
samehkhamis, #1868).
+3
View File
@@ -0,0 +1,3 @@
- The view scan now forbids any hand-written button, Material glyph,
checkbox or range in the views, and any control built in script
(manjunath22466, samehkhamis, #1869).
+4
View File
@@ -0,0 +1,4 @@
- A selected vessel or aircraft can be found again from its card: while it is
off screen or has left its feed (the clock moved, or the view moved away),
Find it flies back to it, looking it up where it was at the clock's time
when the feed no longer has it (samehkhamis, #1870).
@@ -0,0 +1,3 @@
- Street Level's photo viewer settles every open and mount, draws one
viewer at a time and states its view contract (manjunath22466,
samehkhamis, #1871).
+3
View File
@@ -0,0 +1,3 @@
- On a phone the search field is centred when no language picker sits beside
it, instead of keeping the picker's room empty on its right (samehkhamis,
#1872).
@@ -0,0 +1,4 @@
- Satellite clouds draw again in a built app instead of showing "Weather
imagery unavailable": the weather shell read its texture limit in a
parameter default, which esbuild compiles for older browsers into code that
throws. A test now refuses the form under `src/` (samehkhamis, #1873).
+3
View File
@@ -0,0 +1,3 @@
- Weather imagery and shells say what they show (`shows`, such as
`'clouds'`), so a renderer can tell such a layer apart; nothing draws
differently (samehkhamis, #1875).
@@ -0,0 +1,2 @@
- On desktop the search dock sits above the World Timeline, which takes the
dock's floor (Sameh Khamis, @samehkhamis, #1876).
@@ -0,0 +1,4 @@
- A plane that lands and is reported on the ground with no altitude stays on
the ground, instead of hanging at its approach height until it takes off
or its 3D model appears; its labels read "On the ground" (samehkhamis,
#1877).
+92 -19
View File
@@ -10,6 +10,20 @@ or an older position from another feed) and one reported slower than 2 m/s
give no course and keep the last; an aircraft with no course at all faces
north.
A selected vessel, aircraft or military aircraft can be found again from its
Context card. While it is off screen, behind the globe or out of its layer's
feed (the clock jumped to a time the feed lacks it, or the view moved away
from it), the card's header shows Find it (`store.locate()`,
`src/ui/stores/entityCard.js`). One still in its feed is flown to (an
aircraft followed). One out of its feed is looked up at the layer's time on
its own track (`locate` on the vessels, flights and military layers, through
`locateOnTrack` in `src/data/locate.js`): the newest point at or before the
world clock's time while the layer follows the clock, else the newest. The card
moves to it and says how old that reading is, and the camera flies there. Once
the feed has it again, its layer selects it again (an aircraft is followed).
With no point at or before the time, the card says there is no reading then and
the camera stays. A followed item is never counted as off screen.
While anything moves (a layer in motion, the camera, a followed contact), the
globe draws at the display's own refresh rate; there is no fixed 60 FPS cap.
The render governor (`src/renderGovernor.js`) caps a parked scene at
@@ -93,6 +107,16 @@ settling. Oblique views below 300 km are left alone.
`QA_BASE_URL=http://localhost:4173 node scripts/qa-zoom-out-guard.mjs` exercises
the real browser controller at desktop and phone widths with keyless fixtures.
Below 150 km Cesium sizes a wheel or pinch zoom step from the depth it picks at
the canvas centre. Icons drawn over depth (aircraft, vessels and most markers:
`disableDepthTest: Infinity`) sit on the near plane and write a depth of
exactly 0 there (`src/render/cesium/iconSetPrimitive.js`), which that pick
reads as nothing drawn, so it keeps the ground under the icon. Any depth past
the near plane would be taken for a surface a near plane's distance from the
camera, and the zoom would stop while an icon is under the centre.
`QA_BASE_URL=http://localhost:5173 node scripts/qa-zoom-under-icon.mjs` checks
this against a dev server (`npm run dev`).
Cesium's free look (Shift+drag, which turns the camera in place) works only
below 1,000 km. Above that height a few drags could turn the whole planet out of
frame and leave only stars, so Shift+drag does nothing there. Cesium also turns
@@ -1191,9 +1215,11 @@ every width, right to left it takes the bottom right at every width, and
`src/ui/creditLineHeight.js` keeps its height in `--credit-line-height`: the
coordinates (and, right to left, the Tactical readout) stay 6px above it
however many lines it wraps onto, and the dock and World Timeline rise when
it is taller than their usual clearance. Narrower than 1120px the dock leaves
no room between the corners, so the coordinates and the readout sit above
the dock, and above the World Timeline while it shows. Outside that layout
it is taller than their usual clearance. The World Timeline takes the dock's
floor and the dock (with the Omnibar's field) sits above it, rising by the
bar's height while it shows, as the plain dock does. Narrower than 1120px the
dock leaves no room between the corners, so the coordinates and the readout
sit above the dock. Outside that layout
Cesium's credit box wraps from 1200px, as before; the phone shell, clean
view, recording and scene playback lay the line out themselves.
The left rail treats the centered World Timeline and voice control as
@@ -1929,6 +1955,16 @@ The row count explicitly says **nearby**: loaded records can be outside the
screen. Cyan camera badges use Manjunath's camera artwork; selection switches to a
larger coral badge with corner brackets and an animated tactical card. Numeric
mapped bearings draw illustrative 90 m direction wedges (not measured coverage).
A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant,
Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras
in October 2026) gets a `SPEC` line on its card from vendored datasheet records
(`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's
`createModelSpecLookup`). A `manufacturer` naming another maker rejects the
match, and the raw tag text is never shown.
Unversioned `AutoVu SharpV` and `AutoVu SharpX` tags show no specs; G1/G2
tags show the G2 (1280x960) record and G3 tags the G3 record. The default
hourly extract has no `model` field yet; an Overpass-backed source or a custom
adapter record's optional `model` fills it.
The shared overlay paints gradients for at most 64 nearby cameras, promoting the
selected camera; farther cameras keep native Cesium badges without wedges.
Native ground-clamped wedges (a ground polyline plus a classification polygon per
@@ -1991,14 +2027,33 @@ directory. Every `/api/cctv` route refuses cross-site browser requests but
accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded
request skips the key-bearing Street View fallback and gets the placeholder.
The CCTV layer draws only the cameras on or near the screen. Zoomed out, it
keeps one camera per ground cell sized to the view, preferring a healthy feed,
and the cells are anchored to the ground so a pan keeps the same cameras. The
active camera always shows. Ground placement and coverage geometry load only
for the cameras in view, with at most two attempts per camera and view regime.
The view pass reruns while the camera moves, paced by its own cost. The camera
picker lists the cameras in view, active camera first, and closes with the
count of cameras outside the view.
The CCTV layer draws only the cameras on or near the screen. Zoomed out, a
ground cell with two or more cameras shows one marker at their mean position. A
green camera pictogram sits under its top edge and the count just below its
middle. The marker grows with the count and paints on the world overlay at
callout resolution. The count covers the whole cell up to the horizon, including
its off-screen cameras. Overlapping markers merge and add their counts. A lone
camera whose icon would touch a marker joins the nearest one, unless the HUD
hides the merged marker. In that case the lone camera keeps its icon and the
count stays where it was before the merge. If the marker there would still cover
the icon, the camera stays in its count when the label fits. The active camera
keeps its own icon beside any marker that would cover it and stays out of the
count. A click on a marker zooms in on its group, at least halving the distance
each time. If halving would leave the group wider or taller than the frame, the
view zooms in on the nearest of the group's ground cells with two or more
cameras. The cockpit or a tracked object holds the view in place. Ambient cards
and coverage attach only to
cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A
camera the height batch never answered for takes the drawn terrain as its ground
once it is near the screen. It reads that height again from much closer, once
the terrain in view has loaded, or when the terrain source changes. A later
Re:Earth answer replaces it. A fallback preserves it. Close up every camera
shows. Cameras on one mount draw side by side and their records keep the mount.
Ground placement has at most two attempts per camera and view regime. The view
pass reruns while the camera moves, paced by its own cost, and when the terrain
in view finishes loading. The camera picker lists the active camera first, then
one camera per visible cell, preferring healthy feeds. It ends with the count of
catalog cameras missing from the list.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them.
@@ -2117,7 +2172,10 @@ trail, a route. A layer under another layer's card or label
(`isUnderOtherCard`) does nothing: it neither acts on its item there nor
treats the click as empty space, so a tracked aircraft stays tracked and a
selection stays selected. Context (`src/ui/entityContextBridge.js`) names
nothing under a card. With no card on top, the scene rules are unchanged.
nothing under a card. A layer can claim a target it paints outside the overlay's
entries (`registerClickClaim`) where no card or label is on top. A CCTV count
claims each click that zooms to it, so a tracked aircraft stays tracked.
With no card or claim on top, the scene rules are unchanged.
World-overlay hit rectangles are what is painted on screen until the next
paint: an overlay change (a click subscriber publishing its selection card)
no longer clears them mid-click, and a paint that draws nothing clears them
@@ -6304,7 +6362,17 @@ caption has no place name (KartaView's is where the drive began) and links to
the full-size photo through the image proxy, since kartaview.org's photo
pages fail for signed-out visitors. The viewer itself is `photoViewer.js`,
shared with Panoramax: each provider hands it a `PhotoSources` table (first
and sharper flat and panorama URLs, and the caption fields).
and sharper flat and panorama URLs, and the caption fields). It builds no
element: it presents the viewer through the layer's
`subscribePhotoViewer()`, which the application shell publishes to the
`gev-street-level-photo` store, and `StreetLevelPhotoViewer` draws it in the
viewer host and hands back the canvas the panorama is drawn on (a fresh one
after a lost context). Each mount and each canvas has a key of its own, so
a viewer never draws on another one's elements, and of two viewers
mounting at once only the later one is drawn (`photoViewers.js`): the
earlier one's mount closes. A view may draw at once or later; what it
reads (`mountKey`, `actions.supersede()`) is `ViewerAdapter.subscribeView`
in `registry.js`. Without a subscribed view these photos cannot open.
Panoramax (`providers/panoramax/`) is keyless and browser-side: the
meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and
@@ -7516,7 +7584,7 @@ silently demoting every later lookup for the session.
ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to
the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active
camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a
periodic white flash). Camera icons are cyan for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES`
periodic white flash). Camera icons are green for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES`
default 36 → 250, hard bound 300), filtered to `camera_status === TURNED_ON` (~815 live of
1,003 rows). City packs (2026-07-04): Caltrans (districts 4/7/11/3 — SF, LA, San Diego,
Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default
@@ -8562,7 +8630,7 @@ pins and share links already supply complete boxes.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
- The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged.
- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only within 3 km of the camera and only for the nearest `MODEL_MAX` — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design.
- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only within 3 km of the camera and only for the nearest `MODEL_MAX` — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. Start-up never reads a stored `gev:layer-state:v2` blob back: a bare URL starts from these defaults and a link from its hash (`src/ui/shareRestoration.js`, `allowLocalState: false`), so clearing the address always resets the view.
- Civilian and military 2D aircraft use the established distance scale: `3×` near
the camera and a `0.5×` floor from 8,000 km outward. A standard 20 px ambient
icon therefore remains about 10 px at globe altitude while retaining the
@@ -8805,13 +8873,18 @@ that era's default (`scf` → 35, `ko` → 5). Every link since carries both fie
explicitly, because the generator always writes them, so no era whose default
later changed depends on a fallback either way.
**They do NOT all persist the same way, and only one of them persists at all.**
**None of them comes back from storage on a bare URL; only the hash carries them.**
Worth stating plainly, because "a default you can override" and "a default that
remembers" are different promises:
- **3D models** have durable storage — `gev:layer-state:v2` in local storage,
written by `LayerStateCoordinator` on explicit intent. A session that stored a
snapshot keeps whatever it stored, across tabs and restarts.
- **3D models** are written to `gev:layer-state:v2` in local storage by
`LayerStateCoordinator` on explicit intent, but start-up never reads it back:
a link restores what its hash carries, and a bare URL starts with the default
layers and options (`src/ui/shareRestoration.js` passes
`allowLocalState: false`), so clearing the address always resets the view.
A host may name the layers a bare URL starts with (`startLayers` on
`createApplicationControls`, e.g. `['flights', 'satellites']`); they are
restored passively, never written to storage, and a link's own layers win.
- **Detection mode/density and scope feather have NO storage key at all.** Their
only durable carrier is the URL hash (`dm`/`dd`, `scf`), written on a 500 ms
debounce. A same-URL reload therefore keeps them only if that debounce already
+1
View File
@@ -107,6 +107,7 @@ Call it before views render. `onLocaleChange` listeners word their text again at
- **Translate the label, not the value.** Layer ids, enums, share-link parameters, API fields, voice tool schemas and feed data (callsigns, vessel and place names) stay as they are; translate only the text shown for them.
- **No `t()` at module top level.** Keep the English in `msg()` and call `t()` when rendering.
- **Numbers and dates** go through `formatNumber`, `formatDate`, `formatRelativeTime` and `formatUtcDayMonth` from `src/i18n/index.js`, which follow the active language.
Compact CCTV count badges painted on the map use Latin digits, a decimal point and a `K` suffix for thousands (`999`, `1.7K`, `12K`). Each badge keeps its width and reads the same across locales. Format these badges only with `formatCameraCount` in `src/data/cctvCellCounts.js`.
- **Identical English means identical translation,** unless you give it a context: `t('CLEAR', { context: 'action' })` (a button) is its own catalog entry, `action|CLEAR`, while `t('CLEAR')` (the sky) stays separate. English output is the same.
- **Text that should stay English** (a brand, a code, a unit symbol) is simply not wrapped.
+119 -8
View File
@@ -84,21 +84,43 @@ Home and End), since each of Core's groups keeps its own keyboard policy, and
once and asks for a change only when it lands on another option. Every
segmented group in Core is a `UiSegmented`; the old `segmentedControl.js`
adapter is gone.
No view hand-writes a control the kit has: every button in an SFC outside
the kit is a `UiButton`, `UiCloseButton` or another kit control, every
Material Symbols glyph a `UiIcon`, every checkbox a `UiCheckbox`, every
select a `UiSelect`, and every range a `UiSlider` except the radio
tuner's and the world timeline's, for the reasons given below. No module
outside the kit, and no SFC's script, builds a button, select, field or
Material glyph in script or writes one as markup in a string, apart from
the globe panel's standalone page (`src/tools/globePanel.js`), plain HTML
a host serves with no Vue or kit, whose Expand and Open buttons are
written as markup (`src/ui/kit/viewControls.test.mjs` pins all of it).
The native fields left are the text, number, password and file inputs
and the two text areas (the chat's message box and the scene dialog's
multiline field) the kit has no control for, and the search fields whose
surfaces this document names. The scene dialog's single-line field takes
its type from its caller, which passes text-like types only.
`UiButton` adds `pressedClass`, Core's class on a pressed toggle (most use
`active`); its pressed classes toggle through `classList`, so a class other
code adds (a voice highlight) survives a press. Every pressed toggle (a
control with `aria-pressed`) in the views is a `UiButton` with `pressed`
except two that keep their own `aria-pressed`: Bhote Koshi's cinematic
button, whose state the event layer writes into the attributes its panel
renders, and Explore's story cards, which are `role="button"` elements,
not buttons (`src/ui/kit/viewControls.test.mjs` pins it). Where the
except Explore's story cards, which keep their own `aria-pressed` since
they are `role="button"` elements, not buttons
(`src/ui/kit/viewControls.test.mjs` pins it). Where the
converted buttons draw Material symbols (the tilt-map button, the Context
header's search and expand, the imported files' row actions and the rail
chips' icons), the glyphs are `UiIcon`s with `:size="null"`, so the site
rules still size them. Core's pressable chips and pills (the rail cards'
chips and action chips, Recent Imagery's day chips, SWAP and ZOOM IN, map
sources, cities and places, and the view context's place and layer chips)
are `UiButton`s too; the key setup chip is still a plain button. `UiChip`
sources, cities and places, the view context's place and layer chips and
the key setup chip) are `UiButton`s too. `UiChip` is a non-interactive
label chip, used by the voice card.
header's search and expand, Draw, Import, the imported files' and drawn
shapes' row actions and the rail chips' icons), the glyphs are `UiIcon`s
with `:size="null"`, so the site rules still size them. Core's pressable
chips and pills (the rail cards' chips and action chips, Recent Imagery's
day chips, SWAP and ZOOM IN, map sources, cities and places, and the view
context's place and layer chips) are `UiButton`s too; the key setup chip
is still a plain button. `UiChip`
is a non-interactive label chip, used by the voice card.
The welcome card's buttons (SKIP, the three start tiles, BROWSE STORIES,
BACK and the main NEXT / ENTER GOD MODE action) are ghost `UiButton`s:
@@ -192,6 +214,51 @@ while a query is typed. The Filter button opens a disclosure and carries
a `UiIcon` with `:size="null"`, so `layer-finder.css` still sizes them
(`src/ui/kit/layerFinderControls.test.mjs` pins it); the search field's
magnifier is `UiSearchField`'s own span.
The Space Missions panel's buttons (a mission's roster row, FOCUS,
REPLAY ASCENT, the replay's pause, PREV, NEXT and SHOW ALL / DESELECT),
the Contacts panel's (PREV, FOCUS, NEXT and a contact's row), the Radio
panel's (Enable, PREV, PLAY, NEXT and STOP), the RTL-SDR card's (Connect,
Locate, Change device, FM, ADS-B, Tune and the two seeks) and the key
setup's (the POWER UP chip, a key's REMOVE, the voice auth toggle and
SAVE KEYS) are ghost `UiButton`s. Radio's Enable and the card's Connect,
FM and ADS-B are pressed toggles with `active`; PLAY and Locate keep
their own `active` class without `aria-pressed`, since their words say
what they will do or have done. The chip's bolt is a `UiIcon` with
`:size="null"`, so provider-settings.css still sizes it
(`src/ui/kit/missionsRadioControls.test.mjs` pins it). The card's FM
frequency stays a native number field, which the kit has no control for,
and the replay's pause, the roster's chevron and the compass arrows are
text characters, not Material symbols.
Utilities' Draw and Import are on the kit. Draw (a pressed toggle with
`active`), Clear and Import are ghost `UiButton`s, their glyphs `UiIcon`s
with `pp-icon` and `:size="null"`. Draw's five colour swatches, in the
toolbar and in a drawn shape's row, are ghost `UiButton`s with
`role="radio"`: they say they are chosen with `aria-checked` and their own
`active` class, never `aria-pressed`. A drawn shape's row (its swatch,
show/hide, the application's row actions and fly to, beside its remove
`UiCloseButton`) is on the kit too, its glyphs `UiIcon`s with
`:size="null"`, so `controls.css` still sizes them; show/hide says what it
does in its name (Show …, Hide …) rather than being pressed. The Street
Level panel's controls already were kit controls; its EXPAND ⤢ ⤡ and its
errors' ⚠ are text characters and stay text
(`src/ui/kit/drawControls.test.mjs` pins it).
The AI chat panel's and the voice control's buttons are ghost
`UiButton`s: the chat's Settings, quick prompts, attachment removes,
Attach layer, Attach a file, Expand conversation, command suggestions,
Expand chat, Add attachment and Send (a submit button that turns into
Stop reply), and the voice control's Open AI chat, Back to chat, Back to
voice, its Preview and Settings tabs and the error tray's DISMISS, beside
the tier button, the mic and the dock and minimize buttons, which already
were. The tier button and dock are pressed toggles; the mic is one only
while its owner has a state for it; the tabs keep `role="tab"` and
`aria-selected`. DISMISS is a text button, not a cross, so it is not a
`UiCloseButton`. The Settings and tab glyphs are `UiIcon`s with
`:size="null"`, so voice-cost.css and voice-card.css still size them
(`src/ui/kit/chatVoiceControls.test.mjs` pins it). The chat bubble,
globe, attach, send and stop, expand and Back glyphs stay inline SVG,
since no Material symbol the page loads draws them the same, and the
message box, file picker and inactivity minutes stay native fields, which
the kit has none of. The voice modules build no controls in script.
The small surfaces' buttons are ghost `UiButton`s: the locale picker's
button, the phone tab bar's tabs, the globe actions' Clear, Share, Reset
and north-up compass, the imagery divider's handle, the scene sharing
@@ -208,6 +275,36 @@ targets in its template, as many as `view.subRings` says, rather than
building them in script; the Omnibar's one other `material-symbols-outlined`
is a stylesheet selector, and the layer disclosure only names a button in a
comment (`src/ui/kit/smallSurfacesControls.test.mjs` pins it).
The Street Level photo viewer of KartaView and Panoramax (the photo, the
panorama canvas and the ‹ › buttons) is `StreetLevelPhotoViewer`, drawn
from what the photo viewer presents rather than built in script. Its ‹ and
› are ghost `UiButton`s, not pressed toggles, whose glyphs are text
characters; the viewer builds no element, and the street-level layer it
belongs to needs no Vue (`src/ui/kit/streetLevelPhotoControls.test.mjs`
pins it). The notice the God's Eye View panel page shows when it loses its
3D graphics (`#status`, in `src/app/globePanelRuntime.js`) stays built in
script: that script is sent to the host as source text and runs in the
host's panel page before the app loads, so it can import nothing.
The Bhote Koshi reconstruction panel's buttons (previous and next beat,
Play, Play scene, Cinematic, Full story, Open original, Lower gorge, the
field reports and Open public map) are ghost `UiButton`s that keep their
`data-action` hooks. Cinematic is a pressed toggle with no pressed class,
since bhote-koshi.css reads its `aria-pressed`: the event layer presents
its state as the record's `pressed`, which the panel passes to the
button, instead of writing an `aria-pressed` attribute. The ‹ and ›
arrows are text characters. The event's embedded media cards (each
anchored witness clip's frame, leader line, title, status and original
link, and the hidden YouTube preload) are drawn by
`BhoteKoshiMediaCards`, which `src/data/bhoteKoshiEmbeddedMedia.js`
renders into its overlay root with `h()` and `render()` on every change,
words again on a locale change, and places after each frame; they hold
no control, and the original link stays a link. The script still builds
the provider SDKs' script and preconnect tags, the overlay root, and the
Facebook player node: that node is warmed hidden before its card exists
and carried, loaded, into the card's player, where the SDK replaces its
contents, so a template could only rebuild it and reload the player; the
X post is likewise built by its SDK inside the player
(`src/ui/kit/bhoteKoshiControls.test.mjs` pins it).
`UiSelect` renders the bare native select (Core's labels sit outside it or
come as an `aria-label`) with `v-model`, `options` and `disabled`;
options that carry their own attributes come through the slot, a caller's
@@ -388,7 +485,20 @@ slot whenever its view is drawn.
(done: `RecentImageryReadout` and its day cards, the same way),
Street level (done: `StreetLevelPanel` renders the `gev-street-level`
store that `StreetLevelControls` publishes to; the controls keep their
listeners, EXPAND, focus and resizing), CCTV (done: `CctvPanel` renders
listeners, EXPAND, focus and resizing; `StreetLevelPhotoViewer`, beside
it in the layer panels, teleports into the viewer host the photo viewer
KartaView and Panoramax mount there, which `createPhotoViewer()`
presents through the layer's `subscribePhotoViewer()` and the
application shell publishes to the `gev-street-level-photo` store, so
the portable `./layers/street-level` entries need no Vue; the viewer
keeps every decision, the photo loading, keys, drag and zoom, and draws
its panorama on the canvas the view hands back, a fresh one after a lost
WebGL context; each mount and canvas is keyed, so no viewer reuses
another's elements, and of two viewers mounting at once only the later
is drawn while the earlier one's mount closes; with no view
subscribed, as when the layer runs without the application shell, a
KartaView or Panoramax photo cannot mount),
CCTV (done: `CctvPanel` renders
the whole panel from the `gev-cctv` store, including the camera picker,
the inline pose editor, the frame preview, source badge and typed
summary; `CctvControls` keeps its listeners, the frame requests and the
@@ -490,7 +600,8 @@ slot whenever its view is drawn.
reconstruction panel (`BhoteKoshiPanel`, last in the context rail,
renders what the event layer publishes to the `gev-bhote-koshi-panel`
store: each control's text, hidden, disabled, value and attributes as
the layer writes them, unchanged frames sending nothing; the rail takes
the layer writes them, and the cinematic button's pressed state,
unchanged frames sending nothing; the rail takes
`bhote-event-active` while it shows), the full-globe celestial ring
(`CelestialRing` teleports into the globe container what `CelestialRing`
in `src/celestialRing.js` publishes to the `gev-celestial-ring` store and
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>God's Eye View</title>
<!-- Raster fallbacks: Safari ignores an SVG apple-touch-icon and falls back to a
screenshot of the page, so an installed app needs a real PNG. Regenerate
+18
View File
@@ -640,6 +640,9 @@
"src/layers/cctv/health.js",
"src/data/cctv.js",
"src/data/cctvCatalogCap.test.mjs",
"src/data/cctvCellCounts.test.mjs",
"src/data/cctvViewPass.test.mjs",
"src/data/cctvViewThinning.test.mjs",
"src/data/cctvDisplayCode.test.mjs",
"src/data/cctvFootprint.js",
"src/data/cctvGroundHeights.test.mjs",
@@ -658,12 +661,17 @@
"src/data/cctvTxdotSource.test.mjs",
"src/layers/cctv/source.test.mjs",
"src/layers/cctv/frames.test.mjs",
"src/layers/cctv/countMarkers.test.mjs",
"src/layers/cctv/count_click_overlay.test.mjs",
"src/layers/cctv/count_click_framing.test.mjs",
"src/layers/cctv/ground.test.mjs",
"src/layers/cctv/rendering.test.mjs",
"src/data/alprCameras.js",
"src/data/alprCameras.test.mjs",
"src/data/dataCredits.test.mjs",
"src/layers/alpr/index.js",
"src/layers/alpr/model.js",
"src/layers/alpr/modelSpecs.test.mjs",
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/presentation.test.mjs",
@@ -1148,6 +1156,8 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/photoViewers.test.mjs",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -1290,6 +1300,7 @@
"src/render/cesium/zoomOutGuard.test.mjs",
"src/app/controls.test.mjs",
"scripts/qa-zoom-out-guard.mjs",
"scripts/qa-zoom-under-icon.mjs",
"src/hudSummaryGate.test.mjs",
"src/hudSummaryLine.test.mjs",
"src/testSupport/stubMgrs.mjs",
@@ -1350,9 +1361,16 @@
"src/ui/kit/welcomeControls.test.mjs",
"src/ui/kit/omnibarControls.test.mjs",
"src/ui/kit/storiesControls.test.mjs",
"src/ui/kit/chatVoiceControls.test.mjs",
"src/ui/kit/cockpitControls.test.mjs",
"src/ui/kit/smallSurfacesControls.test.mjs",
"src/ui/kit/commandDockControls.test.mjs",
"src/ui/kit/streetLevelPhotoControls.test.mjs",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/kit/bhoteKoshiControls.test.mjs",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/ui/kit/missionsRadioControls.test.mjs",
"src/ui/kit/drawControls.test.mjs",
"src/ui/styles/chip.css",
"src/ui/styles/empty-state.css",
"src/ui/rail/RailChips.vue",
+26
View File
@@ -211,7 +211,9 @@
"src/ui/stores/windInspection.js",
"src/ui/views/panels/WindInspectionMarker.vue",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/views/panels/MissionReplayOverlay.vue",
"src/ui/views/panels/StreetLevelPhotoViewer.vue",
"src/ui/stores/bhoteKoshiPanel.js",
"src/ui/views/panels/BhoteKoshiPanel.vue",
"src/ui/stores/celestialRing.js",
@@ -1604,6 +1606,7 @@
"src/ui/stores/status.js",
"src/ui/toast.js",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/stores/celestialRing.js",
"src/ui/stores/worldOverlayActions.js",
"src/ui/stores/awarenessDirection.js",
@@ -1687,6 +1690,7 @@
"src/data/aircraftEmergency.js",
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/data/locate.js",
"src/data/trackingClickGesture.js",
"src/ui/stores/sceneSharing.js",
"src/maps/attribution.js",
@@ -1963,6 +1967,7 @@
"src/layers/flights/policy.js",
"src/render/color.js",
"src/layers/flights/queries.js",
"src/data/locate.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
"src/render/cesium/query.js",
@@ -2114,6 +2119,7 @@
"src/layers/military/policy.js",
"src/render/color.js",
"src/layers/military/queries.js",
"src/data/locate.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
"src/render/cesium/query.js",
@@ -2281,6 +2287,7 @@
"src/layers/vessels/lifecycle.js",
"src/layers/vessels/policy.js",
"src/layers/vessels/queries.js",
"src/data/locate.js",
"src/geo/vector.js",
"src/layers/vessels/rendering.js",
"src/render/camera/poseSignature.js",
@@ -3351,6 +3358,9 @@
"src/data/cctvCards.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cameraFraming.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/iconOrientation.js",
"src/data/screenRotation.js",
@@ -3556,6 +3566,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -3641,6 +3652,8 @@
"src/render/cesium/common.js",
"src/render/cesium/internals.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/cctv/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -4181,6 +4194,7 @@
"src/render/cesium/heights.js",
"src/ui/imagerySplit.js",
"src/data/bhoteKoshiEmbeddedMedia.js",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/data/bhoteKoshiLocator.js",
"src/data/bhoteKoshiIncidentPlaces.js",
"src/data/bhoteKoshiFloodPath.js",
@@ -4313,6 +4327,8 @@
"src/data/cctvFootprint.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/cockpitAirLod.js",
"src/data/cockpitContactDot.js",
@@ -4439,6 +4455,7 @@
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -5150,6 +5167,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -5368,6 +5386,7 @@
"src/ui/stores/windInspection.js",
"src/layers/wind/inspectionMarker.js",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/stores/bhoteKoshiPanel.js",
"src/ui/stores/celestialRing.js",
"src/ui/stores/screenAnnotations.js",
@@ -5521,6 +5540,7 @@
"src/data/entityContext.js",
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/data/locate.js",
"src/render/cesium/cardPreviews.js"
],
"external": [
@@ -5583,6 +5603,7 @@
"src/ui/imagerySplit.js",
"src/maps/imageryComparison.js",
"src/data/bhoteKoshiEmbeddedMedia.js",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/data/bhoteKoshiLocator.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
@@ -5654,6 +5675,8 @@
"src/data/cctvFootprint.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/cockpitAirLod.js",
"src/data/cockpitContactDot.js",
@@ -5728,6 +5751,7 @@
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -5959,6 +5983,7 @@
"src/layers/vessels/lifecycle.js",
"src/layers/vessels/policy.js",
"src/layers/vessels/queries.js",
"src/data/locate.js",
"src/layers/vessels/rendering.js",
"src/render/motion/iconBook.js",
"src/layers/vessels/iconBook.js",
@@ -6213,6 +6238,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env node
/**
* Real-app regression: the wheel zooms with an over-depth icon under the
* centre of the canvas. Start a dev server (`npm run dev`), then run this
* file with QA_BASE_URL set to it.
*
* Below 150 km Cesium sizes a zoom step from the depth it picks at the canvas
* centre. An icon drawn over depth must leave nothing there for that pick, or
* the camera takes the icon (a metre away, on the near plane) for the ground
* and stops zooming.
*/
import assert from 'node:assert/strict';
import puppeteer from 'puppeteer';
const origin = process.env.QA_BASE_URL || 'http://localhost:4173';
const CAMERA_HEIGHT_M = 15_000;
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
...(process.platform === 'darwin'
? ['--use-angle=metal', '--enable-gpu']
: [
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
]),
],
protocolTimeout: 120_000,
});
const errors = [];
try {
const page = await browser.newPage();
page.on('pageerror', (error) => errors.push(error.message));
const viewport = { width: 1200, height: 800 };
await page.setViewport(viewport);
await page.goto(`${origin}/?welcome=0`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(
() =>
window.__godsEyeView?.viewer &&
window.__godsEyeView.viewer.scene.screenSpaceCameraController
.enableInputs &&
document.getElementById('loading-screen')?.classList.contains('hidden'),
{ timeout: 90_000 },
);
const setup = await page.evaluate(async (cameraHeight) => {
const C = await import('/node_modules/cesium/Build/Cesium/index.js');
const { drawOf } = await import('/src/render/rendererOf.js');
const viewer = window.__godsEyeView.viewer;
const scene = viewer.scene;
viewer.camera.cancelFlight();
viewer.trackedEntity = undefined;
// Explicit real renders make each gesture independent of host frame rate.
viewer.useDefaultRenderLoop = false;
const controller = scene.screenSpaceCameraController;
controller.inertiaZoom = 0;
controller.inertiaSpin = 0;
const lon = -30;
const lat = 40; // open Atlantic: nothing else of the app's draws here
const icons = drawOf(viewer).icons({ id: 'qa-zoom-under-icon' });
const item = {
id: 'qa-icon',
pos: C.Cartesian3.fromDegrees(lon, lat, 100),
// Held in place on the GPU, as a live aircraft or vessel icon is.
motion: { kind: 'hold', courseDeg: 0 },
image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#f0f"/></svg>',
)}`,
size: [64, 64],
disableDepthTest: Infinity,
};
const centre = () =>
new C.Cartesian2(
scene.canvas.clientWidth / 2,
scene.canvas.clientHeight / 2,
);
const frame = () => {
scene.requestRender();
viewer.render();
};
const qa = {
height: () => viewer.camera.positionCartographic.height,
setIcon(shown) {
icons.set(shown ? [item] : []);
},
reset() {
viewer.camera.cancelFlight();
viewer.camera.lookAtTransform(C.Matrix4.IDENTITY);
viewer.camera.setView({
destination: C.Cartesian3.fromDegrees(lon, lat, cameraHeight),
orientation: { heading: 0, pitch: -C.Math.PI_OVER_TWO, roll: 0 },
});
frame();
},
async frames(count) {
for (let i = 0; i < count; i++) {
frame();
await new Promise((resolve) => setTimeout(resolve, 0));
}
return qa.height();
},
/** Whether the icon is what a click at the canvas centre picks. */
iconAtCentre() {
const picked = scene.pick(centre());
return JSON.stringify(picked?.id ?? null).includes('qa-icon');
},
/** Metres from the camera to what the depth pick finds at the centre. */
centreDepthM() {
frame();
const point = scene.pickPositionWorldCoordinates(centre());
return point
? C.Cartesian3.distance(point, viewer.camera.positionWC)
: null;
},
};
window.__zoomUnderIconQa = qa;
const gl = scene.context._gl;
const debug = gl.getExtension('WEBGL_debug_renderer_info');
return {
renderer: gl.getParameter(
debug ? debug.UNMASKED_RENDERER_WEBGL : gl.RENDERER,
),
logDepth: scene.logarithmicDepthBuffer,
pickPosition: scene.pickPositionSupported,
};
}, CAMERA_HEIGHT_M);
console.log(
`[INFO] WebGL renderer: ${setup.renderer}; log depth ${setup.logDepth}`,
);
assert.ok(setup.pickPosition, 'the context must support depth picks');
const qa = (method, ...args) =>
page.evaluate(
(name, rest) => window.__zoomUnderIconQa[name](...rest),
method,
args,
);
const x = viewport.width / 2;
const y = viewport.height / 2;
await page.mouse.move(x, y);
/** Wheel `deltaY` at the canvas centre, then the settled camera height. */
const wheel = async (deltaY) => {
await qa('reset');
await page.evaluate(
({ x, y, deltaY }) => {
window.__godsEyeView.viewer.canvas.dispatchEvent(
new WheelEvent('wheel', {
deltaY,
clientX: x,
clientY: y,
bubbles: true,
cancelable: true,
}),
);
},
{ x, y, deltaY },
);
return qa('frames', 40);
};
// The ground alone: what the icon must not change.
await qa('setIcon', false);
await qa('reset');
await qa('frames', 10);
const groundDepth = await qa('centreDepthM');
const groundIn = await wheel(-600);
const groundOut = await wheel(600);
console.log(
`[INFO] no icon: centre depth ${groundDepth?.toFixed(1)} m, wheel in to ${groundIn.toFixed(0)} m, out to ${groundOut.toFixed(0)} m`,
);
assert.ok(groundIn < CAMERA_HEIGHT_M * 0.95, 'control: wheel in zooms in');
assert.ok(groundOut > CAMERA_HEIGHT_M * 1.05, 'control: wheel out zooms out');
await qa('setIcon', true);
await qa('reset');
await page.waitForFunction(
async () => {
await window.__zoomUnderIconQa.frames(1);
return window.__zoomUnderIconQa.iconAtCentre();
},
{ timeout: 30_000 },
);
console.log('[PASS] the icon draws under the canvas centre');
const depth = await qa('centreDepthM');
const zoomedIn = await wheel(-600);
const zoomedOut = await wheel(600);
console.log(
`[INFO] icon at centre: depth pick ${depth === null ? 'finds nothing' : `${depth.toFixed(3)} m away`}, wheel in to ${zoomedIn.toFixed(0)} m, out to ${zoomedOut.toFixed(0)} m`,
);
assert.ok(
depth === null || depth > 100,
`the depth pick must not land on the icon (${depth} m from the camera)`,
);
console.log('[PASS] the depth pick at the centre ignores the icon');
assert.ok(
zoomedIn < CAMERA_HEIGHT_M * 0.95,
`wheel in must zoom in under an icon (height ${zoomedIn.toFixed(1)} m)`,
);
console.log('[PASS] wheel in zooms in');
assert.ok(
zoomedOut > CAMERA_HEIGHT_M * 1.05,
`wheel out must zoom out under an icon (height ${zoomedOut.toFixed(1)} m)`,
);
console.log('[PASS] wheel out zooms out');
assert.ok(await qa('iconAtCentre'), 'the icon must still pick by click');
console.log('[PASS] the icon still picks by click');
assert.deepEqual(errors, [], 'no JavaScript page errors');
console.log('[PASS] no JavaScript page errors');
} finally {
await browser.close();
}
+4
View File
@@ -21,6 +21,8 @@ export { START_VIEW };
* `homeView` is where the title's logo goes back to (with the clock live): the
* start view unless given, for a host whose `startView` only carries a view
* across a rebuild.
* `startLayers` are the layer ids a bare address (one that carries no link)
* starts with: none by default; a host may pass `['flights', 'satellites']`.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
@@ -36,6 +38,7 @@ export function createApplicationControls({
localePicker = true,
startView = START_VIEW,
homeView = startView,
startLayers = [],
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
@@ -59,6 +62,7 @@ export function createApplicationControls({
initialShareCode,
localePicker,
homeView,
startLayers,
});
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
+2 -1
View File
@@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js';
import * as credits from '../../data/dataCredits.js';
import * as sprites from '../../data/spriteOrder.js';
import * as activation from '../../cctvFocusRequest.js';
import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { CITY_POIS } from '../../cityPois.js';
import * as picking from '../../data/pickRegistry.js';
@@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) {
credits,
sprites,
activation,
overlays,
overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry },
locations: { CITY_POIS },
picking,
terrain,
+19 -6
View File
@@ -912,10 +912,12 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
'#command-dock:has(#location-bar:not(.collapsed))',
'#command-dock:has(#control-panel:not(.collapsed))',
];
assert.equal(
omnibarVar('--world-timeline-lift'),
'0px',
'the Omnibar layout holds the timeline lift at 0',
// The dock rises over the World Timeline by world-timeline.css's lift, as
// the plain dock does; the Omnibar scope leaves the lift alone.
assert.doesNotMatch(
fs.readFileSync(path.join(ROOT, 'src/ui/styles/omnibar-dock.css'), 'utf8'),
/--world-timeline-lift\s*:/,
'the Omnibar layout leaves the timeline lift to world-timeline.css',
);
for (const width of WIDTHS.filter((w) => w >= OMNIBAR_MIN_WIDTH)) {
for (const height of HEIGHTS) {
@@ -968,10 +970,21 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
credit.part.startsWith(OMNIBAR_SCOPE),
`the Omnibar owns the credit row at ${width}px`,
);
const dockBottom = omnibarPx(
// The dock rises over the World Timeline from the dock's floor, and
// the bar takes that floor: the floor is what clears the credit.
assert.equal(
dock.decl.value,
'var(--omnibar-dock-raised)',
`Omnibar dock bottom at ${width}px`,
);
assert.equal(
omnibarVar('--omnibar-dock-raised').replace(/\s+/g, ' '),
'calc( var(--omnibar-dock-bottom) + var(--world-timeline-lift, 0px) )',
);
const dockBottom = omnibarPx(
'var(--omnibar-dock-bottom)',
height,
'Omnibar dock bottom',
'Omnibar dock floor',
);
const creditTop =
omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') +
+2
View File
@@ -50,6 +50,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
'surveillance:type': 'ALPR',
operator: 'Flock Safety',
'camera:type': 'fixed',
model: ' L6Q ',
'surveillance:zone': 'traffic',
'camera:direction': '270',
ref: 'ATX-001',
@@ -63,6 +64,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
longitude: -97.7431,
operator: 'Flock Safety',
manufacturer: null,
model: 'L6Q',
cameraType: 'fixed',
zone: 'traffic',
directionDeg: 270,
+173 -179
View File
@@ -6,6 +6,8 @@ import {
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
const YOUTUBE_HOSTS = new Set([
'youtube.com',
@@ -98,6 +100,7 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
let _cardSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
@@ -682,32 +685,61 @@ export function createBhoteKoshiEmbeddedMedia({
let record = null;
let warmRecord = null;
let generation = 0;
// Text the cards show, kept as the calls that word it so a locale change
// words it again. A node is forgotten once it has left the page.
const worded = new Map();
function forgetDetached() {
for (const node of worded.keys())
if (!node.isConnected) worded.delete(node);
let destroyed = false;
// The cards in the root, in the order they were shown: the current one and
// any still leaving. Their text is kept as the calls that word it, so a
// locale change words it again.
const cards = [];
/** Render the cards and the YouTube preload into the root, synchronously. */
function render() {
if (destroyed) return;
const warmFrame = warmRecord?.frame;
renderVue(
h(BhoteKoshiMediaCards, {
warm: warmFrame
? {
key: warmRecord.key,
src: warmFrame.src,
title: warmFrame.title(),
}
: null,
cards: cards.map((current) => ({
id: current.id,
provider: current.source.provider,
portrait: current.portrait,
entering: current.entering,
leaving: current.leaving,
unavailable: current.unavailable,
label: current.label(),
title: current.title(),
status: current.status(),
url: current.source.url,
frame: current.frame && {
src: current.frame.src,
title: current.frame.title(),
onLoad: current.frame.onLoad,
},
bind: current.bind,
})),
}),
root,
);
}
function word(node, property, text) {
let properties = worded.get(node);
if (!properties) worded.set(node, (properties = new Map()));
properties.set(property, text);
writeWord(node, property, text());
}
function writeWord(node, property, value) {
if (property === 'textContent' || property === 'title')
node[property] = value;
else node.setAttribute(property, value);
}
const offLocale = onLocaleChange(() => {
forgetDetached();
for (const [node, properties] of worded)
for (const [property, text] of properties)
writeWord(node, property, text());
});
const offLocale = onLocaleChange(render);
const leavingRecords = new Set();
/** Word a card's status and draw it. */
function setStatus(current, text) {
current.status = text;
render();
}
/** Mark a card unavailable or not and draw it. */
function setUnavailable(current, unavailable) {
current.unavailable = unavailable;
render();
}
const prefersReducedMotion = () =>
globalRef.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ===
true;
@@ -848,9 +880,10 @@ export function createBhoteKoshiEmbeddedMedia({
if (current.exitTimer != null) globalRef.clearTimeout?.(current.exitTimer);
destroyFacebookSession(current.facebookSession);
current.youtubeSession?.destroy();
current.card?.remove?.();
const at = cards.indexOf(current);
if (at !== -1) cards.splice(at, 1);
leavingRecords.delete(current);
forgetDetached();
render();
}
const position = () => {
@@ -866,7 +899,8 @@ export function createBhoteKoshiEmbeddedMedia({
current.enterFrame = scheduleFrame(() => {
current.enterFrame = null;
if (token !== generation || record !== current) return;
current.card.classList.add('is-entering');
current.entering = true;
render();
});
}
}
@@ -888,9 +922,10 @@ export function createBhoteKoshiEmbeddedMedia({
removeRecord(current);
return;
}
current.card.classList.remove('is-entering');
current.card.classList.add('is-leaving');
current.entering = false;
current.leaving = true;
leavingRecords.add(current);
render();
current.exitTimer =
globalRef.setTimeout?.(
() => removeRecord(current),
@@ -900,11 +935,10 @@ export function createBhoteKoshiEmbeddedMedia({
function clearWarm(key = null) {
if (!warmRecord || (key && warmRecord.key !== key)) return;
if (warmRecord.facebookSession)
destroyFacebookSession(warmRecord.facebookSession);
else warmRecord.iframe?.remove?.();
const facebookSession = warmRecord.facebookSession;
warmRecord = null;
forgetDetached();
if (facebookSession) destroyFacebookSession(facebookSession);
else render();
}
function takeWarmFacebook(key, host) {
@@ -944,29 +978,26 @@ export function createBhoteKoshiEmbeddedMedia({
warmRecord = { key, facebookSession };
return true;
}
const iframe = documentRef.createElement('iframe');
iframe.className = 'bhote-embedded-media-warmup';
iframe.src = embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
});
word(iframe, 'title', () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
);
iframe.tabIndex = -1;
iframe.setAttribute('aria-hidden', 'true');
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
root.append(iframe);
warmRecord = { key, iframe };
warmRecord = {
key,
frame: {
src: embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
}),
title: () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
},
};
render();
return true;
}
async function mountX(current, token) {
word(current.status, 'textContent', () => t('LOADING X POST…'));
setStatus(current, () => t('LOADING X POST…'));
try {
const api = await xLoader(documentRef, globalRef);
if (token !== generation || record !== current) return;
@@ -986,14 +1017,12 @@ export function createBhoteKoshiEmbeddedMedia({
throw new Error(
msg('The X post is unavailable or cannot be embedded.'),
);
word(current.status, 'textContent', () =>
t('X POST · PROVIDER CONTROLS'),
);
setStatus(current, () => t('X POST · PROVIDER CONTROLS'));
position();
} catch (error) {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(String(error?.message || msg('X embed unavailable'))),
}),
@@ -1010,16 +1039,14 @@ export function createBhoteKoshiEmbeddedMedia({
session.shouldPlay = autoplay === true;
session.onReady = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('FACEBOOK · PROVIDER CONTROLS'),
);
current.card.classList.remove('is-unavailable');
current.status = () => t('FACEBOOK · PROVIDER CONTROLS');
setUnavailable(current, false);
position();
};
session.onError = (error) => {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(
String(error?.message || msg('Facebook embed unavailable')),
@@ -1030,9 +1057,7 @@ export function createBhoteKoshiEmbeddedMedia({
};
session.onPlaybackBlocked = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
);
setStatus(current, () => t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'));
};
if (session.ready) session.onReady();
else if (session.error) session.onError(session.error);
@@ -1078,104 +1103,69 @@ export function createBhoteKoshiEmbeddedMedia({
if (warmRecord && warmRecord.key !== warmKey) clearWarm();
hide({ preserveWarm: true });
const token = ++generation;
const card = documentRef.createElement('section');
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
card.dataset.provider = source.provider;
word(card, 'aria-label', () =>
t('Embedded {provider} media for {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
const leader = documentRef.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);
leader.classList.add('bhote-embedded-callout-leader');
leader.setAttribute('aria-hidden', 'true');
leader.innerHTML =
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
const player = documentRef.createElement('div');
player.className = 'bhote-embedded-callout-player ui-scroll';
const footer = documentRef.createElement('footer');
const title = documentRef.createElement('strong');
word(title, 'textContent', () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
);
const status = documentRef.createElement('small');
status.setAttribute('role', 'status');
word(status, 'textContent', () =>
t('{provider} · EMBEDDED SOURCE', {
provider: providerLabel(source.provider),
}),
);
const link = documentRef.createElement('a');
link.href = source.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
record = {
const providerName = () => providerLabel(source.provider);
const sourceName = () =>
observation?.title
? bhoteEventText(observation.title)
: t('witness source');
const current = {
id: ++_cardSequence,
key,
source,
anchor,
card,
leader,
player,
status,
portrait: isPortraitMedia(media),
entering: false,
leaving: false,
unavailable: false,
label: () =>
t('Embedded {provider} media for {source}', {
provider: providerName(),
source: sourceName(),
}),
title: () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
status: () =>
t('{provider} · EMBEDDED SOURCE', { provider: providerName() }),
frame: null,
frameElement: null,
card: null,
leader: null,
player: null,
entered: false,
};
if (source.provider === 'x') {
void mountX(record, token);
} else if (source.provider === 'facebook') {
bindFacebook(record, token, warmKey, autoplay);
} else {
const iframe = documentRef.createElement('iframe');
iframe.src = embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
});
const controlled =
// The elements the card's view draws: placed after each frame, filled by
// the provider.
current.bind = (name, element) => {
if (element) current[name] = element;
};
let controlled = false;
if (source.provider === 'youtube') {
const url = new URL(
embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
}),
);
controlled =
autoplay &&
Number.isFinite(Number(endAtSec)) &&
Number(endAtSec) > startAtSec;
if (controlled) {
const url = new URL(iframe.src);
url.searchParams.set('enablejsapi', '1');
if (globalRef.location?.origin)
url.searchParams.set('origin', globalRef.location.origin);
iframe.src = url.href;
}
word(iframe, 'title', () =>
t('{provider} media: {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
iframe.allow =
'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
iframe.addEventListener?.(
'load',
() => {
current.frame = {
src: url.href,
title: () =>
t('{provider} media: {source}', {
provider: providerName(),
source: sourceName(),
}),
onLoad: () => {
if (token !== generation || record?.key !== key) return;
clearWarm(warmKey);
if (
@@ -1184,38 +1174,41 @@ export function createBhoteKoshiEmbeddedMedia({
record.youtubeSession.getState().phase,
)
) {
word(status, 'textContent', () =>
t('{provider} · PROVIDER CONTROLS', {
provider: providerLabel(source.provider),
}),
setStatus(current, () =>
t('{provider} · PROVIDER CONTROLS', { provider: providerName() }),
);
}
position();
},
{ once: true },
);
player.append(iframe);
if (controlled) {
const current = record;
current.youtubeSession = createTrimmedYouTubePlayback({
iframe,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
word(status, 'textContent', () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
};
}
record = current;
cards.push(current);
render();
if (source.provider === 'x') {
void mountX(current, token);
} else if (source.provider === 'facebook') {
bindFacebook(current, token, warmKey, autoplay);
} else if (controlled) {
current.youtubeSession = createTrimmedYouTubePlayback({
iframe: current.frameElement,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
setStatus(current, () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
position();
return true;
@@ -1223,11 +1216,12 @@ export function createBhoteKoshiEmbeddedMedia({
function destroy() {
offLocale();
worded.clear();
hide({ immediate: true });
for (const current of [...leavingRecords]) removeRecord(current);
clearWarm();
removePostRender?.();
destroyed = true;
renderVue(null, root);
root.remove();
}
+171 -68
View File
@@ -1,3 +1,4 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
@@ -12,6 +13,31 @@ import {
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
// The cards draw provider frames; the tests never load their pages, and the
// page's note that each one is not loaded is dropped.
window.happyDOM.settings.disableIframePageLoading = true;
const consoleError = console.error;
console.error = (error, ...rest) => {
if (!/Iframe page loading is disabled/.test(String(error?.message)))
consoleError(error, ...rest);
};
/**
* Embedded media in a fresh globe container of the page, and the overlay
* root it renders into.
*/
function domFixture(options = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const media = createBhoteKoshiEmbeddedMedia({
viewer: { container },
documentRef: document,
globalRef: {},
...options,
});
return { media, container, root: container.firstElementChild };
}
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
const media = createBhoteKoshiEmbeddedMedia({
@@ -186,31 +212,138 @@ test('trimmed YouTube teardown revokes pending SDK and player callbacks', async
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const { media, container, root } = domFixture();
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
const card = root.querySelector('section');
const frame = card.querySelector('iframe');
assert.ok(card.isConnected);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
assert.equal(card.isConnected, false);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(root.querySelector('section'), null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
assert.notEqual(root.querySelector('section iframe'), frame);
media.destroy();
assert.equal(container.children.length, 0);
});
test('a card draws its provider, source, status and original link, and words them again in a new locale', async () => {
const { setLocale } = await import('../i18n/index.js');
const { media, root } = domFixture();
assert.equal(media.show({
observation: { title: 'Flood footage', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k', orientation: 'portrait' } },
anchor: {},
}), true);
const card = root.querySelector('section');
assert.equal(card.className, 'bhote-embedded-callout is-youtube is-portrait');
assert.equal(card.dataset.provider, 'youtube');
assert.equal(card.getAttribute('aria-label'), 'Embedded YOUTUBE media for Flood footage');
const leader = card.firstElementChild;
assert.equal(leader.namespaceURI, 'http://www.w3.org/2000/svg');
assert.equal(leader.getAttribute('class'), 'bhote-embedded-callout-leader');
assert.equal(leader.getAttribute('aria-hidden'), 'true');
assert.equal(leader.querySelector('path').getAttribute('pathLength'), '1');
assert.equal(leader.querySelector('circle').getAttribute('r'), '4');
const body = card.querySelector('.bhote-embedded-callout-body');
assert.equal(body.getAttribute('data-overlay-input'), '');
const player = body.firstElementChild;
assert.equal(player.className, 'bhote-embedded-callout-player ui-scroll');
const frame = player.firstElementChild;
assert.equal(frame.tagName, 'IFRAME');
assert.equal(new URL(frame.src).pathname, '/embed/DbqRexFxv3k');
assert.equal(frame.title, 'YOUTUBE media: Flood footage');
assert.equal(frame.getAttribute('allow'), 'autoplay; encrypted-media; picture-in-picture; fullscreen');
assert.equal(frame.hasAttribute('allowfullscreen'), true);
assert.equal(frame.getAttribute('referrerpolicy'), 'strict-origin-when-cross-origin');
const [title, status, link] = body.querySelector('footer').children;
assert.equal(title.tagName, 'STRONG');
assert.equal(title.textContent, 'FLOOD FOOTAGE');
assert.equal(status.getAttribute('role'), 'status');
assert.equal(status.textContent, 'YOUTUBE · EMBEDDED SOURCE');
assert.equal(link.href, 'https://www.youtube.com/watch?v=DbqRexFxv3k');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(link.textContent, 'OPEN ORIGINAL ↗');
frame.dispatchEvent(new Event('load'));
assert.equal(status.textContent, 'YOUTUBE · PROVIDER CONTROLS');
try {
await setLocale('es');
assert.notEqual(link.textContent, 'OPEN ORIGINAL ↗', 'the link is worded again');
assert.notEqual(status.textContent, 'YOUTUBE · PROVIDER CONTROLS', 'the status is worded again');
assert.ok(root.querySelector('section') === card, 'in place');
} finally {
await setLocale('en');
}
media.destroy();
});
test('an X post is built by the provider inside the card and its failure marks the card', async () => {
let fail = false;
const { media, root } = domFixture({
xLoader: async () => ({ widgets: { createTweet: async (id, target) => {
if (fail) return null;
target.append(Object.assign(document.createElement('div'), { className: 'twitter-tweet', textContent: id }));
return {};
} } }),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://x.com/Indowatchosint/status/2092640554568007958' } };
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const status = card.querySelector('[role="status"]');
assert.equal(status.textContent, 'LOADING X POST…');
await new Promise((resolve) => setTimeout(resolve));
assert.equal(card.querySelector('.bhote-embedded-callout-player .twitter-tweet').textContent, '2092640554568007958');
assert.equal(status.textContent, 'X POST · PROVIDER CONTROLS');
assert.equal(card.classList.contains('is-unavailable'), false);
media.hide({ immediate: true });
fail = true;
assert.equal(media.show({ observation, anchor: {} }), true);
await new Promise((resolve) => setTimeout(resolve));
const failed = root.querySelector('section');
assert.ok(failed.classList.contains('is-unavailable'));
assert.equal(failed.querySelector('[role="status"]').textContent, 'The X post is unavailable or cannot be embedded. OPEN ORIGINAL.');
media.destroy();
});
test('a warmed Facebook player moves into the card and stays through its redraws', async () => {
let ready;
const { media, root } = domFixture({
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() {} },
XFBML: { parse() {} },
}),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://www.facebook.com/reel/1571491657757829' } };
media.warm({ observation });
await Promise.resolve(); await Promise.resolve();
const host = root.querySelector('.bhote-embedded-media-warmup');
const embed = host.querySelector('.fb-video');
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const player = card.querySelector('.bhote-embedded-callout-player');
assert.ok(host.parentNode === player, 'the warmed player is carried over, not rebuilt');
assert.equal(host.className, 'bhote-facebook-player-host');
assert.equal(host.hasAttribute('aria-hidden'), false);
ready({ type: 'video', id: embed.id, instance: { mute() {}, play() {}, pause() {} } });
assert.equal(card.querySelector('[role="status"]').textContent, 'FACEBOOK · PROVIDER CONTROLS');
assert.ok(host.parentNode === player, 'a redraw keeps the provider player');
media.destroy();
});
test('a leaving card animates out and is removed after its exit', () => {
const timers = [];
const { media, root } = domFixture({ globalRef: { setTimeout: (fn) => timers.push(fn), clearTimeout() {} } });
media.show({ observation: { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {} });
const card = root.querySelector('section');
card.hidden = false;
media.hide();
assert.ok(card.isConnected);
assert.ok(card.classList.contains('is-leaving'));
assert.equal(card.classList.contains('is-entering'), false);
timers.forEach((fn) => fn());
assert.equal(card.isConnected, false);
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
@@ -303,28 +436,8 @@ test('Mailung playback stops at source timestamp 0:07 without changing other cli
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
const { media, root } = domFixture(options);
return { media, root };
}
for (const operation of ['pause', 'hide', 'destroy']) {
@@ -343,16 +456,18 @@ test('camera updates retain a preload until the visible player loads', () => {
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
assert.equal(frame.className, 'bhote-embedded-media-warmup');
assert.equal(frame.getAttribute('aria-hidden'), 'true');
assert.equal(frame.tabIndex, -1);
assert.equal(frame.title, 'Preloading YOUTUBE media');
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.ok(root.children[0] === frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
assert.ok(frame.parentNode === root, 'keep the preload while the visible player starts');
root.querySelector('section .bhote-embedded-callout-body > .bhote-embedded-callout-player > iframe')
.dispatchEvent(new Event('load'));
assert.equal(frame.isConnected, false, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
@@ -420,25 +535,9 @@ test('a media card stays between the panels when right-to-left swaps their sides
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
const container = document.body.appendChild(document.createElement('div'));
const viewer = { container, canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
@@ -454,14 +553,18 @@ test('a shown card follows its anchor through the renderer ports', () => {
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef: document, globalRef: {} });
const root = container.firstElementChild;
root.getBoundingClientRect = () => ({ left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
const card = root.querySelector('section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// The leader runs from the anchor to the card's near edge.
assert.equal(card.querySelector('path').getAttribute('d'), `M ${300 + 10 - 352} ${200 + 5 - parseFloat(card.style.top)} L 0 ${Math.max(16, Math.min(360 - 16, 200 + 5 - parseFloat(card.style.top)))}`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
+3 -2
View File
@@ -989,9 +989,10 @@ function createPanelRecords(event) {
textContent: t('▶ PLAY SCENE'),
hidden: true,
}),
// `pressed` is the button's pressed state; the view renders it as one.
cinematicButton: panelRecord({
textContent: t('◉ CINEMATIC'),
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: panelRecord({ textContent: t('↺ FULL STORY') }),
corridorButton: panelRecord(),
@@ -2860,7 +2861,7 @@ export function createBhoteKoshiEventLayer({
'textContent',
_cinematicActive ? t('■ RELEASE CAMERA') : t('◉ CINEMATIC'),
);
setElementAttribute(button, 'aria-pressed', String(_cinematicActive));
setElementProperty(button, 'pressed', _cinematicActive);
return true;
}
+4
View File
@@ -101,6 +101,7 @@ function eventPanel() {
get textContent() { return record().textContent; },
get hidden() { return record().hidden; },
get disabled() { return record().disabled; },
get pressed() { return record().pressed; },
get value() { return typed ?? record().value; },
set value(value) { typed = value; },
getAttribute: (name) => record().attributes[name] ?? null,
@@ -2711,6 +2712,8 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
play.dispatch('click');
assert.equal(layer.getCinematicState().active, true);
assert.equal(layer.getPlaybackState().progress, 0);
const cinematicControl = panel.querySelector('[data-action="cinematic"]');
assert.equal(cinematicControl.pressed, true, 'the cinematic button is pressed while it owns the camera');
assert.equal(layer.getPlaybackState().playing, true);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
@@ -2720,6 +2723,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
panel.querySelector('[data-action="cinematic"]').dispatch('click');
assert.equal(layer.getCinematicState().active, false);
assert.equal(viewer._test.cameraTransforms.length, 2);
assert.equal(cinematicControl.pressed, false, 'releasing the camera unpresses the button');
animationCallbacks[1](91001);
assert.equal(play.textContent, '↺ REPLAY');
const cameraLookCount = viewer._test.cameraLooks.length;
+8 -1
View File
@@ -38,7 +38,7 @@ function presentation(patch = {}) {
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
cinematicButton: record({
textContent: '◉ CINEMATIC',
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
corridorButton: record(),
@@ -156,6 +156,10 @@ test('a later presentation updates the controls in place', async (t) => {
disabled: true,
attributes: { 'aria-label': 'Play Global context' },
});
next.refs.cinematicButton = record({
textContent: '■ RELEASE CAMERA',
pressed: true,
});
next.refs.progressInput = record({ value: '250', hidden: true });
next.refs.imagerySection = record({ hidden: true });
store.publish(next);
@@ -164,6 +168,9 @@ test('a later presentation updates the controls in place', async (t) => {
assert.equal(play.textContent, '▶ PLAY SHOT');
assert.equal(play.disabled, true);
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
const cinematic = $('[data-action="cinematic"]');
assert.equal(cinematic.getAttribute('aria-pressed'), 'true');
assert.equal(cinematic.textContent, '■ RELEASE CAMERA');
assert.ok(
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
);
+1 -1
View File
@@ -1,4 +1,4 @@
import { toRadians } from '../geo/index.js';
import { toRadians } from '../geo/vector.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
+15 -1
View File
@@ -85,7 +85,9 @@ import {
} from '../cctvFocusRequest.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_CAMERA_ICON,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
@@ -353,7 +355,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
}
});
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
test('camera icons are violet for video feeds, green for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
// Every catalog record is placed as it is made, and drawn there.
@@ -385,6 +387,18 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
const image = (record) => icons.item(record.camera.id).image;
const idleImage = image(idleStill);
assert.equal(idleImage, IDLE_CAMERA_ICON);
assert.equal(image(activeVideo), CAMERA_ICON);
assert.equal(image(idleVideo), CAMERA_ICON);
idleStill.camera.feedType = 'hls';
refreshCoverageStyles();
assert.equal(image(idleStill), CAMERA_ICON);
idleStill.camera.feedType = 'image';
refreshCoverageStyles();
assert.equal(image(idleStill), idleImage);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
+2
View File
@@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000;
const RETRY_MAX_MS = 5 * 60 * 1000;
export const CCTV_OVERLAY_SOURCE_ID = 'cctv';
/** The source a CCTV count marker takes clicks as. */
export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count';
export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
fullEnd: CCTV_CARD_SCALE_FULL_M,
midEnd: CCTV_CARD_SCALE_MID_M,
+238
View File
@@ -0,0 +1,238 @@
import { fromDegrees } from '../geo/ellipsoid.js';
/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */
export function formatCameraCount(count) {
if (count < 1000) return String(count);
const thousands =
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
return `${thousands}K`;
}
/** An empty cell and its on-screen picker candidate. */
export function createCameraCell(key) {
return {
key,
count: 0,
latSum: 0,
lonSum: 0,
heightSum: 0,
south: Infinity,
north: -Infinity,
west: Infinity,
east: -Infinity,
low: Infinity,
high: -Infinity,
winner: null,
rank: Infinity,
};
}
/** Accumulate one horizon-visible mount in its ground cell. */
export function addCellCamera(cell, camera) {
const { lat, lon, absoluteHeightM: height = 0 } = camera;
cell.count++;
// Integer sums make the mean independent of catalog order, to about a centimetre.
cell.latSum += Math.round(lat * 1e7);
cell.lonSum += Math.round(lon * 1e7);
cell.heightSum += Math.round(height * 100);
cell.south = Math.min(cell.south, lat);
cell.north = Math.max(cell.north, lat);
cell.west = Math.min(cell.west, lon);
cell.east = Math.max(cell.east, lon);
cell.low = Math.min(cell.low, height);
cell.high = Math.max(cell.high, height);
}
const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180;
/** Mean longitude and latitude of a cell's mounts, in degrees. */
export function cellLonLat(cell) {
return {
lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)),
lat: cell.latSum / (1e7 * cell.count),
};
}
/**
* Geographic mean of the mounts. Its height is the drawn ground under it
* when the cell carries one (`groundM`), since a camera nobody has looked at
* yet may still hold a catalog height far from the terrain; otherwise the
* mean mount height.
*/
export function cellCenter(cell) {
const { lon, lat } = cellLonLat(cell);
return fromDegrees(
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */
export function cellHalfExtents(cell) {
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
return {
halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel),
halfHeightM: 0.5 * (cell.north - cell.south) * 111_320,
};
}
/** A padded sphere over the rectangle and every mount, centred at groundM
* when set, otherwise at the mid mount height. */
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = wrapLongitude((cell.east + cell.west) / 2);
const height = Number.isFinite(cell.groundM)
? cell.groundM
: (cell.high + cell.low) / 2;
const { halfWidthM, halfHeightM } = cellHalfExtents(cell);
const halfWidth = Math.hypot(halfWidthM, halfHeightM);
const vertical = Math.max(cell.high - height, height - cell.low);
const radius = 1.2 * Math.hypot(halfWidth, vertical);
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
}
/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */
function addCell(target, cell) {
// Across the antimeridian a cell joins on the side of the group's mean.
const shift = target.count
? 360 *
Math.round(
(target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9,
)
: 0;
target.count += cell.count;
target.latSum += cell.latSum;
target.lonSum += cell.lonSum + shift * 1e7 * cell.count;
target.heightSum += cell.heightSum;
target.south = Math.min(target.south, cell.south);
target.north = Math.max(target.north, cell.north);
target.west = Math.min(target.west, cell.west + shift);
target.east = Math.max(target.east, cell.east + shift);
target.low = Math.min(target.low, cell.low);
target.high = Math.max(target.high, cell.high);
}
/** Visit the touching pills in this marker's bucket and its eight neighbors. */
function visitNeighbors(marker, grid, gap, visit) {
for (let col = -1; col <= 1; col++) {
for (let row = -1; row <= 1; row++) {
const bucket = grid.get(`${marker.col + col},${marker.row + row}`);
if (!bucket) continue;
for (const other of bucket) {
// Distance between the horizontal centre segments of the two pills.
const extra = marker.halfSegment + other.halfSegment;
const dx = Math.max(0, Math.abs(marker.x - other.x) - extra);
const dy = marker.y - other.y;
const reach = marker.radius + other.radius + gap;
if (dx * dx + dy * dy >= reach * reach) continue;
visit(other, dx * dx + dy * dy, reach);
}
}
}
}
/**
* Merge connected groups of overlapping horizontal pills. Each marker occupies
* one grid bucket. Even the widest pill can only touch its eight neighbors.
* A cell with one camera takes the footprint `sizeFor(1)` gives its icon and
* joins the nearest count it touches. Lone cameras never join each other
* or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways.
* A merged group lists its ground cells in `parts`.
* Ground cells stay intact for the camera picker and individual-icon pass.
*/
export function mergeCountCells(cells, project, sizeFor, gap) {
let columnWidth = 0;
let rowHeight = 0;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count, cell);
columnWidth = Math.max(columnWidth, width + gap);
rowHeight = Math.max(rowHeight, height + gap);
// The view projector reuses its result object.
return {
cell,
x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined,
y: screen?.y,
halfSegment: (width - height) / 2,
radius: height / 2,
};
});
const grid = new Map();
for (const marker of markers) {
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
marker.col = Math.floor(marker.x / columnWidth);
marker.row = Math.floor(marker.y / rowHeight);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
if (marker.cell.count > 1) marker.bucket.add(marker);
}
for (const marker of markers) {
if (marker.cell.count !== 1 || !marker.bucket) continue;
let best = Infinity;
visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => {
const clearance = Math.sqrt(distanceSquared) - reach;
if (clearance < best) {
best = clearance;
marker.nearest = other;
}
});
}
// Only counts were candidates for nearest. Now they can claim lone cameras.
for (const marker of markers)
if (marker.cell.count === 1) marker.bucket?.add(marker);
const members = [];
for (const seed of markers) {
if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue;
members.length = 0;
members.push(seed);
for (const marker of members) {
if (marker.cell.count === 1) continue;
visitNeighbors(marker, grid, gap, (other) => {
if (other.cell.count === 1 && other.nearest !== marker) return;
other.bucket.delete(other);
members.push(other);
});
}
if (members.length === 1) {
seed.result = seed.cell;
} else {
const group = createCameraCell(seed.cell.key);
group.lone = [];
group.parts = [];
for (const { cell } of members) {
addCell(group, cell);
group.parts.push(...(cell.parts ?? [cell]));
if (cell.count === 1) group.lone.push(cell);
else if (cell.lone) group.lone.push(...cell.lone);
}
seed.result = group;
}
}
const groups = [];
for (const marker of markers) {
if (marker.result) groups.push(marker.result);
else if (!marker.bucket || marker.bucket.has(marker))
groups.push(marker.cell);
}
return groups;
}
/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */
export function withoutLoneCameras(group, keep = []) {
const counts = (group.parts ?? []).filter((cell) => cell.count > 1);
if (!counts.length) return null;
const core = createCameraCell(group.key);
core.parts = [...counts, ...keep];
if (keep.length) core.lone = [...keep];
for (const cell of core.parts) addCell(core, cell);
return core;
}
+216
View File
@@ -0,0 +1,216 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fromDegrees } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import { getLocale, setLocale } from '../i18n/index.js';
import {
createCameraCell,
addCellCamera,
cellCenter,
cellBounds,
formatCameraCount,
mergeCountCells,
} from './cctvCellCounts.js';
test('camera counts use Latin digits and K notation whatever the UI language', () => {
const previous = getLocale();
const examples = [
[2, '2'],
[999, '999'],
[1000, '1K'],
[1150, '1.2K'],
[1687, '1.7K'],
[9960, '10K'],
[10000, '10K'],
[12345, '12K'],
[12500, '13K'],
[1000000, '1000K'],
];
try {
setLocale('ar');
for (const [count, label] of examples)
assert.equal(formatCameraCount(count), label);
} finally {
setLocale(previous);
}
});
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
const cameras = [
{ lon: 12, lat: 52, absoluteHeightM: 30 },
{ lon: 12, lat: 52, absoluteHeightM: 40 },
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
];
const cell = createCameraCell();
for (const camera of cameras) addCellCamera(cell, camera);
const expected = fromDegrees(12.001, 52.002, 40);
assert.ok(distance(cellCenter(cell), expected) < 0.001);
const bounds = cellBounds(cell);
for (const { lon, lat, absoluteHeightM } of cameras) {
assert.ok(
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
bounds.radius,
);
}
});
function mergeCounts(sizes, counts, positions) {
const cells = counts.map((count, i) => ({
...createCameraCell(String(i)),
count,
}));
let i = 0;
const groups = mergeCountCells(
cells,
() => positions[i++],
(count) => sizes[count],
4,
);
return { cells, groups };
}
test('stadiums merge by their own radii and segment lengths across grid boundaries', () => {
const sizes = {
2: { width: 28, height: 28 },
7350: { width: 80, height: 48 },
};
const check = (counts, positions, expected) => {
const { groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
assert.equal(
groups.reduce((sum, cell) => sum + cell.count, 0),
counts[0] + counts[1],
);
};
const origin = { x: 35, y: 37 };
// Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear.
check([2, 7350], [origin, { x: 35, y: 78 }], [7352]);
check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]);
// The large pill's centre segment extends 16 pixels towards the circle.
check([7350, 2], [origin, { x: 92, y: 37 }], [7352]);
check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]);
check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]);
// Large pills can reach across a row boundary at their full diameter.
check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]);
});
test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => {
const sizes = {
1: { width: 24, height: 24 },
9: { width: 40, height: 40 },
};
const check = (counts, positions, expected) => {
const { cells, groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
// A lone camera that stays apart is still its own cell object.
assert.deepEqual(
groups.filter((cell) => cell.count === 1),
cells.filter((cell) => groups.includes(cell) && cell.count === 1),
);
};
const at = (x, y = 100) => ({ x, y });
// Radii 20 and 12: the four-pixel gap is clear at 36 pixels.
check([9, 1], [at(100), at(135)], [10]);
check([9, 1], [at(100), at(136)], [9, 1]);
check([1, 9], [at(135), at(100)], [10]);
// Overlapping icons with no count beside them stay two icons.
check([1, 1], [at(100), at(110)], [1, 1]);
// A count takes every lone camera it touches, on either side.
check([1, 9, 1], [at(70), at(100), at(130)], [11]);
// A lone camera that only touches another lone camera is left alone.
check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]);
});
test('cells merged across the antimeridian stay at the antimeridian', () => {
for (const lon of [179.9, 179.99, 179.999]) {
for (const reversed of [false, true]) {
const east = createCameraCell('e');
const west = createCameraCell('w');
for (let i = 0; i < 2; i++) {
addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 });
addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 });
}
const cells = reversed ? [west, east] : [east, west];
const screens = [
{ x: 100, y: 100 },
{ x: 120, y: 100 },
];
let i = 0;
const [group, ...rest] = mergeCountCells(
cells,
() => screens[i++],
() => ({ width: 40, height: 40 }),
4,
);
assert.equal(rest.length, 0);
assert.equal(group.count, 4);
const expected = fromDegrees(180, 0, 0);
assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`);
const bounds = cellBounds(group);
assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`);
for (const l of [lon, -lon])
assert.ok(
distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius,
);
}
}
});
test('flight bounds on drawn ground still contain every mount', () => {
// Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m.
const flat = createCameraCell('k');
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
flat.groundM = 0;
const fb = cellBounds(flat);
assert.ok(
distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius,
'flat',
);
// Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them.
const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180));
const ravine = createCameraCell('r');
addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 });
addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 });
ravine.groundM = 0;
const rb = cellBounds(ravine);
for (const lon of [10, east])
assert.ok(
distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius,
'ravine',
);
});
test('a lone camera between two counts joins one of them and does not merge them', () => {
const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } };
const run = (counts, xs) =>
mergeCounts(
sizes,
counts,
xs.map((x) => ({ x, y: 100 })),
)
.groups.map((cell) => cell.count)
.sort((a, b) => a - b);
assert.deepEqual(run([9, 9], [70, 130]), [9, 9]);
for (const [counts, xs] of [
[
[9, 1, 9],
[70, 100, 130],
],
[
[1, 9, 9],
[100, 70, 130],
],
[
[9, 9, 1],
[70, 130, 100],
],
])
assert.deepEqual(run(counts, xs), [9, 10], String(counts));
});
+254
View File
@@ -0,0 +1,254 @@
import { afterEach, beforeEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
refreshHorizonCulling,
} from './cctv.js';
const WIDTH = 800;
const HEIGHT = 600;
const bindings = [];
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 8,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
for (const unbind of bindings.splice(0)) unbind();
});
function recordsAt(lonLats, height = 10) {
return lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
return {
camera: {
id: `cam-${String(index).padStart(4, '0')}`,
name: `Camera ${index}`,
city: 'Test',
lat,
lon,
headingDeg: 0,
pitchDeg: -18,
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
absoluteHeightM: height,
},
position: { x: position.x, y: position.y, z: position.z },
groundSamples: {},
groundResolved: {},
coverageEntities: [],
projection: null,
};
});
}
const plain = ({ x, y, z }) => ({ x, y, z });
function lookingAt(eye, target, ports = {}) {
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
return {
viewer: viewerWithAxes(eye, direction, right, up, ports),
direction,
right,
up,
};
}
function topDown(height, ports = {}) {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, height);
return viewerWithAxes(
eye,
{ x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 0, y: 0, z: 1 },
ports,
);
}
function viewerWithAxes(eye, direction, right, up, ports) {
const carto = Cesium.Cartographic.fromCartesian(eye);
const { port } = fakeCameraPort({
pose: {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
height: carto.height,
position: plain(eye),
direction: plain(direction),
up: plain(up),
right: plain(right),
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
draw: fakeDrawPort(),
...ports,
}),
);
return viewer;
}
/** Pinhole projection, as the layer's projector. */
function project(view, eye, point) {
const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3());
const z = Cesium.Cartesian3.dot(d, view.direction);
const t = Math.tan(Math.PI / 6);
const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT));
const y = Cesium.Cartesian3.dot(d, view.up) / z / t;
return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z };
}
for (const [label, horizontalM, aboveM] of [
['100 m approach', 100, 4],
['800 m approach', 800, 50],
]) {
test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => {
const ground = 1872;
const records = recordsAt([
[0, 0],
[0, 0],
]);
// geoid fallback after a 429
for (const r of records)
r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' };
const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8);
const eye = Cesium.Cartesian3.fromDegrees(
0,
-horizontalM / 111_320,
ground + 8 + aboveM,
);
const reads = [];
const view = lookingAt(eye, mount, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return ground;
},
},
});
_setCctvCoverageStateForTest({ viewer: view.viewer, records });
const stale = project(view, eye, records[0].position);
const truth = project(view, eye, mount);
assert.ok(stale.y > HEIGHT * 2);
assert.ok(truth.y > 0 && truth.y < HEIGHT);
refreshHorizonCulling();
refreshHorizonCulling();
assert.equal(records[0].groundPrior.ellipsoid, ground);
assert.ok(reads.length > 0, 'the stale camera was never read');
});
}
test('cameras off the visible screen cannot spend the whole terrain read budget', () => {
// 300 cameras with no prior around the screen edge, tiles not loaded; the
// 301st at the screen centre over a loaded tile.
const lonLats = [];
for (let i = 0; i < 300; i++) {
const a = (i / 300) * 2 * Math.PI;
// ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide)
lonLats.push([
(Math.cos(a) * 250) / 111_320,
(Math.sin(a) * 190) / 111_320,
]);
}
lonLats.push([0, 0]);
const records = recordsAt(lonLats);
const perPass = [];
let reads;
const viewer = topDown(200, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9
? 40
: null;
},
},
});
_setCctvCoverageStateForTest({ viewer, records });
for (let pass = 0; pass < 3; pass++) {
reads = [];
refreshHorizonCulling();
perPass.push(reads.length);
}
const last = records.at(-1);
assert.equal(last.groundPrior?.ellipsoid, 40);
assert.ok(perPass.every((n) => n <= 300));
});
test("the active camera's icon moves beside a count that would cover it", () => {
const records = recordsAt([
[0, 0],
[0, 0],
[0, 0],
]);
const viewer = topDown(20_000);
_setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const [marker] = cctvLayer._cctvDrawnForTest().counts.markers;
const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990;
const apartPx =
Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) /
metresPerPixel;
assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon');
});
test('a lone camera just inside the grouping threshold joins the count beside it', () => {
const h = 740;
// mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10
const records = recordsAt([
[0, 235 / 111_320],
[0, 255 / 111_320],
[0, 255 / 111_320],
]);
for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' };
const viewer = topDown(h + 10);
_setCctvCoverageStateForTest({ viewer, records });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const markers = cctvLayer._cctvDrawnForTest().counts.markers;
assert.deepEqual(
markers.map((marker) => marker.cell.count),
[3],
);
assert.equal(
icons.item('cam-0000').show,
false,
'the near singleton still draws beside the count',
);
});
File diff suppressed because it is too large. Load diff
+43
View File
@@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a
]);
coordinator.destroy();
});
test('start layers turn on when nothing names any, and are never written as the user choice', async () => {
const storage = memoryStorage();
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage,
});
const results = await coordinator.start({
allowLocalState: false,
startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'],
});
assert.equal(coordinator.source, 'start');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
'earthquakes',
'traffic',
]);
assert.equal(manager.isEnabled('earthquakes'), true);
assert.equal(manager.isEnabled('traffic'), true);
assert.equal(
results.every((result) => result.persistenceWrite === false),
true,
);
assert.deepEqual(storage.writes, []);
coordinator.destroy();
});
test('a shared layer payload wins over start layers', async () => {
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage: memoryStorage(),
});
const shared = createDefaultLayerState();
shared.enabledLayerIds = ['radio'];
await coordinator.start({
shareLayerState: shared,
allowLocalState: false,
startLayerIds: ['earthquakes'],
});
assert.equal(coordinator.source, 'share');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']);
assert.equal(manager.isEnabled('earthquakes'), false);
coordinator.destroy();
});
+8 -1
View File
@@ -103,6 +103,7 @@ export class LayerStateCoordinator {
shareLayerState = null,
allowLocalState = true,
shareCreatedAtMs = null,
startLayerIds = [],
} = {}) {
if (this._destroyed)
throw new Error('Layer-state coordinator is destroyed');
@@ -125,7 +126,13 @@ export class LayerStateCoordinator {
selected = this._normalize(stored);
this._source = 'local';
}
} else {
}
if (!selected && startLayerIds.length) {
// The layers the application starts with when nothing names any:
// restored passively, so they are never written as the user's choice.
selected = this._normalize({ enabledLayerIds: startLayerIds });
this._source = 'start';
} else if (!selected && !allowLocalState) {
// A valid historical camera/style share with no v2 layer payload keeps
// the exact legacy default-layer behavior. It must not inherit an
// unrelated recipient's saved local layer preferences.
+102
View File
@@ -0,0 +1,102 @@
import { fromDegreesInto } from '../geo/ellipsoid.js';
/**
* Finding a selected vessel or aircraft again once it has left the screen or
* its layer's feed: where its own track has it at a time, and whether a point
* is on screen at all.
*/
/**
* The newest point of a track at or before `atMs` (any time when `atMs` is
* not given), from a live source's `getTrack` records
* (`{observedAtMs, latitude, longitude, baroAltitudeM?}`).
* @param {Array<object>} points
* @param {number} [atMs]
* @returns {{lat: number, lon: number, altitudeM: ?number, observedAtMs: number}|null}
*/
export function readingAt(points, atMs) {
let best = null;
for (const point of points ?? []) {
const lat = Number(point?.latitude);
const lon = Number(point?.longitude);
const observedAtMs = point?.observedAtMs;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (!Number.isFinite(observedAtMs)) continue;
if (Number.isFinite(atMs) && observedAtMs > atMs) continue;
if (best && best.observedAtMs >= observedAtMs) continue;
const altitude = Number(point.baroAltitudeM ?? point.altitudeM);
best = {
lat,
lon,
altitudeM: Number.isFinite(altitude) ? altitude : null,
observedAtMs,
};
}
return best;
}
/**
* Where a source's track has a vessel or aircraft at `atMs` (now, when not
* given): `{status: 'found', lat, lon, altitudeM, observedAtMs, atMs}`, or
* `{status: 'none'}` when the track has no point at or before the time, the
* source keeps no tracks or the lookup fails.
* @param {{getTrack?: Function}|null} source
* @param {string} reference The track reference the layer's records carry.
* @param {{atMs?: number, signal?: AbortSignal}} [options]
*/
export async function locateOnTrack(source, reference, { atMs, signal } = {}) {
if (typeof source?.getTrack !== 'function' || !reference)
return { status: 'none' };
try {
const track = await source.getTrack(
reference,
Number.isFinite(atMs) ? { signal, atMs } : { signal },
);
const reading = readingAt(track?.records, atMs);
// The time it was looked up for, so its reading's age can be told.
const at = Number.isFinite(atMs) ? atMs : Date.now();
return reading
? { status: 'found', ...reading, atMs: at }
: { status: 'none' };
} catch (error) {
if (signal?.aborted) throw error;
return { status: 'none' };
}
}
/** Mean Earth radius (m), for the horizon test. */
const EARTH_RADIUS_M = 6_371_000;
/**
* Whether a point is in the camera's view: in front of it, inside its field
* of view and on the near side of the globe.
* @param {{position: {x, y, z}, direction: {x, y, z}, up: {x, y, z},
* right: {x, y, z}, fovy: number, aspectRatio: number}} pose
* @param {number} lat
* @param {number} lon
* @param {number} [heightM]
* @returns {boolean}
*/
export function onScreen(pose, lat, lon, heightM = 0) {
if (!pose?.position || !Number.isFinite(lat) || !Number.isFinite(lon))
return false;
const p = fromDegreesInto(lon, lat, Math.max(0, heightM || 0), {
x: 0,
y: 0,
z: 0,
});
const c = pose.position;
const v = { x: p.x - c.x, y: p.y - c.y, z: p.z - c.z };
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const ahead = dot(v, pose.direction);
if (!(ahead > 0)) return false;
const tanY = Math.tan(pose.fovy / 2);
const tanX = tanY * (pose.aspectRatio || 1);
if (Math.abs(dot(v, pose.right) / ahead) > tanX) return false;
if (Math.abs(dot(v, pose.up) / ahead) > tanY) return false;
// Behind the globe: the camera is below the point's horizon plane. Judged
// on a sphere through the point, which is close enough for a button.
const length = Math.hypot(p.x, p.y, p.z) || EARTH_RADIUS_M;
const normal = { x: p.x / length, y: p.y / length, z: p.z / length };
return dot({ x: c.x - p.x, y: c.y - p.y, z: c.z - p.z }, normal) > 0;
}
+114
View File
@@ -0,0 +1,114 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { locateOnTrack, onScreen, readingAt } from './locate.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
const point = (observedAtMs, latitude, longitude, extra = {}) => ({
observedAtMs,
latitude,
longitude,
...extra,
});
test('the reading at a time is the newest point at or before it', () => {
const track = [
point(3_000, 3, 30),
point(1_000, 1, 10, { baroAltitudeM: 900 }),
point(2_000, 2, 20),
point(Number.NaN, 9, 90),
point(4_000, Number.NaN, 40),
];
assert.deepEqual(readingAt(track, 2_500), {
lat: 2,
lon: 20,
altitudeM: null,
observedAtMs: 2_000,
});
assert.equal(readingAt(track, 1_000).altitudeM, 900, 'at its own time');
assert.equal(readingAt(track).observedAtMs, 3_000, 'no time: the newest');
assert.equal(readingAt(track, 500), null, 'before its first point');
assert.equal(readingAt([], 500), null);
});
test('a track lookup asks for the time and reads the point at it', async () => {
const asked = [];
const source = {
async getTrack(reference, options) {
asked.push([reference, options.atMs]);
return { records: [point(1_000, 1, 10), point(5_000, 5, 50)] };
},
};
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 2_000 }), {
status: 'found',
lat: 1,
lon: 10,
altitudeM: null,
observedAtMs: 1_000,
atMs: 2_000,
});
assert.deepEqual(asked, [['vessel:a', 2_000]]);
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 500 }), {
status: 'none',
});
const live = await locateOnTrack(source, 'vessel:a');
assert.equal(live.observedAtMs, 5_000, 'live: its newest point');
assert.equal(asked.at(-1)[1], undefined, 'live asks for no time');
});
test('a source without tracks, or one that fails, finds nothing', async () => {
assert.deepEqual(await locateOnTrack({}, 'a'), { status: 'none' });
assert.deepEqual(await locateOnTrack(null, 'a'), { status: 'none' });
const failing = {
getTrack: async () => {
throw new Error('down');
},
};
assert.deepEqual(await locateOnTrack(failing, 'a'), { status: 'none' });
assert.deepEqual(
await locateOnTrack({ getTrack: async () => ({ records: [] }) }, ''),
{ status: 'none' },
'no reference',
);
});
/** A camera 1000 km above a point, looking straight down. */
function poseAbove(lat, lon) {
const at = fromDegreesInto(lon, lat, 0, { x: 0, y: 0, z: 0 });
const length = Math.hypot(at.x, at.y, at.z);
const up = { x: at.x / length, y: at.y / length, z: at.z / length };
const position = {
x: at.x + up.x * 1e6,
y: at.y + up.y * 1e6,
z: at.z + up.z * 1e6,
};
const direction = { x: -up.x, y: -up.y, z: -up.z };
// North-ish screen up, east right: any pair at right angles will do.
const east = {
x: -Math.sin((lon * Math.PI) / 180),
y: Math.cos((lon * Math.PI) / 180),
z: 0,
};
const north = {
x: up.y * east.z - up.z * east.y,
y: up.z * east.x - up.x * east.z,
z: up.x * east.y - up.y * east.x,
};
return {
position,
direction,
up: north,
right: east,
fovy: Math.PI / 3,
aspectRatio: 1.5,
};
}
test('a point is on screen in view, and not out of view or behind the globe', () => {
const pose = poseAbove(10, 20);
assert.equal(onScreen(pose, 10, 20), true, 'under the camera');
assert.equal(onScreen(pose, 11, 21), true, 'near it');
assert.equal(onScreen(pose, 30, 20), false, 'outside the view');
assert.equal(onScreen(pose, -10, -160), false, 'the far side of the globe');
assert.equal(onScreen(pose, Number.NaN, 20), false, 'no position');
assert.equal(onScreen(null, 10, 20), false, 'no camera');
});
+36 -4
View File
@@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) {
let _overlayHitTest = null;
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
const clickCards = new WeakMap();
const _clickClaims = new Map();
/**
* Register a target drawn outside the world overlay's entries, such as a CCTV
* count. A claim runs once per click where no card or label is painted above
* it and must not call `clickCard`.
* @param {string} layerId
* @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim
*/
export function registerClickClaim(layerId, claim) {
if (!layerId || typeof claim !== 'function') return;
_clickClaims.set(layerId, claim);
}
/** Remove a layer's claim when it is disabled or destroyed. */
export function unregisterClickClaim(layerId) {
_clickClaims.delete(layerId);
}
/**
* Sets (or with null, clears) the hit test that names the card or label
@@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) {
}
/**
* The topmost interactive card or label painted at a click, read once per
* click so every handler of it sees the same one whatever ran first.
* The topmost interactive card or label painted at a click, or a target a
* layer claims (`registerClickClaim`). All handlers share one result per click.
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
* @returns {{sourceId: string, entryId: string}|null}
*/
@@ -179,14 +197,28 @@ export function clickCard(click) {
try {
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
} catch {
// a broken hit test must never break click handling
clickCards.set(click, null);
return null;
}
if (!card) {
// A claim that reads this click again cannot re-enter the claims loop.
clickCards.set(click, null);
for (const claim of _clickClaims.values()) {
try {
card = claim(click) ?? null;
} catch {
card = null;
}
if (card) break;
}
}
clickCards.set(click, card);
return card;
}
/**
* True when another layer's card or label is painted on top at a click. The
* True when another layer has the top card, label, or claimed target
* (`registerClickClaim`) at a click. The
* card on top takes the click: a scene item under it does not act, and is
* not empty space either, so the layer leaves its selection alone.
* @param {object} click The shared dispatcher event.
+41
View File
@@ -20,6 +20,8 @@ import {
clickCard,
isUnderOtherCard,
setClickCardHitTest,
registerClickClaim,
unregisterClickClaim,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun
setClickCardHitTest(null);
}
});
test('a click claim is the card on top only where no card or label is painted', () => {
const event = (x) => ({ screenPosition: { x, y: 5 } });
let calls = 0;
registerClickClaim('counts', (click) => {
calls++;
return click.screenPosition.x === 4
? { sourceId: 'counts', entryId: 'k' }
: null;
});
try {
registerClickClaim('counts', null);
const click = event(4);
assert.equal(isUnderOtherCard(click), true);
assert.equal(isUnderOtherCard(click, ['counts']), false);
assert.equal(calls, 1);
assert.equal(clickCard(event(9)), null);
const quake = { sourceId: 'quake-card', entryId: 'q1' };
setClickCardHitTest(() => quake);
assert.deepEqual(clickCard(event(4)), quake);
assert.equal(calls, 2);
setClickCardHitTest(() => {
throw new Error('broken overlay hit test');
});
assert.equal(clickCard(event(4)), null);
assert.equal(calls, 2);
setClickCardHitTest(null);
unregisterClickClaim('counts');
assert.equal(clickCard(event(4)), null);
registerClickClaim('counts', () => {
throw new Error('broken claim');
});
assert.equal(clickCard(event(4)), null);
} finally {
unregisterClickClaim('counts');
setClickCardHitTest(null);
}
});
+5 -1
View File
@@ -4739,5 +4739,9 @@
"Select a map item to see its details.": "اختر عنصرًا على الخريطة لرؤية تفاصيله.",
"Bilawal on {site}": "بلال على {site}",
"Bilawal's website": "موقع بلال الإلكتروني",
"BACK": "رجوع"
"BACK": "رجوع",
"Finding it…": "جارٍ البحث عنه…",
"No reading at this time": "لا توجد قراءة في هذا الوقت",
"Last reading · {age}": "آخر قراءة · {age}",
"Find it": "اعثر عليه"
}
+5 -1
View File
@@ -4315,5 +4315,9 @@
"Select a map item to see its details.": "Wähle ein Kartenelement aus, um seine Details zu sehen.",
"Bilawal on {site}": "Bilawal auf {site}",
"Bilawal's website": "Bilawals Website",
"BACK": "ZURÜCK"
"BACK": "ZURÜCK",
"Finding it…": "Wird gesucht…",
"No reading at this time": "Zu dieser Zeit kein Messwert",
"Last reading · {age}": "Letzter Stand · {age}",
"Find it": "Finden"
}
+5 -1
View File
@@ -4421,5 +4421,9 @@
"Select a map item to see its details.": "Selecciona un elemento del mapa para ver sus detalles.",
"Bilawal on {site}": "Bilawal en {site}",
"Bilawal's website": "Sitio web de Bilawal",
"BACK": "ATRÁS"
"BACK": "ATRÁS",
"Finding it…": "Buscando…",
"No reading at this time": "Sin lectura a esta hora",
"Last reading · {age}": "Última lectura · {age}",
"Find it": "Encontrar"
}
+5 -1
View File
@@ -4421,5 +4421,9 @@
"Select a map item to see its details.": "Sélectionnez un élément de la carte pour voir ses détails.",
"Bilawal on {site}": "Bilawal sur {site}",
"Bilawal's website": "Site web de Bilawal",
"BACK": "RETOUR"
"BACK": "RETOUR",
"Finding it…": "Recherche…",
"No reading at this time": "Aucune donnée à cette heure",
"Last reading · {age}": "Dernière donnée · {age}",
"Find it": "Retrouver"
}
+5 -1
View File
@@ -4421,5 +4421,9 @@
"Bilawal on YouTube": "בילוואל ב־YouTube",
"The studio behind GEV": "הסטודיו שמאחורי GEV",
"Open source. Self-host, fork, add a layer.": "קוד פתוח. אירוח עצמאי, יצירת עותק והוספת שכבה.",
"ENTER GOD MODE": "כניסה למצב אלוהים"
"ENTER GOD MODE": "כניסה למצב אלוהים",
"Finding it…": "מחפש…",
"No reading at this time": "אין קריאה בזמן הזה",
"Last reading · {age}": "קריאה אחרונה · {age}",
"Find it": "מצא"
}
+5 -1
View File
@@ -4421,5 +4421,9 @@
"Select a map item to see its details.": "Seleziona un elemento della mappa per vederne i dettagli.",
"Bilawal on {site}": "Bilawal su {site}",
"Bilawal's website": "Sito web di Bilawal",
"BACK": "INDIETRO"
"BACK": "INDIETRO",
"Finding it…": "Ricerca in corso…",
"No reading at this time": "Nessun dato a quest'ora",
"Last reading · {age}": "Ultimo dato · {age}",
"Find it": "Trova"
}
+5 -1
View File
@@ -4209,5 +4209,9 @@
"Select a map item to see its details.": "地図上の項目を選択すると詳細が表示されます。",
"Bilawal on {site}": "{site}のBilawal",
"Bilawal's website": "Bilawalのウェブサイト",
"BACK": "戻る"
"BACK": "戻る",
"Finding it…": "検索中…",
"No reading at this time": "この時刻のデータなし",
"Last reading · {age}": "最終データ・{age}",
"Find it": "探す"
}
+5 -1
View File
@@ -4421,5 +4421,9 @@
"Select a map item to see its details.": "Selecione um item do mapa para ver seus detalhes.",
"Bilawal on {site}": "Bilawal no {site}",
"Bilawal's website": "Site de Bilawal",
"BACK": "VOLTAR"
"BACK": "VOLTAR",
"Finding it…": "A procurar…",
"No reading at this time": "Sem leitura nesta hora",
"Last reading · {age}": "Última leitura · {age}",
"Find it": "Encontrar"
}
+5 -1
View File
@@ -4527,5 +4527,9 @@
"Select a map item to see its details.": "Выберите объект на карте, чтобы увидеть подробности.",
"Bilawal on {site}": "Билал на {site}",
"Bilawal's website": "Сайт Билала",
"BACK": "НАЗАД"
"BACK": "НАЗАД",
"Finding it…": "Поиск…",
"No reading at this time": "Нет данных на это время",
"Last reading · {age}": "Последние данные · {age}",
"Find it": "Найти"
}
+5 -1
View File
@@ -4315,5 +4315,9 @@
"Bilawal on YouTube": "Bilawal på YouTube",
"The studio behind GEV": "Studion bakom GEV",
"Open source. Self-host, fork, add a layer.": "Öppen källkod. Kör själv, skapa en egen variant, lägg till ett lager.",
"ENTER GOD MODE": "STARTA GUDLÄGE"
"ENTER GOD MODE": "STARTA GUDLÄGE",
"Finding it…": "Söker…",
"No reading at this time": "Ingen avläsning vid den här tiden",
"Last reading · {age}": "Senaste avläsning · {age}",
"Find it": "Hitta"
}
+5 -1
View File
@@ -4527,5 +4527,9 @@
"Select a map item to see its details.": "Виберіть об’єкт на карті, щоб побачити подробиці.",
"Bilawal on {site}": "Білал на {site}",
"Bilawal's website": "Сайт Білала",
"BACK": "НАЗАД"
"BACK": "НАЗАД",
"Finding it…": "Пошук…",
"No reading at this time": "Немає даних на цей час",
"Last reading · {age}": "Останні дані · {age}",
"Find it": "Знайти"
}
+5 -1
View File
@@ -4209,5 +4209,9 @@
"Select a map item to see its details.": "选择地图上的项目以查看详情。",
"Bilawal on {site}": "Bilawal 的 {site} 主页",
"Bilawal's website": "Bilawal 的网站",
"BACK": "返回"
"BACK": "返回",
"Finding it…": "正在查找…",
"No reading at this time": "此时无数据",
"Last reading · {age}": "最后数据 · {age}",
"Find it": "查找"
}
+5 -1
View File
@@ -4209,5 +4209,9 @@
"Select a map item to see its details.": "選擇地圖上的項目以查看詳情。",
"Bilawal on {site}": "Bilawal 的 {site} 主頁",
"Bilawal's website": "Bilawal 的網站",
"BACK": "返回"
"BACK": "返回",
"Finding it…": "正在查找…",
"No reading at this time": "此時無數據",
"Last reading · {age}": "最後數據 · {age}",
"Find it": "查找"
}
+3 -1
View File
@@ -27,7 +27,9 @@ let instances = 0;
* records fully cover, reused for later views inside it) and `zoom` (their
* tile precision; `source.detailZoom(box)` names the zoom a view needs). Records use stable string ids and latitude /
* longitude in degrees; optional directionDeg is a compass bearing [0, 360).
* Manufacturer, operator and cameraType are optional display fields.
* Manufacturer, operator, cameraType and model are optional display fields;
* model only selects a vendored datasheet line (modelSpecs.js), never shown
* as text.
* Source label and attribution { name, description, text, href } identify the
* actual provider; href must be HTTPS. Provider payload parsing stays in source.
* Context services remove obsolete records with
+250
View File
@@ -0,0 +1,250 @@
/**
* @module alprModelSpecs
*
* Datasheet specs for the ALPR hardware that OpenStreetMap `model` tags name,
* vendored from the CCTV Camera Database (CC0-1.0) and matched with the CCTV
* layer's rules; DATA_SOURCES.md has the provenance. Flock Safety publishes no
* datasheet resolution, so Flock models stay unresolved; an unknown model
* never implies anything.
*
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
* night vision) — never endpoints, operators or what a camera records.
*/
import { createModelSpecLookup, lookupModelSpec } from '../cctv/modelSpecs.js';
/**
* Records from the dataset's model-enrichment extract (v2.29.0), with the
* bare product codes mappers tag ("L6Q") added as aliases where the title
* names the product line ("Vigilant L6Q"). A tag without a generation or
* variant could name any of them, so the SharpV G3 and SharpX XGA titles
* carry theirs. Fields the card does not read (type, url, fov_deg, …) stay as
* in the dataset, like the CCTV records.
*/
const RECORDS = [
{
id: 'motorola-solutions-l5f',
brand: 'Motorola Solutions',
model: 'Vigilant L5F',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5f/',
aliases: ['L5F', 'L5F Fixed LPR Camera System'],
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l5m',
brand: 'Motorola Solutions',
model: 'Vigilant L5M',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5m/',
aliases: [
'L5M',
'L5M Mobile LPR Camera System',
'L5M Mobile ANPR Camera System',
],
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l5q',
brand: 'Motorola Solutions',
model: 'Vigilant L5Q',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5q/',
aliases: ['L5Q', 'L5Q Quick Deploy LPR Camera System'],
resolution: { mp: 3 },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l6d',
brand: 'Motorola Solutions',
model: 'Vigilant L6D',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l6d/',
aliases: [
'L6D',
'L6D Dual-Purpose LPR Camera',
'VSM-L6D-8IR',
'VSM-L6D-7IR',
],
fov_deg: '52-3 horizontal',
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
varifocal: true,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l6q',
brand: 'Motorola Solutions',
model: 'Vigilant L6Q',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l6q/',
aliases: ['L6Q', 'L6Q Quick-Deploy LPR Camera System'],
resolution: { mp: 2.1, w: 1920, h: 1080, label: '1080p' },
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpv',
brand: 'Genetec',
model: 'AutoVu SharpV G3',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/',
aliases: [
'AU-V-WS850-LC-G3-000',
'AU-V-BS850-LC-G3-0M0',
'AU-V-BS850-LC-G3-0M1',
],
resolution: { mp: 2.3, w: 1920, h: 1200, label: '1920x1200' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpv-g2',
brand: 'Genetec',
model: 'AutoVu SharpV G2',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv-g2/',
aliases: ['AutoVu SharpV G1', 'AU-V-WS850-LC-G2', 'AU-V-WS850-LC'],
resolution: { mp: 1.2, w: 1280, h: 960, label: '1280x960' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpx',
brand: 'Genetec',
model: 'AutoVu SharpX XGA',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/',
// i18n-ignore: datasheet label
resolution: { mp: 1, w: 1024, h: 946, label: 'XGA (1024x946)' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpz3',
brand: 'Genetec',
model: 'AutoVu SharpZ3',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpz3/',
resolution: { mp: 1.6, w: 1456, h: 1088, label: '1456x1088' },
lens_count: 3,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'axis-q1700-le',
brand: 'Axis',
model: 'Q1700-LE',
type: 'box',
url: 'https://www.cctv-database.com/camera/axis-q1700-le/',
fov_deg: '16-2.3 horizontal / 9.6-1.3 vertical',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
varifocal: true,
night_vision: { type: 'ir', range_m: 50 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'axis-q1800-le',
brand: 'Axis',
model: 'Q1800-LE',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/axis-q1800-le/',
aliases: ['03107-001', 'Q1800-LE-3 (License Plate Verifier kit)'],
fov_deg: '38-2.3 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
varifocal: true,
night_vision: { type: 'ir', range_m: 40 },
environment: ['indoor', 'outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cb62-te-f',
brand: 'Verkada',
model: 'CB62-TE-F',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/verkada-cb62-te-f/',
fov_deg: '42 to 17 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
varifocal: true,
night_vision: { type: 'ir', range_m: 50 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-ch52-e-f',
brand: 'Verkada',
model: 'CH52-E-F',
type: 'panoramic',
url: 'https://www.cctv-database.com/camera/verkada-ch52-e-f/',
fov_deg: '89 to 37 H (per sensor); up to 328 combined',
// i18n-ignore: datasheet label
resolution: { mp: 5, w: 2688, h: 1944, label: '4 x 5MP (20MP)' },
lens_count: 4,
varifocal: true,
night_vision: { type: 'ir', range_m: 30 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cp63-e',
brand: 'Verkada',
model: 'CP63-E',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/verkada-cp63-e/',
fov_deg: '64 to 2 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
ptz: true,
varifocal: true,
night_vision: { type: 'ir', range_m: 100 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cr63-e',
brand: 'Verkada',
model: 'CR63-E',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/verkada-cr63-e/',
fov_deg: '109 to 49 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
varifocal: true,
night_vision: { type: 'ir', range_m: 20 },
environment: ['indoor', 'outdoor'],
},
// The CCTV layer's record: one colour-neutral title for the B/G/W variants.
lookupModelSpec('MIC-7522-Z30B', 'Bosch'),
];
const lookupDatasheetSpec = createModelSpecLookup(RECORDS);
/**
* Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer`
* naming another maker rejects the match, so a "Flock Safety" camera tagged
* "L6Q" stays unresolved rather than borrowing Motorola's specs.
* @param {string|null} model - The OSM `model` tag.
* @param {string|null} [manufacturer] - The OSM `manufacturer` tag.
* @returns {Object|null} The spec record, or null when unknown.
*/
export function lookupAlprModelSpec(model, manufacturer) {
// Adapter records arrive unnormalized and the matcher's word trim is
// quadratic on long punctuation runs: match only tag-sized strings (the
// built-in sources keep 180 characters).
if (typeof model !== 'string' || model.length > 180) return null;
if (
manufacturer != null &&
(typeof manufacturer !== 'string' || manufacturer.length > 180)
)
return null;
return lookupDatasheetSpec(model, manufacturer);
}
+157
View File
@@ -0,0 +1,157 @@
// src/layers/alpr/modelSpecs.test.mjs
// Mapped ALPR model tags resolve to vendored datasheets, and never guess.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { decodeAlprTile } from './tileRecords.js';
import { alprLabelDetails } from './visuals.js';
const OSM = { attribution: { name: 'OpenStreetMap' } };
test('the model tags mappers write resolve to their datasheet record', () => {
// [model tag, manufacturer tag, record id] as they appear on OSM nodes.
for (const [model, manufacturer, id] of [
['L6Q', 'Motorola Solutions', 'motorola-solutions-l6q'],
['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'],
['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'],
['L6Q', null, 'motorola-solutions-l6q'],
['AutoVu SharpV G3', 'Genetec', 'genetec-autovu-sharpv'],
['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'],
['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'],
['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'],
['AutoVu SharpX XGA', 'Genetec', 'genetec-autovu-sharpx'],
['Q1700-LE', 'Axis Communications', 'axis-q1700-le'],
['Q1800-LE', 'Axis Communications', 'axis-q1800-le'],
['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'],
['CB62-TE-F', 'Verkada Inc.', 'verkada-cb62-te-f'],
['CH52-E-F', 'Verkada Inc.', 'verkada-ch52-e-f'],
['CR63-E', 'Verkada', 'verkada-cr63-e'],
['MIC-7522-Z30B', 'The Bosch Group', 'bosch-mic-7522-z30b'],
])
assert.equal(
lookupAlprModelSpec(model, manufacturer)?.id,
id,
`${manufacturer} ${model}`,
);
});
test('unknown, mis-attributed or partial models stay unresolved', () => {
for (const [model, manufacturer] of [
['Falcon', 'Flock Safety'],
// A Motorola code under another maker is a mapping error, not a match.
['L6Q', 'Flock Safety'],
// "AutoVu Sharp" is an older line than SharpV; "Q1800" names no variant.
['AutoVu Sharp', 'Genetec'],
['Q1800', 'Axis Communications'],
// Without a maker, a code-less product name is never trusted.
['AutoVu SharpV', null],
// A SharpV without its generation could be G1, G2 or G3, and a SharpX
// without XGA could be the VGA model.
['AutoVu SharpV', 'Genetec'],
['AutoVu SharpV HD', 'Genetec'],
['Genetec AutoVu SharpV', 'Genetec'],
['AutoVu SharpX', 'Genetec'],
['UnicamVELOCITY3', null],
[null, 'Motorola Solutions'],
// Adapter text is matched only as a string of tag size.
[['L6Q'], 'Motorola Solutions'],
['L6Q' + ' IP'.repeat(60), 'Motorola Solutions'],
])
assert.equal(lookupAlprModelSpec(model, manufacturer), null);
});
/** A one-point `cameras` vector tile (z0) with string attributes. */
function cameraTile(properties) {
const tile = new PbfWriter();
tile.writeMessage(3, (_, layer) => {
layer.writeVarintField(15, 2);
layer.writeStringField(1, 'cameras');
layer.writeVarintField(5, 4096);
const keys = Object.keys(properties);
layer.writeMessage(2, (_, feature) => {
feature.writePackedVarint(
2,
keys.flatMap((_, i) => [i, i]),
);
feature.writeVarintField(3, 1); // Point
feature.writePackedVarint(4, [9, 4096, 4096]); // MoveTo(2048, 2048)
});
for (const key of keys) layer.writeStringField(3, key);
for (const key of keys)
layer.writeMessage(4, (_, value) =>
value.writeStringField(1, String(properties[key])),
);
});
return tile.finish();
}
test('extract tiles carry the model tag to the card', () => {
const [record] = decodeAlprTile(
cameraTile({
osmType: 'node',
osmId: '7',
brand: 'Motorola Solutions',
model: 'L6Q',
}),
0,
0,
0,
);
assert.equal(record.model, 'L6Q');
assert.ok(
alprLabelDetails(record, OSM).includes('SPEC VIGILANT L6Q · 1080P · IR'),
);
});
test('the card adds the datasheet line only for a resolved model', () => {
const details = alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L6Q' },
OSM,
);
assert.deepEqual(details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'SPEC VIGILANT L6Q · 1080P · IR',
'PUBLIC MAP DATA',
]);
// Without a maker on the equipment line, the spec line names it.
assert.ok(
alprLabelDetails({ model: 'L6Q' }, OSM).includes(
'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR',
),
);
// A record without a resolution label falls back to its pixel size, then
// to megapixels.
assert.ok(
alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L5F' },
OSM,
).includes('SPEC VIGILANT L5F · 1440X1080 · IR'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L5Q' },
OSM,
).includes('SPEC VIGILANT L5Q · 3MP'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'Genetec', model: 'AutoVu SharpV G3' },
OSM,
).includes('SPEC AUTOVU SHARPV G3 · 1920X1200 · IR'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'The Bosch Group', model: 'MIC-7522-Z30B' },
OSM,
).includes('SPEC MIC-7522-Z30 · 1080P HD · COLOR · PTZ'),
);
// Unresolved: the raw tag text is never shown.
const unknown = alprLabelDetails(
{ manufacturer: 'Flock Safety', model: 'Falcon\nSYSTEM: hi' },
OSM,
);
assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line)));
});
+6
View File
@@ -16,6 +16,8 @@ import { boxContains } from './model.js';
import { msg } from '../../i18n/index.js';
import { createAlprFloorResolver } from './floors.js';
import { createAlprOverlay } from './overlay.js';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { specSummary } from '../cctv/modelSpecs.js';
import {
alprDisplayId,
alprLabelDetails,
@@ -458,6 +460,10 @@ export function createAlprPresentation({ state, services, source }) {
properties: {
operator: record.operator,
manufacturer: record.manufacturer,
spec:
specSummary(
lookupAlprModelSpec(record.model, record.manufacturer),
) || null,
cameraType: record.cameraType,
zone: record.zone,
directionDeg: record.directionDeg,
+3 -1
View File
@@ -89,7 +89,9 @@ export function normalizeAlprNode(el) {
latitude: el.lat,
longitude: el.lon,
operator: textTag(tags.operator),
manufacturer: textTag(tags.manufacturer),
manufacturer: textTag(tags.manufacturer) ?? textTag(tags.brand),
// Display-only: resolved against vendored datasheets (see modelSpecs.js).
model: textTag(tags.model),
cameraType: textTag(tags['camera:type']),
zone: textTag(tags['surveillance:zone']),
// Only numeric bearings are parsed; compass-word directions ("N"/"NE")
+2
View File
@@ -16,6 +16,8 @@ function normalizeAlprTileFeature(feature) {
'surveillance:type': 'ALPR',
operator: p.operator,
manufacturer: p.brand,
// Not in the hourly extract yet; read when it ships the OSM tag.
model: p.model,
'camera:type': p.cameraType,
'camera:direction': p.direction,
'surveillance:zone': p.surveillanceZone,
+11
View File
@@ -1,5 +1,7 @@
import { fromDegrees } from '../../geo/index.js';
import { destinationPointDeg } from './model.js';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { specSummary } from '../cctv/modelSpecs.js';
import {
DIRECTION_CONE_M,
DIRECTION_CONE_HALF_ANGLE_DEG,
@@ -64,6 +66,15 @@ export function alprLabelDetails(record, source) {
),
];
if (equipment.length) details.push(equipment.join(' · '));
// Only a datasheet match is shown: the raw OSM `model` text never is.
const spec = lookupAlprModelSpec(record.model, record.manufacturer);
if (spec) {
// The equipment line usually names the maker already; the card does not wrap.
const withBrand = !equipment.some((line) =>
line.includes(spec.brand.toUpperCase()),
);
details.push(`SPEC ${specSummary(spec, { withBrand }).toUpperCase()}`);
}
if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA');
return details;
}
+1 -1
View File
@@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) {
let rank = 0;
const push = (id, { pinned = false, active = false } = {}) => {
const record = layerState._recordById.get(id);
if (!record?.position) return;
if (!record?.position || (!active && record.viewGrouped)) return;
entries.push(
createCctvThumbnailOverlayEntry({
id,
+2 -1
View File
@@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const camera = records[i].camera;
objects.push({
position: records[i].position,
// A camera sharing its mount is drawn beside its mates.
position: records[i].spreadPosition ?? records[i].position,
sourceId: camera.id,
// Short semantic code where the id is opaque (see cameraDisplayCode).
id: `CAM-${camera.code || camera.id}`,
+430
View File
@@ -0,0 +1,430 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
withoutLoneCameras,
} from '../../data/cctvCellCounts.js';
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import {
CAMERA_GREEN,
COUNT_CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
} from './policy.js';
import { liftedForHorizon } from '../../geo/horizon.js';
// Diameter at one camera before applying the size limits, in CSS pixels.
const COUNT_BASE_PX = 38;
// Extra diameter for each tenfold increase in camera count.
const COUNT_PX_PER_DECADE = 5;
// Minimum height of a count marker in CSS pixels.
const COUNT_MIN_HEIGHT_PX = 40;
// Maximum height of a count marker in CSS pixels.
const COUNT_MAX_HEIGHT_PX = 58;
// Clear fill between the count and the inside of the ring, in CSS pixels.
const COUNT_TEXT_PADDING_PX = 6;
// Height of the camera glyph in the smallest and the largest marker.
const COUNT_GLYPH_MIN_PX = 7.5;
const COUNT_GLYPH_MAX_PX = 10;
// Clear fill above the glyph in the smallest and the largest marker.
const COUNT_GLYPH_TOP_MIN_PX = 3;
const COUNT_GLYPH_TOP_MAX_PX = 4;
// Clear fill between the glyph's top corners and the inside of the ring.
const COUNT_GLYPH_PADDING_PX = 2;
// The middle of the digits sits this share of the inner radius below the
// marker's centre, which leaves the glyph clear of the count.
const COUNT_LABEL_DROP = 0.2;
// Merge passes per view. A merged centre and wider label can reach a further
// marker. The cap bounds work on motion ticks.
const COUNT_MERGE_PASSES = 3;
const FONT = WORLD_OVERLAY_STYLE.fontTitle;
// Reserve the camera's landscape slot even while the map sprite is loading.
const GLYPH_ASPECT = 1.5;
const RING_PX = 2;
const RIM_PX = 1;
const STROKE_INSET = RIM_PX + RING_PX / 2;
// Painted bounds of the camera art, scaled from its viewBox to source pixels.
const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36);
const GLYPH_SOURCE_ASPECT = 28.1 / 19.5;
/** Merged camera groups and their last painted hit rectangles in CSS pixels. */
export function createCountMarkers(
registerPaintLane,
id,
refreshView,
keyholeAlpha,
) {
let hardUi = null;
let sprite = null;
let spriteReady = false;
const markers = [];
const hits = [];
const textMetrics = new Map();
const fonts = globalThis.document?.fonts;
let measureCtx;
let hitCount = 0;
const lane = registerPaintLane?.('ambient-label', paint, {
id,
active: false,
target: 'shared',
});
function loadSprite() {
if (sprite || typeof Image === 'undefined') return;
sprite = new Image();
sprite.onload = () => {
spriteReady = true;
if (markers.length) lane?.requestPaint();
};
sprite.src = COUNT_CAMERA_ICON;
}
fonts?.addEventListener?.('loadingdone', fontsLoaded);
/** Font changes can widen a pill enough to merge it with its neighbor. */
function fontsLoaded() {
textMetrics.clear();
if (!markers.length) return;
refreshView();
lane?.requestPaint();
}
/** Seat the glyph under the top of the ring and the count just below centre. */
function sizeFor(count) {
const text = formatCameraCount(count);
let metrics = textMetrics.get(text);
if (!metrics) {
measureCtx ??= globalThis.document
.createElement('canvas')
.getContext('2d');
measureCtx.font = FONT;
measureCtx.textBaseline = 'middle';
metrics = measureCtx.measureText(text);
textMetrics.set(text, metrics);
}
const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count);
const clamped = Math.max(
COUNT_MIN_HEIGHT_PX,
Math.min(COUNT_MAX_HEIGHT_PX, diameter),
);
const height = 2 * Math.round(clamped / 2);
const grown =
(height - COUNT_MIN_HEIGHT_PX) /
(COUNT_MAX_HEIGHT_PX - COUNT_MIN_HEIGHT_PX);
const glyphHeight =
COUNT_GLYPH_MIN_PX + (COUNT_GLYPH_MAX_PX - COUNT_GLYPH_MIN_PX) * grown;
const radius = height / 2 - RIM_PX - RING_PX;
const glyphTop =
COUNT_GLYPH_TOP_MIN_PX +
(COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown -
radius;
const ascent = metrics.actualBoundingBoxAscent;
const descent = metrics.actualBoundingBoxDescent;
const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2;
// Each row must clear the ring at the edge where the circle is narrowest.
const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2));
const extra = Math.max(
0,
Math.ceil(
Math.max(
metrics.width + 2 * COUNT_TEXT_PADDING_PX - chordAt(labelY + descent),
glyphHeight * GLYPH_ASPECT +
2 * COUNT_GLYPH_PADDING_PX -
chordAt(glyphTop),
),
),
);
return {
text,
width: height + extra,
height,
glyphHeight,
glyphBottom: glyphTop + glyphHeight,
labelY,
};
}
/** Keep covered icons in the restored count if its new label clears the HUD. */
function retainCoveredCameras(group, core, project) {
const anchor = cellCenter(core);
const at = project(anchor);
if (!at) return core;
const { x, y } = at; // The projector reuses its result.
const size = sizeFor(core.count);
const halfSegment = (size.width - size.height) / 2;
const covered = group.lone.filter((lone) => {
const p = project(cellCenter(lone));
if (!p) return false;
// The pill outline that merging measures, without its gap.
const dx = Math.max(
0,
Math.abs(p.x + (lone.offsetPx ?? 0) - x) - halfSegment,
);
const reach = (size.height + (lone.iconPx ?? CAMERA_ICON_PX)) / 2;
return dx * dx + (p.y - y) ** 2 < reach * reach;
});
if (!covered.length) return core;
const { width, height } = sizeFor(core.count + covered.length);
if (hardUi({ x: x - width / 2, y: y - height / 2, w: width, h: height }))
return core;
const held = withoutLoneCameras(group, covered);
held.anchor = anchor;
held.groundM = core.groundM;
for (const lone of covered) lone.absorbed = true;
return held;
}
/**
* Reuse marker slots in ground-key order, and invalidate only changed frames.
* `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite
* value where it has not loaded. A count stands on that ground when available
* and otherwise uses its cameras' mean mount height.
*/
function update(cells, project, groundHeight = null) {
// Lone cameras take part so that one beside a count joins it.
let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key));
const footprint = (count, cell) => {
if (count > 1) return sizeFor(count);
const px = cell.iconPx ?? CAMERA_ICON_PX;
return { width: px, height: px };
};
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
for (const cell of list) {
if (cell.count === 1 || cell.groundM !== undefined) continue;
const { lon, lat } = cellLonLat(cell);
const height = groundHeight(lon, lat);
cell.groundM = Number.isFinite(height) ? Math.round(height) : null;
}
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES &&
visible.length > 1 &&
visible.some((cell) => cell.count > 1);
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
footprint,
COUNT_MERGE_GAP_PX,
);
if (merged.length === visible.length) break;
visible = merged;
}
// A lone camera that is no longer its own entry now counts in a marker.
const apart = new Set(visible);
for (const cell of cells)
if (cell.count === 1) cell.absorbed = !apart.has(cell);
visible = visible.filter((cell) => cell.count > 1);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
let cell = visible[i];
// If the merged count is under the HUD, restore the count and its lone icons.
if (hardUi && cell.lone?.length) {
const at = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count);
const rect = at && {
x: at.x - width / 2,
y: at.y - height / 2,
w: width,
h: height,
};
if (rect && hardUi(rect)) {
for (const lone of cell.lone) lone.absorbed = false;
const core = withoutLoneCameras(cell);
if (core) {
ground([core]);
cell = retainCoveredCameras(cell, core, project);
cell.releasedAt = rect;
}
}
}
const marker = (markers[i] ??= { focus: 1 });
const last = marker.cell;
const size = sizeFor(cell.count);
if (
!last ||
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM ||
last.anchor?.x !== cell.anchor?.x ||
last.anchor?.y !== cell.anchor?.y ||
last.anchor?.z !== cell.anchor?.z
) {
marker.pos = cell.anchor ?? cellCenter(cell);
marker.cullPos = liftedForHorizon(marker.pos);
marker.hudHidden = undefined;
changed = true;
}
changed ||=
size.text !== marker.text ||
size.width !== marker.width ||
size.glyphBottom !== marker.glyphBottom ||
size.labelY !== marker.labelY;
marker.cell = cell;
Object.assign(marker, size);
// Paint never grows the hit buffer, even when a pan reveals every group.
hits[i] ??= {};
}
markers.length = visible.length;
if (markers.length) loadSprite();
// Keep the last frame pickable until the host clears its pixels.
lane?.setActive(markers.length > 0 || hitCount > 0);
if (changed) lane?.requestPaint();
}
/** Draw at device density using the host's CSS-pixel transform and projection. */
function paint(frame) {
hardUi = frame.overlapsHardUi ?? hardUi;
if (!markers.length) {
// Deactivating invalidates the host, so finish the shared frame first.
if (hitCount) queueMicrotask(deactivateIfEmpty);
hitCount = 0;
return;
}
hitCount = 0;
const { ctx, occluder, viewProjectionMatrix: m } = frame;
let refresh = false;
ctx.save();
try {
ctx.font = FONT;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let i = 0; i < markers.length; i++) {
const marker = markers[i];
// The core can stay visible while the HUD uncovers the merged count.
if (marker.cell.releasedAt) refresh ||= !hardUi(marker.cell.releasedAt);
const { height } = marker;
const { x: px, y: py, z: pz } = marker.pos;
const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos)))
continue;
const x =
(0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) *
frame.width;
const y =
(0.5 - (0.5 * (m[1] * px + m[5] * py + m[9] * pz + m[13])) / w) *
frame.height;
const rect = hits[hitCount];
rect.x = x - marker.width / 2;
rect.y = y - height / 2;
rect.w = marker.width;
rect.h = height;
if (
rect.x >= frame.width ||
rect.y >= frame.height ||
rect.x + rect.w <= 0 ||
rect.y + rect.h <= 0
)
continue;
const hidden = Boolean(hardUi?.(rect));
const previous = marker.hudHidden;
if (previous !== hidden) {
marker.hudHidden = hidden;
// The active icon steps aside only for visible counts beside it.
refresh ||=
((hidden || previous !== undefined) && marker.besideActive) ||
marker.cell.lone?.some((cell) => cell.absorbed === hidden);
}
if (hidden) continue;
const fade =
frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1;
if (!(fade > 0)) continue;
ctx.globalAlpha = marker.focus * fade;
ctx.beginPath();
ctx.roundRect(
rect.x + STROKE_INSET,
rect.y + STROKE_INSET,
rect.w - 2 * STROKE_INSET,
height - 2 * STROKE_INSET,
height / 2 - STROKE_INSET,
);
ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)';
ctx.lineWidth = RING_PX + 2 * RIM_PX;
ctx.stroke();
ctx.fillStyle = '#0e1720';
ctx.fill();
ctx.strokeStyle = CAMERA_GREEN;
ctx.lineWidth = RING_PX;
ctx.stroke();
ctx.fillStyle = CAMERA_GREEN;
if (spriteReady) {
const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT;
ctx.drawImage(
sprite,
...GLYPH_SOURCE,
x - width / 2,
y + marker.glyphBottom - marker.glyphHeight,
width,
marker.glyphHeight,
);
}
ctx.fillText(marker.text, x, y + marker.labelY);
rect.cell = marker.cell;
hitCount++;
}
} finally {
ctx.restore();
}
if (refresh) queueMicrotask(refreshView);
}
/** Resolve the topmost group actually painted at this screen position. */
function pickedCell(point) {
if (!point) return null;
for (let i = hitCount - 1; i >= 0; i--) {
const rect = hits[i];
const radius = rect.h / 2;
// Distance from the pill's horizontal centre segment.
const dx = Math.max(
0,
Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2,
);
const dy = point.y - (rect.y + radius);
if (dx * dx + dy * dy <= radius * radius) return rect.cell;
}
return null;
}
/** A new group may already have arrived since the empty frame. */
function deactivateIfEmpty() {
if (!markers.length) lane?.setActive(false);
}
/** Release the visible groups and clear their hit targets immediately. */
function hide() {
markers.length = hits.length = hitCount = 0;
lane?.setActive(false);
}
/** Unhook this viewer's painter and its font listener. */
function dispose() {
hide();
fonts?.removeEventListener?.('loadingdone', fontsLoaded);
lane?.unregister();
}
return {
markers,
update,
pickedCell,
hide,
dispose,
requestPaint: () => lane?.requestPaint(),
};
}
+179
View File
@@ -0,0 +1,179 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height });
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => {
const m = counts();
m.update([cellAt('a', 400, 2, -20)], project, () => -30);
const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid
const horizon = horizonFrom(eye);
assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true);
assert.equal(paint({ occluder: horizon }).length, 1);
});
test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => {
const hud = { overlapsHardUi: (rect) => rect.x < 200 };
for (const paintedFirst of [true, false]) {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const m = counts(() => m.update(cells, project));
if (paintedFirst) paint(hud);
m.update(cells, project);
const labels = paint(hud);
await Promise.resolve();
assert.ok(!cells[1].absorbed || labels.length > 0);
// Moving the HUD at rest also changes whether the lone icon is needed.
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
paint(hud);
await Promise.resolve();
assert.equal(cells[1].absorbed, false);
m.dispose();
}
});
test('a count stays visible when a lone camera would move it under the HUD', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 225 };
const m = counts(() => m.update(cells, project));
paint(hud);
m.update(cells, project);
assert.equal(paint(hud)[0]?.text, '2');
assert.equal(cells[1].absorbed, false);
await Promise.resolve();
paint(hud);
await Promise.resolve();
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
assert.equal(paint()[0]?.text, '3');
m.dispose();
});
test('a restored count includes the lone camera it still covers at the HUD edge', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 206, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 221 };
const scratch = {};
const update = () =>
m.update(cells, (p) => Object.assign(scratch, project(p)));
const m = counts(update);
update();
assert.equal(Math.round(paint()[0].x), 202);
paint(hud);
await Promise.resolve();
const [marker] = paint(hud);
assert.equal(marker?.text, '3');
assert.equal(Math.round(marker.x), 200);
assert.equal(cells[1].absorbed, true);
assert.ok(m.pickedCell({ x: 206, y: 300 }).parts.includes(cells[1]));
paint();
await Promise.resolve();
assert.equal(Math.round(paint()[0].x), 202);
m.dispose();
});
test('counts fade with the Scope keyhole like the callouts', () => {
const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha);
m.update([cellAt('a', 400, 2)], project);
assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25);
assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []);
assert.equal(m.pickedCell({ x: 400, y: 300 }), null);
assert.equal(paint()[0].alpha, 1);
});
@@ -0,0 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// Cesium's default 60 degree field of view spans the wider side, so a 4:3
// window has a vertical fovy of about 46.8 degrees. Two pairs 50 km and 80 km
// east of an eye 800 m up merge into one count. At half the distance all four
// fit in the frame (the group is wide, not tall), so the flight must keep all
// four in frame instead of approaching only the near pair.
test('a count click on an east-west group that fits keeps every member in the frame', () => {
const viewer = {};
const flights = [];
const aspectRatio = 800 / 600;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const members = [];
const cells = [50_000, 80_000].map((start) => {
const cell = createCameraCell(String(start));
for (const eastM of [start, start + 10]) {
const lon = eastM / M;
addCellCamera(cell, { lat: 0, lon, absoluteHeightM: 8 });
members.push(lon);
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
// Reference: a north-up top-down frame at half the distance holds all four.
const halfwayM = 65_005 / 2;
const refHalfX = halfwayM * Math.tan(fovy / 2) * aspectRatio;
assert.ok(members.every((lon) => Math.abs(lon * M - 65_005) <= refHalfX));
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfX = range * Math.tan(fovy / 2) * aspectRatio;
const inFrame = members.filter(
(lon) => Math.abs((lon - center.lon) * M) <= halfX,
);
assert.equal(
inFrame.length,
4,
`only ${inFrame.length} of 4 members in frame (range ${Math.round(range)} m)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
// A count of four merged in a tilted view: two pairs 10 km and 40 km north of
// an eye 800 m up. After the click, at least one member must be in frame.
test('a count click from a tilted view keeps the group members in the frame', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const metresPerDegree = 111_320;
const members = [];
const cells = [10_000, 40_000].map((start) => {
const cell = createCameraCell(String(start));
for (const northM of [start, start + 10]) {
const lat = northM / metresPerDegree;
addCellCamera(cell, { lat, lon: 0, absoluteHeightM: 8 });
members.push(fromDegrees(0, lat, 8));
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
const state = { _viewer: viewer };
const navigation = createNavigation({ state, parts: {} });
navigation.zoomToCell(groups[0]);
assert.equal(flights.length, 1);
const { range, pitch } = flights[0].options.offset;
assert.equal(pitch, -Math.PI / 2);
const { center } = flights[0].bounds;
const halfSpanM = range * Math.tan(fovy / 2);
assert.ok(
members.some((point) => distance(point, center) <= halfSpanM),
'no member of the group is in the final frame',
);
assert.ok(range < distance(fromDegrees(0, 0, 800), center));
} finally {
unbind();
}
});
@@ -0,0 +1,69 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// A count of 40 cameras 40 km north of an eye 800 m up takes in a lone camera
// 10 km north that is drawn just below it. The click must not land on the lone
// camera alone: at least one of the 40 counted cameras must be in the frame.
test('a count click does not fly to a lone camera that joined the count', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const crowd = createCameraCell('crowd');
const counted = [];
for (let i = 0; i < 40; i++) {
const lat = (40_000 + i / 4) / M;
addCellCamera(crowd, { lat, lon: 0, absoluteHeightM: 8 });
counted.push(lat);
}
const lone = createCameraCell('lone');
addCellCamera(lone, { lat: 10_000 / M, lon: 0, absoluteHeightM: 8 });
const screens = [
{ x: 400, y: 300 },
{ x: 400, y: 330 },
];
const groups = mergeCountCells(
[crowd, lone],
() => screens.shift(),
(count) =>
count > 1 ? { width: 40, height: 40 } : { width: 24, height: 24 },
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 41);
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfY = range * Math.tan(fovy / 2);
const inFrame = counted.filter(
(lat) => Math.abs((lat - center.lat) * M) <= halfY,
);
assert.ok(
inFrame.length > 0,
`none of the 40 counted cameras is in the frame (range ${Math.round(range)} m, centre ${Math.round(center.lat * M)} m north)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,65 @@
import * as picking from '../../data/pickRegistry.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
function setup() {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: { extractPickedCameraId: () => null },
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
return { click, counts: () => [zooms, clicks] };
}
test('a click a painted overlay target took (Space Missions label) does not fly to the count', () => {
const { click, counts } = setup();
// What the dispatcher hands subscribers after an onOverlayClick handler returned true.
click({
screenPosition: { x: 20, y: 26 },
overlay: true,
topHit: { set: '', id: null, surface: false },
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(
counts()[0],
0,
'count flight ran although an overlay target handled the click',
);
});
test("another layer's world-overlay card on top (clickCard) takes the click from the count", () => {
const { click, counts } = setup();
picking.setClickCardHitTest(() => ({
sourceId: 'earthquakes',
entryId: 'eq-1',
}));
try {
click({
screenPosition: { x: 20, y: 26 },
topHit: null,
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.ok(
picking.isUnderOtherCard({ screenPosition: { x: 1, y: 1 } }, ['cctv']),
);
assert.equal(counts()[0], 0, 'count flight ran under another layer card');
} finally {
picking.setClickCardHitTest(null);
}
});
@@ -0,0 +1,96 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on pairs 300 m above the ground under the group centre keeps a member in the frame', () => {
const aspectRatio = 4 / 3;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 800 },
{ eastM: 5000, h: 800 },
],
groundM: 500,
});
const flat = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 500 },
{ eastM: 5000, h: 500 },
],
groundM: 500,
});
assert.equal(flat.inFrame, 4);
assert.ok(r.inFrame > 0, `no member in frame: ${JSON.stringify(r)}`);
});
@@ -0,0 +1,84 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on a north-south group in a 32:9 window keeps every member in the frame', () => {
const aspectRatio = 32 / 9;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 800),
pairs: [
{ northM: 15_000, h: 8 },
{ northM: 17_000, h: 8 },
],
groundM: 8,
});
assert.equal(r.inFrame, 4, JSON.stringify(r));
});
+145
View File
@@ -0,0 +1,145 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0, y = H / 2) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, {
lon: lonFor(x),
lat: (Math.asin(((H / 2 - y) * 30) / A) * 180) / Math.PI,
absoluteHeightM: height,
});
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
// 75 counts in five staggered rows, no lone cameras and no active camera,
// pan right 7 CSS px per frame for 60 frames past a left HUD rail. Counts must
// still hide and reappear at the rail, but the paint must not start a full
// view pass on almost every frame: the motion timer passes the view every
// 250 ms, about 4 times in these 60 frames at 60 Hz.
test('a pan past the HUD edge does not pass the view on every frame', async () => {
const run = async (hud) => {
const cells = [];
for (let row = 0; row < 5; row++)
for (let col = 0; col < 15; col++)
cells.push(
cellAt(
`r${row}c${String(col).padStart(2, '0')}`,
30 + col * 50 + row * 10,
2,
0,
120 + row * 60,
),
);
let refreshes = 0;
let hiddenFrames = 0;
const m = counts(() => refreshes++);
m.update(cells, project);
for (let f = 0; f < 60; f++) {
const panned = matrix.slice();
panned[12] = (2 * (f * 7)) / W;
const labels = paint({ ...hud, viewProjectionMatrix: panned });
if (labels.length < 75) hiddenFrames++;
await Promise.resolve();
}
m.dispose();
return { refreshes, hiddenFrames };
};
const control = await run({});
const withHud = await run({ overlapsHardUi: (rect) => rect.x < 150 });
assert.equal(control.refreshes, 0);
assert.ok(withHud.hiddenFrames > 0, 'the HUD hides no count');
assert.ok(
withHud.refreshes <= 4,
`${withHud.refreshes} full view passes from paint in 60 frames`,
);
});
@@ -0,0 +1,59 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
// Earthquake discs (like fire perimeters and drone airspace) are deliberately
// unowned background fills. A clean tap on a count painted over a disc must
// zoom to the count and be the card on top for every layer, so Earthquakes
// opens no card. An owned scene object (an aircraft) still takes the click.
test('a count over an earthquake disc takes the click', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({ key: 'g' }) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (hit) => ({
screenPosition: { x: 20, y: 26 },
topHit: hit,
drawHit: hit,
hit,
gesture: { travelPx: 0, durationMs: 20 },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id.startsWith('aircraft:'));
try {
const disc = event({ set: 'earthquakes:1:discs', id: 'earthquake:abc' });
assert.deepEqual(picking.clickCard(disc), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(disc);
assert.deepEqual([zooms, clicks], [1, 0]);
const aircraft = event({ set: 'flights:icons', id: 'aircraft:abc' });
assert.equal(picking.clickCard(aircraft), null);
click(aircraft);
assert.deepEqual([zooms, clicks], [1, 1]);
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
+77 -47
View File
@@ -1,4 +1,4 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
@@ -22,11 +22,12 @@ export function createGround({ state: layerState, services, parts, source }) {
* - `google-3d` — photoreal stack: globe hidden, the visible Google 3D
* tileset IS the surface → one-shot scene sampling refines.
* - `terrain-globe` — any globe stack: the Re:Earth point-height prior IS the
* resolution (zero scene queries).
* resolution. A camera the batch left unanswered takes the
* drawn terrain from the view pass (`adoptDrawnGround`).
*
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* that never samples the scene's tiles. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
@@ -214,56 +215,84 @@ export function createGround({ state: layerState, services, parts, source }) {
let applied = 0;
let moved = 0;
for (let i = 0; i < records.length && i < priors.length; i++) {
const record = records[i];
const prior = priors[i];
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) continue;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
applied += 1;
} else if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
applied += 1;
}
const outcome = applyGroundPrior(records[i], priors[i]);
if (outcome === 'moved') moved += 1;
else if (outcome === 'applied') applied += 1;
}
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
* Gives one live record a ground prior: `'moved'` when only its icon went
* onto the prior in place, `'applied'` when its geometry was recomputed,
* null when nothing changed. Pure recomputes, no scene queries.
*/
function applyGroundPrior(record, prior) {
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) return null;
// The drawn terrain beats a fallback. Only a real batch answer replaces it.
if (
prior.source === 'geoid-fallback' &&
record.groundPrior?.source === 'drawn-terrain'
)
return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
fromDegreesInto(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
record.position,
);
parts.rendering.moveCameraIcon(record);
return 'moved';
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
return 'applied';
}
if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
return 'applied';
}
return null;
}
/**
* Applies drawn terrain as a drawn-terrain prior. The read records the eye
* distance (rangeM), globe surface version (surface) and whether terrain
* loading had finished (settled). Reading from under half that range or
* receiving a later Re:Earth answer replaces the height.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, read) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
...read,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +428,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+64
View File
@@ -0,0 +1,64 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createGround } from './ground.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
function setup(record) {
const calls = { culling: 0, geometry: [], notify: 0 };
const state = {
_viewer: null,
_recordById: new Map([[record.camera.id, record]]),
};
const parts = {
rendering: {
refreshHorizonCulling: () => (calls.culling++, true),
moveCameraIcon() {},
},
geometryQueue: { enqueueViewGeometry() {} },
presentation: { notifyListeners: () => calls.notify++ },
geometry: {
// Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell.
updateRecordGeometry(r) {
calls.geometry.push(
ground.groundPriorAltFor(r) + r.camera.mountHeightM,
);
},
},
};
const ground = createGround({
state,
services: {
ground: { resolveGroundFloorCells: async () => {} },
terrain: { resolveEllipsoidalGround: async () => [] },
},
parts,
});
return { ground, calls };
}
test('a late geoid fallback leaves a drawn-terrain height in place', () => {
const camera = {
id: 'a',
lat: 42,
lon: -118,
mountHeightM: 8,
absoluteHeightM: 1880,
};
const record = {
camera,
position: fromDegrees(camera.lon, camera.lat, 1880),
frustumGeometry: {},
frustumPositions: {},
groundSamples: {},
groundResolved: {},
groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 },
};
const { ground, calls } = setup(record);
ground.applyLateGroundPriors(
[record],
[{ ellipsoid: 0, source: 'geoid-fallback' }],
);
assert.equal(record.groundPrior.source, 'drawn-terrain');
assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback');
});
+45 -6
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
@@ -23,8 +23,14 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const {
resolvePickId,
registerPickOwner,
unregisterPickOwner,
clickCard,
registerClickClaim,
unregisterClickClaim,
} = services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -103,6 +109,30 @@ export function createLifecycle({
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const globe = findGlobe(layerState._viewer);
if (layerState._surfaceListenerGlobe !== globe) {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = globe;
}
if (!layerState._surfaceListener && globe?.on) {
// Refresh drawn heights when terrain finishes loading or the surface changes.
let version = globe.surfaceVersion?.();
let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0;
layerState._surfaceListener = globe.on('progress', (progress) => {
const next = globe.surfaceVersion?.();
const loaded = progress?.terrainPending === 0 && terrainPending !== 0;
const swapped = next !== version;
version = next;
terrainPending = progress?.terrainPending ?? terrainPending;
if (
(loaded || swapped) &&
layerState._enabled &&
!layerState._cameraMoving
)
settleView();
});
}
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
@@ -140,6 +170,9 @@ export function createLifecycle({
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
@@ -163,9 +196,11 @@ export function createLifecycle({
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
layerState._viewUnpublished = false;
layerState._viewPose = null;
layerState._viewMotionPass = null;
@@ -285,9 +320,8 @@ export function createLifecycle({
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
// groundPrior — { ellipsoid, source } from the Re:Earth batch
// (null until a late batch lands). The prior applies in EVERY
// regime and is the terrain-globe resolution outright.
// groundPrior — { ellipsoid, source } from the Re:Earth batch, or
// drawn-terrain with its read conditions for an unanswered camera.
// groundResolved — PER-REGIME one-shot latch (regime key →
// boolean): true once this record's resolution completed for that
// regime; such records are excluded from the completion pass so
@@ -386,6 +420,7 @@ export function createLifecycle({
parts.rendering.refreshHorizonCulling();
const input = inputFor(layerState._viewer);
layerState._clickSubscription?.();
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
@@ -481,6 +516,7 @@ export function createLifecycle({
);
return Boolean(coverage && layerState._recordById.has(coverage[1]));
});
registerClickClaim?.('cctv', parts.selection.countClickCard);
if (!layerState._activeCameraId && layerState._records.length) {
layerState._activeCameraId = parts.navigation.openingCameraId();
layerState._autoHopSuspended = false;
@@ -517,6 +553,7 @@ export function createLifecycle({
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._enabled = false;
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
// ADJUST mode does not survive a layer toggle — predictable re-entry.
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
@@ -532,6 +569,7 @@ export function createLifecycle({
parts.rendering.hideCctvVisuals();
// Nothing is in view while the layer is off.
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
parts.presentation.notifyListeners();
},
@@ -550,6 +588,7 @@ export function createLifecycle({
parts.cards.handleVisibilityChange,
);
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
if (layerState._mapStackListener && typeof window !== 'undefined') {
window.removeEventListener(
'gev:map-stack-changed',
+34
View File
@@ -77,6 +77,40 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.equal(state._viewListenerCamera, null);
});
test('terrain loading and surface changes rerun the view pass', () => {
const viewer = {};
let version = 1,
progress,
removed = false;
bindRenderer(viewer, {
camera: fakeCameraPort().port,
globe: {
surfaceVersion: () => version,
on(event, cb) {
assert.equal(event, 'progress');
progress = cb;
return () => {
removed = true;
};
},
},
});
const { lifecycle, passes } = lifecycleFor({
_viewer: viewer,
_enabled: true,
});
lifecycle.attachViewListeners();
progress({ terrainPending: 2 });
assert.equal(passes.length, 0);
progress({ terrainPending: 0 });
assert.equal(passes.length, 1);
version++;
progress({ terrainPending: 0 });
assert.equal(passes.length, 2);
lifecycle.detachViewListeners();
assert.ok(removed);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
+64 -57
View File
@@ -456,33 +456,60 @@ const BRAND_ALIASES = {
Hikvision: ['hiwatch'],
};
function brandWords(record) {
return new Set([
...words(record.brand),
...(BRAND_ALIASES[record.brand] || []),
]);
}
/**
* One entry per record name (model + aliases). `required` is every
* non-generic word of the name — all must appear in a query, so a generation
* or suffix ("Mk II", "7000i" vs "7000") is never dropped. `hasCode` marks
* names carrying a letter+digit model code; names without one ("3950",
* "01959-004", "AUTODOME 800 Series") match only when the brand does.
*/
const NAME_INDEX = RECORDS.flatMap((record) => {
const brand = brandWords(record);
return [record.model, ...(record.aliases || [])].map((name) => {
const nameWords = words(name);
return {
record,
brand,
allowed: new Set(nameWords),
required: nameWords.filter((word) => !isGeneric(word)),
hasCode: nameWords.some(isModelCode),
};
/** A model lookup over `records` with this module's matching rules (see lookupModelSpec). */
export function createModelSpecLookup(records) {
/**
* One entry per record name (model + aliases). `required` is every
* non-generic word of the name — all must appear in a query, so a
* generation or suffix ("Mk II", "7000i" vs "7000") is never dropped.
* `hasCode` marks names carrying a letter+digit model code; names without
* one ("3950", "01959-004", "AUTODOME 800 Series") match only when the
* brand does.
*/
const nameIndex = records.flatMap((record) => {
const brand = new Set([
...words(record.brand),
...(BRAND_ALIASES[record.brand] || []),
]);
return [record.model, ...(record.aliases || [])].map((name) => {
const nameWords = words(name);
return {
record,
brand,
allowed: new Set(nameWords),
required: nameWords.filter((word) => !isGeneric(word)),
hasCode: nameWords.some(isModelCode),
};
});
});
});
return (model, manufacturer) => {
const query = words(model).map(stripVariantSuffix);
if (!query.length) return null;
const maker = words(manufacturer);
const found = new Set();
for (const entry of nameIndex) {
const makerMatches = maker.some((word) => entry.brand.has(word));
if (maker.length && !makerMatches) continue;
if (
!entry.hasCode &&
!makerMatches &&
!query.some((word) => entry.brand.has(word))
)
continue;
if (!entry.required.length) continue;
if (!entry.required.every((word) => query.includes(word))) continue;
if (
!query.every(
(word) =>
entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word),
)
)
continue;
found.add(entry.record);
}
return found.size === 1 ? [...found][0] : null;
};
}
/**
* Looks up a spec record for a hardware-model string.
@@ -502,33 +529,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => {
* @param {string} [manufacturer] - The source's manufacturer, when published.
* @returns {Object|null} The matched spec record, or null when unknown.
*/
export function lookupModelSpec(model, manufacturer) {
const query = words(model).map(stripVariantSuffix);
if (!query.length) return null;
const maker = words(manufacturer);
const found = new Set();
for (const entry of NAME_INDEX) {
const makerMatches = maker.some((word) => entry.brand.has(word));
if (maker.length && !makerMatches) continue;
if (
!entry.hasCode &&
!makerMatches &&
!query.some((word) => entry.brand.has(word))
)
continue;
if (!entry.required.length) continue;
if (!entry.required.every((word) => query.includes(word))) continue;
if (
!query.every(
(word) =>
entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word),
)
)
continue;
found.add(entry.record);
}
return found.size === 1 ? [...found][0] : null;
}
export const lookupModelSpec = createModelSpecLookup(RECORDS);
/**
* Datasheet horizontal FOV as the range the hardware can cover. Only
@@ -602,13 +603,19 @@ export function specFovCapabilityToken(
/**
* One-line spec summary for HUD meta text.
* @param {Object} spec - A record from this module.
* @param {Object} spec - A spec record (CCTV or ALPR). Resolution falls back
* from label to WxH to NMP.
* @param {{withBrand?: boolean}} [options] - `withBrand: false` leaves the
* brand out.
* @returns {string} e.g. 'Axis Q6135-LE · 1080p · IR 250m · PTZ' ('' for null).
*/
export function specSummary(spec) {
export function specSummary(spec, { withBrand = true } = {}) {
if (!spec) return '';
const parts = [`${spec.brand} ${spec.model}`];
if (spec.resolution?.label) parts.push(spec.resolution.label);
const parts = [withBrand ? `${spec.brand} ${spec.model}` : spec.model];
const { label, w, h, mp } = spec.resolution || {};
if (label) parts.push(label);
else if (w && h) parts.push(`${w}x${h}`);
else if (mp) parts.push(`${mp}MP`);
if (spec.night_vision) {
parts.push(
`${spec.night_vision.type.toUpperCase()}${spec.night_vision.range_m ? ` ${spec.night_vision.range_m}m` : ''}`,
+86 -7
View File
@@ -1,6 +1,14 @@
import { distance } from '../../geo/vector.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { rangeForBoundingSphere } from '../../data/cameraFraming.js';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
import {
cellBounds,
cellCenter,
cellHalfExtents,
} from '../../data/cctvCellCounts.js';
import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -79,6 +87,16 @@ export function createNavigation({
return true;
}
/** What holds the view instead of a CCTV flight, or null when it is free. */
function viewHeldBy(viewer) {
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
)
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null;
}
/**
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
@@ -90,14 +108,12 @@ export function createNavigation({
function focusCctvRecord(viewer, record, duration = 2.2) {
if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA;
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
) {
const held = viewHeldBy(viewer);
if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) {
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (isFollowing(viewer)) {
if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -120,6 +136,68 @@ export function createNavigation({
return CCTV_FOCUS_RESULT.FOCUSED;
}
/** The nearest ground cell with two or more cameras, or the group itself if unmerged. */
function nearestPart(cell, eye) {
let nearest = cell;
let best = Infinity;
for (const part of cell.parts ?? []) {
if (part.count < 2) continue;
const d = distance(eye, cellCenter(part));
if (d < best) {
best = d;
nearest = part;
}
}
return nearest;
}
/** Frame a group's padded bounds from above, including coincident mounts. */
function zoomToCell(cell) {
const viewer = layerState._viewer;
if (!viewer || viewHeldBy(viewer)) return;
const camera = cameraOf(viewer);
const pose = camera.pose();
const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2);
const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height || 1;
// Half the range where cells stop grouping, so even coincident mounts split.
const closeRange =
(VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY);
const tanHalfX = tanHalfY * (pose.aspectRatio || 1);
// Range where a cell's ground extent, times `pad`, fits the frame at the
// depth of its highest mount above the bounds centre.
const extentRange = (target, bounds, pad = 1) => {
const { halfWidthM, halfHeightM } = cellHalfExtents(target);
const rise = Math.max(0, target.high - toLonLatH(bounds.center).height);
return (
rise + pad * Math.max(halfWidthM / tanHalfX, halfHeightM / tanHalfY)
);
};
// The sphere fit spans the wider side, so a very wide window also needs the extent.
const fitRange = (target, bounds) =>
Math.max(
closeRange,
rangeForBoundingSphere(viewer, bounds.radius),
extentRange(target, bounds, 1.2),
);
// Approach long groups in halves so every click gets closer.
const halfway = (bounds) =>
pose.position ? distance(pose.position, bounds.center) / 2 : Infinity;
let bounds = cellBounds(cell);
let range = Math.min(halfway(bounds), fitRange(cell, bounds));
// If the group overflows the frame at that range, approach its nearest counted cell.
if (range < extentRange(cell, bounds)) {
const part = nearestPart(cell, pose.position);
bounds = cellBounds(part);
range = Math.min(halfway(bounds), fitRange(part, bounds));
}
camera.flyToBounds(bounds, {
offset: { heading: 0, pitch: -Math.PI / 2, range },
durationS: 1.2,
easing: 'cubicInOut',
});
}
function focusCamera(cameraId, duration = 2.2) {
return focusCctvRecord(
layerState._viewer,
@@ -196,6 +274,7 @@ export function createNavigation({
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
zoomToCell,
focusCamera,
maybeAutoHop,
cctvCycleIndex,
+66 -18
View File
@@ -60,17 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300;
export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10;
// View thinning: camera icons show only on or near the screen, and each
// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX
// at its distance from the viewer (in power-of-two metre steps, so a pan
// keeps the same winners until a camera's distance crosses a step). Cells
// smaller than VIEW_MIN_CELL_M do not thin:
// close up every camera shows, co-located ones included.
// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX
// at their distance. Power-of-two metre steps keep cells stable during a pan.
// A cell with several cameras draws one count. Its best-ranked camera represents
// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so
// every camera shows close up.
export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Cameras within this horizontal distance in metres share a mount.
export const VIEW_SITE_M = 1.5;
// Cameras on one mount (VIEW_SITE_M) draw side by side,
// this many pixels apart, once they show as icons.
export const VIEW_SITE_SPREAD_PX = 30;
// Drawn-terrain reads per view pass for unanswered cameras and for re-reads
// of drawn heights. Off-screen cameras can use at most half of the budget.
// Remaining reads wait for the next pass.
export const VIEW_GROUND_READS = 300;
/**
* The camera icon's drawn size (px). Its SVG is 48 px: 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
export const CAMERA_ICON_PX = 24;
// Minimum gap between the outer rims of two separate markers.
export const COUNT_MERGE_GAP_PX = 4;
// Icons this far past the screen edge (fraction of its size) still show, so
// a pan does not reveal empty ground before the next view pass.
@@ -182,28 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
/**
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
* 2× display draws it at 60 device px, and it stays sharp there.
* 2× display draws it at 60 device px, and it stays sharp there. Active and
* live cameras use cyan art with a billboard tint. Idle cameras use white
* and gray art so the billboard green shows true. The overlay draws the
* green variant directly.
*/
export const CAMERA_ICON = (() => {
function cameraIcon(tint = null) {
function tone(original, gray) {
if (!tint) return original;
const shade = parseInt(gray.slice(1, 3), 16) / 255;
return (
'#' +
tint
.slice(1)
.match(/../g)
.map((channel) =>
Math.round(parseInt(channel, 16) * shade)
.toString(16)
.padStart(2, '0'),
)
.join('')
);
}
const stroke = tone('#75e7ff', '#ffffff');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/>
<stop offset="45%" stop-color="#6fd9ff"/>
<stop offset="100%" stop-color="#1a5f78"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="#0e1720" stroke="#75e7ff" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="#132433" stroke="#75e7ff" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="#dbfbff" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="#10212d" stroke="#75e7ff" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="#0b151d" stroke="#4ecde7" stroke-width="0.8"/>
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
})();
}
export const CAMERA_ICON = cameraIcon();
export const IDLE_CAMERA_ICON = cameraIcon('#ffffff');
/**
* Seed camera definitions used when no live sources are available.
@@ -441,7 +485,11 @@ export const CAMERA_SEEDS = [
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
/** Shared accent for idle still cameras and grouped cameras. */
export const CAMERA_GREEN = '#5dff8f';
export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN);
export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
+12 -9
View File
@@ -229,9 +229,12 @@ export function createPresentation({
// separately from the currently applied frustum ground. Google-3D may
// legitimately refine the latter to the rendered mesh, so callers must
// not infer the prior by subtracting mount height from live geometry.
groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid)
? record.groundPrior.ellipsoid
: null,
// A height read from drawn terrain is unavailable as a Re:Earth prior.
groundPriorM:
Number.isFinite(record.groundPrior?.ellipsoid) &&
record.groundPrior.source !== 'drawn-terrain'
? record.groundPrior.ellipsoid
: null,
intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null,
extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null,
anchor: camera.anchor ? { ...camera.anchor } : null,
@@ -310,16 +313,16 @@ export function createPresentation({
}
/**
* `{ id, city, name }` for the active camera, then every camera the view
* pass shows: what the camera picker lists. A whole catalog would put tens
* of thousands of options in the DOM and slow every layout. The same array
* is returned until the view or the active camera changes, so a consumer
* can compare it by identity.
* `{ id, city, name }` for the active camera, then each camera shown as an
* icon and the best-ranked camera of each visible group. A whole catalog
* would put tens of thousands of options in the DOM and slow every layout.
* Consumers can compare the array by identity until the picker records or
* active camera change.
* @returns {{id: string, city: string, name: string}[]}
*/
function cameraIndex() {
const view = layerState._viewRecords;
const view = layerState._pickerRecords;
const active = parts.selection.getActiveRecord();
const cached = layerState._cameraIndexCache;
if (cached?.view === view && cached.active === active) return cached.list;
+416 -87
View File
@@ -1,7 +1,13 @@
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
VIEW_SITE_M,
IDLE_CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
ACTIVE_COVERAGE_CENTER,
@@ -14,6 +20,8 @@ import {
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
VIEW_SITE_SPREAD_PX,
VIEW_GROUND_READS,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
@@ -24,11 +32,21 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { heightsOf } from '../../queries/heights.js';
import {
fromDegrees,
fromDegreesInto,
toLonLatH,
WGS84,
} from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import { add, distance, dot, scale, sub } from '../../geo/vector.js';
const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR };
const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR };
const LIVE_ICON_STYLE = { image: CAMERA_ICON, color: LIVE_CAMERA_COLOR };
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
@@ -46,12 +64,6 @@ const samePoint = (a, b) =>
/** Degrees to radians. */
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
const CAMERA_ICON_PX = 24;
const CAMERA_SCALE_BY_DISTANCE = Object.freeze({
near: 350,
nearValue: 1.25,
@@ -139,6 +151,12 @@ export function createRendering({
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
layerState._counts = createCountMarkers(
services.overlays?.registerWorldOverlayPaintLane,
`cctv:${iconSets}:counts`,
refreshViewFromCounts,
services.overlays?.keyholeAlpha,
);
return set.id;
}
@@ -146,6 +164,8 @@ export function createRendering({
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
layerState._counts?.dispose();
layerState._counts = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
@@ -153,10 +173,9 @@ export function createRendering({
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
pos: copyPoint(record.spreadPosition ?? record.position),
...cameraIconStyleFor(record),
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
@@ -195,22 +214,26 @@ export function createRendering({
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
// A camera drawn beside its mount mates keeps its offset from the mount.
if (record.spreadOffset)
record.spreadPosition = add(record.position, record.spreadOffset);
const pos = record.spreadPosition ?? record.position;
const item = icons.item(record.camera.id);
// A camera whose icon waited for a position is drawn now.
if (!item) {
icons.put(cameraIconItem(record));
return;
}
if (samePoint(item.pos, record.position)) return;
icons.put({ ...item, pos: copyPoint(record.position) });
if (samePoint(item.pos, pos)) return;
icons.put({ ...item, pos: copyPoint(pos) });
}
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
function cameraColorFor(record) {
/** Select the sprite and tint together when a camera changes state. */
function cameraIconStyleFor(record) {
if (record.camera.id === layerState._activeCameraId)
return ACTIVE_CAMERA_COLOR;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR;
return IDLE_CAMERA_COLOR;
return ACTIVE_ICON_STYLE;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_ICON_STYLE;
return IDLE_ICON_STYLE;
}
const {
@@ -219,11 +242,14 @@ export function createRendering({
focusPassIsNeeded,
advanceSpriteFocus,
focusAlphaNeedsWrite,
nearFarScalarValueAtDistance,
} = services.focus;
const iconScaleAt = (range) =>
nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1;
/**
* Focus modulation rides the layer's existing animation loop; no additional
* scene listener is installed. Only camera-icon alpha changes here — coverage
* scene listener is installed. Camera and count icons share the fade. Coverage
* geometry and monitor-plane styling retain their established cadence.
*/
@@ -276,61 +302,76 @@ export function createRendering({
let writes = 0;
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(item.meta, {
// Keep hidden icons in the state/release pass so the active count cannot
// drop while a stale dim alpha remains waiting to reappear.
screenPosition:
item.show === false || !position ? null : screenPositionFor(position),
/**
* A changed focus factor for an icon or count. CCTV publishes no tracked
* focus target, so every icon is ambient.
*/
function changedFocus(owner, position, shown, width, height, current) {
const focus = advanceSpriteFocus(owner, {
// Keep hidden owners in the active count until their dim alpha clears,
// so the focus pass keeps running while they recover.
screenPosition: shown && position ? screenPositionFor(position) : null,
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
target,
params,
spriteHalfWidthPx: item.size[0] * scale * 0.5,
spriteHalfHeightPx: item.size[1] * scale * 0.5,
spriteHalfWidthPx: width / 2,
spriteHalfHeightPx: height / 2,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
writes += 1;
}
if (focus.active) activeCount++;
if (!focusAlphaNeedsWrite(current, focus.factor, params)) return null;
writes++;
return focus.factor;
}
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const scale = item.scale ?? 1;
const factor = changedFocus(
item.meta,
record.position,
item.show !== false,
item.size[0] * scale,
item.size[1] * scale,
icons.focus(id),
);
if (factor !== null) icons.setFocus(id, factor);
}
const counts = layerState._counts;
const iconWrites = writes;
for (const marker of counts?.markers ?? []) {
const factor = changedFocus(
marker,
marker.pos,
true,
marker.width,
marker.height,
marker.focus,
);
if (factor !== null) marker.focus = factor;
}
if (writes > iconWrites) counts.requestPaint();
return { writes, transitioning, activeCount, ran: true };
}
/** During camera motion the timer and settle pass refresh the counts. */
function refreshViewFromCounts() {
if (!layerState._cameraMoving) refreshHorizonCulling();
}
/**
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
* cell sized to VIEW_CELL_PX at its distance (healthiest first, then a stable
* id order). The active camera shows whenever it is above the horizon
* and near the screen, even in a crowded cell. The shown records become
* `_viewRecords`, the working set for geometry, cards and the camera picker;
* the array keeps its identity while the shown set is unchanged.
* Cull far-side cameras on the CPU because the hidden globe writes no depth.
* Group the rest by ground cell. _viewRecords holds the active camera and
* every nearby icon outside a count for geometry and cards. Cells smaller
* than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the
* best-ranked camera of each visible cell. Both arrays keep their identity
* while their contents are unchanged.
*
* Runs on camera settle, throttled during motion, on resize, enable and
* activation changes — never per frame.
* @returns {boolean} Whether the shown set changed.
* @returns {boolean} Whether the shown set or the picker list changed.
*/
function refreshHorizonCulling() {
@@ -365,7 +406,30 @@ export function createRendering({
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const picker = [];
const cells = new Map();
const visibleCells = [];
// Drawn terrain where the globe is the surface. The photoreal stack has
// no reader, and unloaded tiles return a non-finite height.
const heights = heightsOf(layerState._viewer);
const globe = findGlobe(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
const surface = globe?.surfaceVersion?.() ?? 0;
const terrainSettled = globe?.isSettled?.('terrain') ?? true;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
let offscreenReads = groundReads / 2;
let eyeGround;
const column = { x: 0, y: 0, z: 0 };
const inReadWindow = (s) =>
s &&
s.x >= -width &&
s.x <= 2 * width &&
s.y >= -height &&
s.y <= 2 * height;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -380,48 +444,307 @@ export function createRendering({
(vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared
)
continue;
const screen = project(position);
let screen = project(position);
let range = distance(position, viewer);
// Missing, unresolved and fallback priors can put a mount kilometres
// below the terrain, shifting its projection and inflating its cell.
// Read nearby mounts again from under half the range, on finer terrain
// after loading, or on a different surface.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
const unanswered =
!Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback';
if (
!screen ||
!(screen.x >= minX && screen.x <= maxX) ||
!(screen.y >= minY && screen.y <= maxY)
)
continue;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
const cellM =
VIEW_CELL_PX *
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
record.viewPass = pass;
groundReads > 0 &&
!record.regroundPending &&
(unanswered ||
(drawn &&
(prior.rangeM > 2 * range ||
prior.surface !== surface ||
(!prior.settled && terrainSettled))))
) {
let probe = inReadWindow(screen) ? screen : null;
if (!probe && unanswered) {
// Its height is a guess. Try the ground under the eye instead.
if (eyeGround === undefined) {
const eye = toLonLatH(viewer);
eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null;
groundReads--;
}
if (Number.isFinite(eyeGround)) {
fromDegreesInto(
record.camera.lon,
record.camera.lat,
eyeGround + (record.camera.mountHeightM || 0),
column,
);
const at = project(column);
if (inReadWindow(at)) probe = at;
}
}
const onScreen =
probe &&
probe.x >= 0 &&
probe.x <= width &&
probe.y >= 0 &&
probe.y <= height;
if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) {
groundReads--;
if (!onScreen) offscreenReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
const read = { rangeM: range, surface, settled: terrainSettled };
if (drawn && Math.abs(ground - prior.ellipsoid) < 1)
Object.assign(prior, read);
else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets after this pass.
record.regroundPending = true;
regrounded.push([record, ground, read]);
} else parts.ground.adoptDrawnGround(record, ground, read);
}
}
// The probe reuses the projector's result, and the mount may have moved.
screen = project(position);
range = distance(position, viewer);
}
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
shown.push(record);
picker.push(record);
continue;
}
if (!(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
// Too close to group, but a count beside it can still take it in.
const cell = createCameraCell(`near:${record.camera.id}`);
addCellCamera(cell, record.camera);
cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
cell.winner = record;
cell.rank = 0;
record.viewCell = cell;
visibleCells.push(cell);
continue;
}
const key = worldCellKey(record, cellM);
let cell = cells.get(key);
if (!cell) {
cell = createCameraCell(key);
cells.set(key, cell);
}
addCellCamera(cell, record.camera);
if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
record.viewCell = cell;
if (!nearScreen) continue;
// The picker ranks only candidates that were in its padded viewport.
if (!cell.winner) visibleCells.push(cell);
const rank = viewRank(record);
const holder = cells.get(key);
if (!holder || rank < holder.rank) cells.set(key, { record, rank });
if (rank < cell.rank) {
cell.winner = record;
cell.rank = rank;
}
}
for (const { record } of cells.values()) {
record.viewPass = pass;
shown.push(record);
// Check each mount mate against counts where its icon will be drawn.
const lone = visibleCells.filter((cell) => cell.count === 1);
spreadSharedMounts(
shown.concat(lone.map((cell) => cell.winner)),
pose,
metresPerPixelPerMetre,
pass,
);
for (const cell of lone)
cell.offsetPx =
cell.winner.spreadPass === pass ? cell.winner.spreadPx : 0;
// A count stands on the drawn terrain too: its cell may be too far for
// its cameras to have been read. Marks each lone camera that a count
// marker beside it has taken in.
layerState._counts?.update(visibleCells, project, groundHeight);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
record.pickerPass = pass;
if (cell.count === 1 && !cell.absorbed) {
record.viewPass = pass;
shown.push(record);
}
}
clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
for (const record of layerState._records) {
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const cell = record.viewCell;
record.viewCell = null;
const grouped = Boolean(
cell?.winner && (cell.count > 1 || cell.absorbed),
);
if (grouped !== !!record.viewGrouped) {
const id = record.camera.id;
coverageChanged ||= layerState._coverageCohort?.has(id);
cardsChanged ||=
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const fields = { show: record.viewPass === pass };
if (record.spreadPass === pass) {
const drawn = layerState._icons?.item(record.camera.id)?.pos;
if (!drawn || !samePoint(drawn, record.spreadPosition))
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadOffset = null;
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
const item = patchedCameraIcon(record.camera.id, fields);
if (item) writes.push(item);
}
writeCameraIcons(writes);
if (regrounded.length) queueMicrotask(() => reground(regrounded));
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
previous.some((record) => record.viewPass !== pass);
if (changed) layerState._viewRecords = shown;
return changed;
const oldPicker = layerState._pickerRecords ?? [];
const pickerChanged =
picker.length !== oldPicker.length ||
oldPicker.some((record) => record.pickerPass !== pass);
if (pickerChanged) layerState._pickerRecords = picker;
if (coverageChanged) refreshCoverageStyles();
if (cardsChanged) parts.cards.pushAmbientCardEntries();
return changed || pickerChanged;
}
/**
* Cameras that have geometry take the drawn terrain after the pass that
* read it, then the view is passed again from their new positions.
*/
function reground(entries) {
let changed = false;
for (const [record, ground, read] of entries) {
record.regroundPending = false;
changed =
parts.ground.adoptDrawnGround(record, ground, read) !== null || changed;
}
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
}
/**
* Cameras on one mount would draw as one icon with several callouts. Among
* icon candidates, those within VIEW_SITE_M horizontally get draw positions
* side by side in id order, `VIEW_SITE_SPREAD_PX` apart on screen. A mate
* absorbed by a count keeps its place in the row. Geometry and cards stay
* on the mount.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const grid = new Map();
const mounts = [];
const axes = eastNorthUp(eye);
for (const record of shown) {
// Sea-level coordinates compare horizontal distance across longitude
// and latitude boundaries, including the antimeridian.
const p = fromDegrees(record.camera.lon, record.camera.lat, 0);
const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M);
const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M);
let mount;
for (let i = col - 1; !mount && i <= col + 1; i++)
for (let j = row - 1; !mount && j <= row + 1; j++)
mount = grid
.get(`${i}:${j}`)
?.find((site) => distance(p, site.p) <= VIEW_SITE_M);
if (!mount) {
mount = { p, mates: [] };
mounts.push(mount);
const key = `${col}:${row}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(mount);
}
mount.mates.push(record);
}
for (const { mates } of mounts) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
const record = mates[i];
const p = record.position;
// A pixel's width on the ground grows with depth along the view.
const depth =
(p.x - eye.x) * direction.x +
(p.y - eye.y) * direction.y +
(p.z - eye.z) * direction.z;
const px = (i - (mates.length - 1) / 2) * VIEW_SITE_SPREAD_PX;
record.spreadPx = px;
const metres = px * metresPerPixelPerMetre * depth;
record.spreadOffset = scale(right, metres);
record.spreadPosition = add(p, record.spreadOffset);
record.spreadPass = pass;
}
}
}
/** Only counts visible outside the HUD push the active icon aside. */
function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) {
const markers = layerState._counts?.markers;
for (const marker of markers ?? []) marker.besideActive = false;
if (!layerState._activeCameraId) return;
const record = layerState._recordById.get(layerState._activeCameraId);
if (
record?.viewPass !== pass ||
!markers?.length ||
!pose.right ||
!pose.direction
)
return;
const spread = record.spreadPass === pass;
const p = spread ? record.spreadPosition : record.position;
const screen = project(p);
if (!screen) return;
const { x, y } = screen;
const half =
(CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2;
const spans = [];
for (const marker of markers) {
const at = project(marker.pos);
if (
!at ||
Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX
)
continue;
marker.besideActive = true;
if (marker.hudHidden) continue;
const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX;
spans.push([at.x - reach, at.x + reach]);
}
// Leave the entire overlapping interval, including an adjacent count.
spans.sort((a, b) => a[0] - b[0]);
let left = Infinity,
right = -Infinity;
for (const [start, end] of spans) {
if (start >= right) {
if (left < x && x < right) break;
left = start;
right = end;
} else right = Math.max(right, end);
}
if (!(left < x && x < right)) return;
const shift = x - left < right - x ? left - x : right - x;
const depth = dot(sub(p, pose.position), pose.direction);
const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth);
record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset;
record.spreadPosition = add(record.position, record.spreadOffset);
record.spreadPass = pass;
}
/**
@@ -526,6 +849,7 @@ export function createRendering({
);
parts.projection.clearProjectionOverlay();
if (layerState._icons) layerState._icons.show = false;
layerState._counts?.hide();
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -535,8 +859,12 @@ export function createRendering({
const activeRecord = parts.selection.getActiveRecord();
parts.geometry.ensureActiveCoverageEntities(activeRecord);
const activeId = activeRecord?.camera.id || null;
const coverageVisible =
parts.geometry.buildCoverageVisibleSet(activeRecord);
const cohort = parts.geometry.buildCoverageVisibleSet(activeRecord);
layerState._coverageCohort = cohort;
const coverageVisible = new Set();
for (const id of cohort) {
if (!layerState._recordById.get(id)?.viewGrouped) coverageVisible.add(id);
}
// Drawn coverage needs geometry too (geometryQueue's working set).
layerState._coverageVisibleIds = coverageVisible;
const coverageOn = layerState._coverageMode !== 'off';
@@ -553,7 +881,7 @@ export function createRendering({
for (const record of layerState._records) {
const isActive = record.camera.id === activeId;
const icon = patchedCameraIcon(record.camera.id, {
color: cameraColorFor(record),
...cameraIconStyleFor(record),
scale: isActive ? 1.25 : 1.0,
});
if (icon) restyled.push(icon);
@@ -865,6 +1193,7 @@ export function createRendering({
* @returns {string|null}
*/
function pickCameraIdAt(position) {
if (layerState._counts?.pickedCell(position)) return null;
let hit = null;
try {
hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null;
+85 -2
View File
@@ -1,7 +1,7 @@
// src/layers/cctv/rendering.test.mjs
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
// from the same base color the coverage refresh assigns, so a video-feed camera
// stays violet while it dims instead of falling back to the idle cyan.
// stays violet while it dims instead of falling back to the idle green.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
@@ -114,29 +114,80 @@ test('focus de-emphasis fades each icon from its own color', () => {
}
});
test('focus uses the painted half-width and half-height of each count', () => {
const markers = [
{ width: 40, height: 40 },
{ width: 72, height: 58 },
];
const sizes = [];
const rendering = createRendering({
state: { _counts: { markers } },
services: {
focus: {
focusPassIsNeeded: () => true,
advanceSpriteFocus(_owner, { spriteHalfWidthPx, spriteHalfHeightPx }) {
sizes.push([spriteHalfWidthPx, spriteHalfHeightPx]);
return { factor: 1 };
},
focusAlphaNeedsWrite: () => false,
},
},
});
rendering.applyCctvFocusDeemphasis({});
assert.deepEqual(sizes, [
[20, 20],
[36, 29],
]);
});
test('the icons go with the viewer that drew them, whichever tears down', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const lanes = [];
const overlays = {
registerWorldOverlayPaintLane(name, paint, options) {
const lane = {
name,
paint,
options,
setActive() {},
unregister() {
this.disposed = true;
},
};
lanes.push(lane);
return lane;
},
};
const { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus: {} },
services: { focus: {}, overlays },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
assert.equal(one.draw.sets.size, 1);
assert.equal(lanes[0].name, 'ambient-label');
assert.equal(lanes[0].options.target, 'shared');
assert.equal(lanes[0].options.active, false);
state._viewer = second;
const current = createCameraIcons(second);
assert.notEqual(old, current);
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
assert.equal(two.draw.sets.get(current).disposed, false);
assert.equal(lanes[0].disposed, true);
lanes[0].paint({});
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
assert.equal(lanes[1].disposed, true);
lanes[1].paint({});
assert.equal(state._counts, null);
} finally {
one.unbind();
two.unbind();
@@ -376,3 +427,35 @@ test('a pose with no perspective field of view is projected by the renderer', ()
unbind();
}
});
test('hover picks the underlying camera only outside a painted count', () => {
const viewer = {};
const icon = { set: 'icons', id: 'camera' };
let picks = 0;
const unbind = bindRenderer(viewer, {
query: {
pick() {
picks++;
return icon;
},
},
});
try {
const state = {
_viewer: viewer,
_counts: { pickedCell: ({ x }) => (x <= 17 ? {} : null) },
_icons: { setId: icon.set, has: () => true },
_recordById: new Map([[icon.id, {}]]),
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
assert.equal(rendering.pickCameraIdAt({ x: 17, y: 0 }), null);
assert.equal(picks, 0);
assert.equal(rendering.pickCameraIdAt({ x: 18, y: 0 }), icon.id);
} finally {
unbind();
}
});
+65 -5
View File
@@ -1,3 +1,7 @@
import {
CCTV_COUNT_CARD_SOURCE_ID,
CCTV_OVERLAY_SOURCE_ID,
} from '../../data/cctvCards.js';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
@@ -7,7 +11,13 @@ export function createSelection({
source,
}) {
const { CCTV_ACTIVATION_RESULT } = services.activation;
const { resolvePickId } = services.picking;
const {
resolvePickId,
findPickOwner,
isOwnedByOtherLayer,
isUnderOtherCard,
} = services.picking;
const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID];
/**
* Returns the camera record for the currently active camera. A stale ID falls
@@ -29,6 +39,49 @@ export function createSelection({
return fallback;
}
/** Whether another layer's scene object owns the click at this count. */
function sceneTakesCountClick(event) {
const top = event.topHit;
if (!top) return false;
const drawHit = event.drawHit;
if (drawHit) {
// Unowned fills, such as earthquake discs, let the count take the click.
if (parts.rendering.extractPickedCameraId(drawHit)) return false;
const id = resolvePickId(drawHit);
return id !== null && Boolean(isOwnedByOtherLayer?.('cctv', id));
}
const id = resolvePickId(top);
return id !== null && findPickOwner?.(id) !== 'cctv';
}
/** Leave other layers' cards to the caller since clickCard also calls this. */
function clickedCount(event) {
if (
!isTrackingClickGesture(event.gesture) ||
!layerState._enabled ||
event.overlay
)
return null;
const cell = layerState._counts?.pickedCell(event.screenPosition);
if (!cell) return null;
const { x, y } = event.screenPosition;
if (
layerState._cctvOverlayHost?.hitTest(x, y, {
sourceId: CCTV_OVERLAY_SOURCE_ID,
})?.entryId
)
return null;
return sceneTakesCountClick(event) ? null : cell;
}
/** The count marker as the card on top of a click it takes, for every layer's clickCard. */
function countClickCard(event) {
const cell = clickedCount(event);
return cell
? { sourceId: CCTV_COUNT_CARD_SOURCE_ID, entryId: String(cell.key ?? '') }
: null;
}
/**
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
@@ -41,6 +94,12 @@ export function createSelection({
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
const cell = clickedCount(event);
// Another layer's card or label painted above the count takes the click.
if (cell && !isUnderOtherCard?.(event, OWN_CARD_SOURCES)) {
parts.navigation.zoomToCell(cell);
return;
}
onClick(event);
});
}
@@ -139,11 +198,11 @@ export function createSelection({
// is looking at ever asks.
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
parts.rendering.refreshCoverageStyles();
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
// The active icon always shows and the previous one rejoins its cell.
// Restyle coverage after the view pass sets grouping. Its coverage
// neighbours join the working set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
@@ -218,6 +277,7 @@ export function createSelection({
return {
getActiveRecord,
bindCctvWorldClickGesture,
countClickCard,
setActiveCamera,
deactivateActiveCamera,
cctvEmptyClickDeselects,
+163
View File
@@ -1,6 +1,10 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { createNavigation } from './navigation.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
@@ -52,3 +56,162 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
test('a count click preserves the provisional opening pick until the view settles', () => {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy: Math.PI / 3, aspectRatio: 1 }),
flyToBounds: (bounds) => flights.push(bounds),
},
canvas: { height: 600 },
});
try {
const cell = { west: 1, east: 2, south: 0, north: 0, low: 0, high: 0 };
const state = {
_enabled: true,
_viewer: viewer,
_openingCameraProvisional: true,
_activeCameraId: 'opening',
_counts: {
pickedCell: (point) => (point?.x === 14 && point.y === 26 ? cell : null),
},
};
const parts = {};
parts.navigation = createNavigation({ state, parts });
const selection = createSelection({
state,
parts,
services: { activation: {}, picking: {} },
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => {
assert.fail('a count click reached activation or deselection');
},
);
click({
screenPosition: { x: 14, y: 26 },
get drawHit() {
assert.fail('the camera underneath was picked');
},
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(flights.length, 1);
assert.equal(state._activeCameraId, 'opening');
assert.equal(state._openingCameraProvisional, true);
} finally {
unbind();
}
});
test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: {
hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null),
},
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
picking.registerPickOwner('cctv', (id) => id.startsWith('cam-'));
picking.registerPickOwner('flights', (id) => id === 'abc' || id === 'cam-2');
try {
for (const [x, topHit, expected] of [
[14, null, [0, 1]],
[20, { set: 'flights', id: 'abc' }, [0, 2]],
[20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]],
[20, null, [2, 2]],
[20, { set: 'flights', id: 'cam-2' }, [2, 3]],
]) {
click({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterPickOwner('cctv');
picking.unregisterPickOwner('flights');
}
});
test('a count click is the card on top for every layer, unless the count yields', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: (p) => (p?.x === 20 ? { key: 'g' } : null) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (topHit = null, x = 20, durationMs = 20) => ({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id === 'abc');
try {
const aircraftFirst = event();
assert.equal(picking.isUnderOtherCard(aircraftFirst), true);
assert.deepEqual(picking.clickCard(aircraftFirst), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(aircraftFirst);
assert.deepEqual([zooms, clicks], [1, 0]);
const cctvFirst = event();
click(cctvFirst);
assert.equal(picking.isUnderOtherCard(cctvFirst), true);
assert.deepEqual([zooms, clicks], [2, 0]);
for (const [e, claimed, expected] of [
[event({ set: 'flights', id: 'abc' }), false, [2, 1]],
[event({ set: 'cctv-icons', id: 'cam-2' }), true, [3, 1]],
[event(null, 20, 1000), false, [3, 1]],
[event(null, 60), false, [3, 2]],
[{ ...event(), overlay: true }, false, [3, 3]],
]) {
assert.equal(picking.isUnderOtherCard(e), claimed);
click(e);
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
+11 -3
View File
@@ -15,6 +15,7 @@ export function createState({ services }) {
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._counts = null;
layerState._records = [];
@@ -95,10 +96,14 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// The view records plus the best-ranked camera of each visible cell.
layerState._pickerRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
// The active camera's coverage neighbours, including grouped ones. A
// grouping change in this cohort requires a coverage refresh.
layerState._coverageCohort = null;
// The cohort minus grouped cameras, last drawn by refreshCoverageStyles.
// These belong to the geometry working set even off screen.
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
@@ -113,6 +118,9 @@ export function createState({ services }) {
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
// Reruns the view pass when terrain loads or the surface changes.
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
// A motion pass changed the shown set and the settle pass has not yet told
// subscribers; the camera pose the last view pass ran at.
+12
View File
@@ -1,3 +1,4 @@
import { createCountMarkers } from './countMarkers.js';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
@@ -90,6 +91,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
* @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode.
* @param {boolean} [options.showProjection=false] Projection visibility.
* @param {Map<string, Object>} [options.healthById] Health rows by camera id.
* @param {Function} [options.registerPaintLane] Receives the count painter.
* @returns {void}
*/
@@ -102,6 +104,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
showProjection = false,
healthById = new Map(),
openingCameraProvisional = false,
registerPaintLane,
} = {}) {
layerState._viewer = viewer;
layerState._records = Array.isArray(records) ? records : [];
@@ -123,12 +126,20 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._showProjection = !!showProjection;
layerState._healthById = healthById;
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
layerState._counts?.dispose();
layerState._counts = createCountMarkers(
registerPaintLane,
'cctv:test:counts',
parts.rendering.refreshHorizonCulling,
);
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
@@ -148,6 +159,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
counts: layerState._counts,
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
+44 -1
View File
@@ -21,6 +21,7 @@ import {
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
import { locateOnTrack } from '../../data/locate.js';
export function createQueries({
flightState,
@@ -545,7 +546,9 @@ export function createQueries({
object._labelCallsign = callsign;
object._labelRegistration = registration;
}
const altitude = info?.altitude;
// A grounded contact shows no flight level: its sticky `altitude` may
// still be the approach height.
const altitude = info?.onGround ? 0 : info?.altitude;
if (object._altitude !== altitude) {
object._altitude = altitude;
object.metric = formatFlightLevel(altitude); // altitude is metres
@@ -778,6 +781,46 @@ export function createQueries({
return result;
},
/**
* The track reference of a loaded aircraft, so it can be looked up again
* once it has left the feed (see locate).
* @param {string} icao24
* @returns {string|null}
*/
referenceOf(icao24) {
const id = String(icao24 ?? '')
.trim()
.toLowerCase();
if (!id) return null;
return flightState.records.data.get(id)?.sourceReference ?? id;
},
/**
* Where an aircraft is at the layer's time (the world clock's while the
* layer follows it, else now), from its own track: for an aircraft that
* has left the feed, so it can be found again.
* @param {string} icao24
* @param {{reference?: string, signal?: AbortSignal}} [options]
* @returns {Promise<{status: 'found', lat: number, lon: number,
* altitudeM: ?number, observedAtMs: number}|{status: 'none'}>}
*/
locate(icao24, { reference, signal } = {}) {
const atMs = followsClock(flightState) ? flightState.now() : undefined;
return locateOnTrack(
flightState.feed._source,
reference ??
flightState.records.data.get(
String(icao24 ?? '')
.trim()
.toLowerCase(),
)?.sourceReference ??
String(icao24 ?? '')
.trim()
.toLowerCase(),
{ atMs, signal },
);
},
/**
* Ask for an aircraft's scheduled route (origin and destination airports),
* as tracking does; it lands on the record when the lookup answers.
+14 -3
View File
@@ -232,7 +232,13 @@ export class FlightRecords {
surfaceM = geoidSurfaceLastResortM({
geoAltM: geo_alt,
baroAltM: baro_alt,
priorRenderM: prevMeta?.renderAltitudeM,
// Only a height held ON THE GROUND counts as prior: straight after a
// landing the previous render height is the approach height, and
// holding it left the plane hanging there until a cell warmed —
// forever for a contact far from the viewer, whose cell is never
// queued (HAL-1032).
priorRenderM:
prevMeta?.onGround === true ? prevMeta.renderAltitudeM : null,
geoidN,
});
}
@@ -266,10 +272,15 @@ export class FlightRecords {
let renderAltitudeM;
if (pickedAltM != null) {
renderAltitudeM = pickedAltM;
} else if (Number.isFinite(prevMeta?.renderAltitudeM)) {
} else if (
Number.isFinite(prevMeta?.renderAltitudeM) &&
(!onGround || prevMeta.onGround === true)
) {
renderAltitudeM = prevMeta.renderAltitudeM;
} else {
renderAltitudeM = alt;
// A grounded contact with nothing better sits at 0 m: `alt` is sticky,
// so after a landing it still holds the approach altitude.
renderAltitudeM = onGround ? 0 : alt;
}
// Field-test fix (WAKE01/RS46 class, 2026-07-06; widened round 3):
// floor a low airborne contact's render height at the local coarse
+40 -4
View File
@@ -112,16 +112,52 @@ test('civil record owners isolate state and preserve partial, missing-poll and l
);
});
test('ground transitions preserve last render height while a surface cell is cold', () => {
test('a landing with a cold surface cell sits on the geoid, not at its approach height', () => {
const store = records();
store.geoidReady = true;
store.receive(observation({ ellipsoidAltitudeM: 1040 }), view());
// Every grounded poll, not just the first: a contact far from the viewer
// never has its cell warmed (HAL-1032).
for (let poll = 0; poll < 3; poll += 1) {
const next = store.receive(
observation({
onGround: true,
baroAltitudeM: null,
positionTimeMs: 1700000010000 + poll * 10000,
}),
view(),
);
assert.equal(next.groundFlipped, poll === 0);
assert.equal(next.meta.renderAltitudeM, 40);
assert.equal(next.meta.wasAirborne, true);
}
});
test('a landing before the geoid loads sits at 0 m, not at its approach height', () => {
const store = records();
store.receive(observation({ baroAltitudeM: 1539 }), view());
const next = store.receive(
observation({ onGround: true, baroAltitudeM: null }),
view(),
);
assert.equal(next.groundFlipped, true);
assert.equal(next.meta.renderAltitudeM, 1040);
assert.equal(next.meta.wasAirborne, true);
assert.equal(next.meta.renderAltitudeM, 0);
});
test('a parked contact whose surface cell goes cold holds its ground height', () => {
let floor = 312;
const store = new FlightRecords({
geoidHeight: () => 40,
cachedGroundFloor: () => floor,
floorAltitudeM: (altitude) => altitude,
approxDistanceKm: () => 0,
fleetModels: () => null,
});
store.geoidReady = true;
const grounded = () =>
store.receive(observation({ onGround: true, baroAltitudeM: null }), view());
assert.equal(grounded().meta.renderAltitudeM, 312);
floor = null;
assert.equal(grounded().meta.renderAltitudeM, 312);
});
test('complete snapshots age out vanished aircraft and retain position-less ones unless landed', () => {
+9 -3
View File
@@ -900,13 +900,19 @@ export function createTracking({
// the ICAO hex, so a callsign-less enriched contact heads its readout with
// the tail number rather than raw hex.
const cs = parts.queries._contactLabel(icao24, info);
const altFt = Math.round((info.altitude || 0) * 3.28084);
const altFt = info.onGround
? null
: Math.round((info.altitude || 0) * 3.28084);
// Flight levels are an aviation code; feet and knots read in the active
// language ("0 фт · 1 уз").
const quantity = (value, unit) =>
`${formatNumber(value, { useGrouping: false })} ${unitLabel(unit)}`;
const fl =
altFt >= 18000 ? `FL${Math.round(altFt / 100)}` : quantity(altFt, 'ft');
altFt == null
? t('On the ground')
: altFt >= 18000
? `FL${Math.round(altFt / 100)}`
: quantity(altFt, 'ft');
const spd = info.velocity
? quantity(Math.round(info.velocity * 1.944), 'kts')
: '';
@@ -1164,7 +1170,7 @@ export function createTracking({
// viewFrom — behind + above, distance scaled to altitude — for a readable
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
const followRange = Math.min(
Math.max((info.altitude || 1500) * 1.1 + 2500, 3000),
Math.max((info.onGround ? 0 : info.altitude || 1500) * 1.1 + 2500, 3000),
30000,
);
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
+50 -4
View File
@@ -19,6 +19,7 @@ import {
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
import { locateOnTrack } from '../../data/locate.js';
export function createQueries({
flightState,
@@ -193,9 +194,12 @@ export function createQueries({
lon: num(info?.rawLon),
// altitudeFt is the sticky barometric/MSL aviation field — converted to
// meters here for shape parity with the flights layer.
altitudeM: Number.isFinite(info?.altitudeFt)
? info.altitudeFt * 0.3048
: null,
// A grounded contact reports only an altitude it gave on the ground.
altitudeM: info?.onGround
? (info.groundAltitudeM ?? null)
: Number.isFinite(info?.altitudeFt)
? info.altitudeFt * 0.3048
: null,
speedMps: num(info?.speedMps),
heading: num(info?.track),
verticalRateMps: num(info?.verticalRateMps),
@@ -509,7 +513,9 @@ export function createQueries({
// TR-3B, not the airframe underneath it.
const klass = tr3bTypeLabel(icao24, info?.type || 'MIL');
if (object.klass !== klass) object.klass = klass;
const altitudeFt = info?.altitudeFt ?? 0;
// A grounded contact shows no flight level, like the civil layer; its
// sticky altitudeFt may still be the approach height.
const altitudeFt = info?.onGround ? 0 : (info?.altitudeFt ?? 0);
if (object._altitudeFt !== altitudeFt) {
object._altitudeFt = altitudeFt;
// military metadata stores altitudeFt (feet); the helper takes metres
@@ -651,6 +657,46 @@ export function createQueries({
return result;
},
/**
* The track reference of a loaded aircraft, so it can be looked up again
* once it has left the feed (see locate).
* @param {string} icao24
* @returns {string|null}
*/
referenceOf(icao24) {
const id = String(icao24 ?? '')
.trim()
.toLowerCase();
if (!id) return null;
return flightState.records.data.get(id)?.sourceReference ?? id;
},
/**
* Where an aircraft is at the layer's time (the world clock's while the
* layer follows it, else now), from its own track: for an aircraft that
* has left the feed, so it can be found again.
* @param {string} icao24
* @param {{reference?: string, signal?: AbortSignal}} [options]
* @returns {Promise<{status: 'found', lat: number, lon: number,
* altitudeM: ?number, observedAtMs: number}|{status: 'none'}>}
*/
locate(icao24, { reference, signal } = {}) {
const atMs = followsClock(flightState) ? flightState.now() : undefined;
return locateOnTrack(
flightState.feed._source,
reference ??
flightState.records.data.get(
String(icao24 ?? '')
.trim()
.toLowerCase(),
)?.sourceReference ??
String(icao24 ?? '')
.trim()
.toLowerCase(),
{ atMs, signal },
);
},
/**
* Start camera-tracking an aircraft by ICAO hex identifier.
* @param {string} icao24 - ICAO hex identifier of the aircraft.
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more