mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 08:42:21 +00:00
Merge pull request #1760 from bilawalsidhu/render/renderer-seam
Renderer ports: layers draw, pick and move the camera through a renderer contract
This commit is contained in:
1119 files changed
+149863
-45582
No files matched your search
@@ -106,6 +106,16 @@ jobs:
|
||||
- name: Street Level gate with Mapillary fixtures
|
||||
run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173
|
||||
|
||||
- name: The whole application on the stub renderer, with no Cesium loaded
|
||||
run: |
|
||||
mkdir -p qa-artifacts
|
||||
npm run qa:stub-boot -- --json qa-artifacts/stub-boot.json
|
||||
|
||||
- name: The renderer contract's logic checks on Cesium, headless
|
||||
run: |
|
||||
mkdir -p qa-artifacts
|
||||
npm run qa:conformance -- --json qa-artifacts/conformance.json
|
||||
|
||||
- name: Preview server log
|
||||
if: failure()
|
||||
run: cat preview.log
|
||||
|
||||
@@ -9,6 +9,8 @@ coverage
|
||||
pinokio/ENVIRONMENT
|
||||
pinokio/.installed
|
||||
src/data/local_data/
|
||||
# Written by scripts/record-camera-goldens.mjs and compared byte for byte.
|
||||
src/render/conformance/goldens/
|
||||
*.geojson
|
||||
*.geojsonl
|
||||
|
||||
|
||||
+114
-4
@@ -2,9 +2,120 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- A double-click on the map no longer follows or zooms to what is under
|
||||
it. The globe's own double-click did that for some layers' markers and
|
||||
shapes (earthquakes, cyclones, air quality, news, cables, places and
|
||||
others); following something is a click, as for aircraft and ships. The
|
||||
Cockpit's double-click and a drawing's finishing double-click are
|
||||
unchanged (samehkhamis).
|
||||
- Aircraft no longer jump ahead or back, and their trails no longer kink,
|
||||
when the feed is late. The civil and military layers draw as far behind
|
||||
real time as their feed is late (the 90th percentile of recent report
|
||||
lags plus 5 s, at least 30 s civil and 15 s military, at most five
|
||||
minutes), so an aircraft is placed between two real reports rather than
|
||||
dead reckoned past them; the delay changes slowly, and the icons, the
|
||||
renderer's live clock, labels, the HUD, detection, the tracked camera and
|
||||
the trail all read the same one. Between two reports an aircraft flies
|
||||
one smooth curve that leaves each report along its track, sent to the
|
||||
renderer as `arc` segments; its trail is its reports joined along that
|
||||
same curve, so the icon always sits on it. A late report a coasting
|
||||
aircraft missed is eased onto, at most 30% faster than it flies; past
|
||||
its newest report an aircraft coasts straight on (samehkhamis).
|
||||
- The Display panel has a Sky group on a renderer with a sky to set: the
|
||||
atmosphere, day and night (sun lighting by scene time), the sun, the
|
||||
moon, the stars and the Milky Way's brightness. The choice is kept for the
|
||||
next visit; what is not set stays as the renderer draws it (samehkhamis).
|
||||
- The renderer contract no longer ties a renderer's look to the default
|
||||
renderer's: `globe.sky` switches parts of the sky on and off, while how
|
||||
the sky, atmosphere, haze, lighting, tone mapping and exposure look is
|
||||
the renderer's own. `globe.weather`'s `clouds` is the fraction of the sky
|
||||
covered, as observed; clouds are placed by scene time and the wind and
|
||||
shade the ground under them where the sun lights it. New conformance
|
||||
check `globe.weather.sceneTime` (samehkhamis).
|
||||
- Selecting an aircraft, a vessel, a train or a transit vehicle no longer
|
||||
makes it bigger: it keeps the size and form it had and changes colour (a
|
||||
transit vehicle only widens its dark ring). A click on an aircraft, a
|
||||
vessel or a train no longer moves the camera to a new framing either: the
|
||||
camera keeps its distance and viewing angle, the contact slides to the
|
||||
centre over one second, and the camera then follows it from there (a
|
||||
vessel, which is never followed, is left centred). A
|
||||
follow target asks for this glide with `transitionS` (renderer contract,
|
||||
conformance check `camera.follow.transition`); without it a follow frames
|
||||
at once, as before. An aircraft chosen by voice, search or a shared link
|
||||
is still framed as before (samehkhamis).
|
||||
- The renderer contract's `models` capability draws the procedural fleet
|
||||
models: a model item can carry its glTF bytes (`gltf`, drawn without a
|
||||
fetch), a per-axis stretch (`axisScale`), a colour for its tinted parts
|
||||
(`maskColor`) and a cut below its origin (`clip: 'belowOrigin'`, a hull at
|
||||
the waterline). Aircraft, military, local ADS-B, vessel, transit and rail
|
||||
models are drawn through it (samehkhamis).
|
||||
- A tracked aircraft's trail no longer draws a straight line from its track
|
||||
history across a landing or take-off that was not seen: a parked or
|
||||
taxiing aircraft whose history ends in the air (often its previous flight)
|
||||
starts its trail on the ground (samehkhamis).
|
||||
- Aircraft from adsb.lol that report no ground track (parked or taxiing
|
||||
slowly) now face their reported true heading instead of north, so parked
|
||||
models line up with their gates (samehkhamis).
|
||||
- A renderer can draw weather: the `weather` capability adds `globe.weather`,
|
||||
with clouds, fog, haze, rain and snow (each 0 to 1) and the wind they drift
|
||||
on. `./render/weather` and `./weather/effects` export the shared rules and
|
||||
the strengths of a weather observation. The Cesium renderer does not draw
|
||||
weather (samehkhamis).
|
||||
- Groups of toggles, sliders and notes can be added to the Display panel
|
||||
under Effects, with `publishDisplayGroup` from `./ui/display/groups`
|
||||
(samehkhamis).
|
||||
- The globe opens at planet level, the whole Earth in view, instead of
|
||||
flying in to Austin. A shared link still flies from
|
||||
there to its view. The `startView` option of `createApplicationControls`
|
||||
starts it somewhere else, a city for instance (longitude, latitude and
|
||||
height, and heading and pitch in degrees) (samehkhamis).
|
||||
- An application's own tool can take the pointer as Draw does, and its click
|
||||
handlers can yield while a tool holds it, as the layers' do (`pointer` from
|
||||
`createApplicationTools`) (samehkhamis, #1641).
|
||||
- `gods-eye-view/annotations` no longer reaches Cesium: the world annotation
|
||||
renderer draws its areas, building columns, routes, arrows, rings and
|
||||
markers through the renderer's draw port (the Cesium renderer now drapes
|
||||
arrows, draws clamped rings by camera height and pulses shape alpha), and
|
||||
samples a building's ground through the height service. A click on a
|
||||
world mark now hits its draw set (`meta: { annotation: id }`) rather than
|
||||
an entity. A viewer with no renderer bound needs
|
||||
`gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis).
|
||||
- `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog`
|
||||
no longer reach Cesium: the weather shells and the wind layer's colour
|
||||
shell and flow draw through the renderer's `draw.field` (`rasterShell` and
|
||||
`windStreamlines`, which the Cesium renderer now draws), and the wind
|
||||
relief is the globe port's `hillshade` surface shading. The flow animates
|
||||
as before, and still falls back to the canvas where the renderer refuses
|
||||
it. A viewer with no renderer bound needs
|
||||
`gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis).
|
||||
- `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its
|
||||
pointer events from the renderer's input port and its picks from the query
|
||||
port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and
|
||||
`pickAt`'s result, are the renderer contract's `Hit`; positions are plain
|
||||
`{ x, y }`; `HANDLER_EVENT_TYPES` is gone. Cesium's own picks stay on
|
||||
`event.native` (and `event.pick` and `event.pickWindow`). A viewer with no
|
||||
renderer bound needs `gods-eye-view/render/cesium/unbound`
|
||||
loaded once first (samehkhamis).
|
||||
- `gods-eye-view/application/operations` no longer reaches Cesium: ground
|
||||
snapping and mesh floor sampling ask the renderer's globe, camera and query
|
||||
ports, and see through the caller's draw sets by id (the raw
|
||||
`excludeObjects` option and exclusion callbacks are gone). A viewer with no
|
||||
renderer bound needs `gods-eye-view/render/cesium/unbound`
|
||||
loaded once first, or location framing throws and snaps answer nothing
|
||||
(samehkhamis).
|
||||
- `gods-eye-view/layers/traffic` (and `gods-eye-view/application/sources`,
|
||||
which reaches it) no longer reaches Cesium: the layer keys cached road
|
||||
heights by the globe port's `surfaceVersion()` and waits on
|
||||
`isSettled('surface')`. Heat-lines are always asked for draped; a renderer
|
||||
that cannot drape draws them over the surface instead of the layer
|
||||
dropping them. A viewer with no renderer bound needs
|
||||
`gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis).
|
||||
- Where the Cesium renderer cannot drape (a WebGL context without depth
|
||||
textures), every draped line now draws over the surface, as the renderer
|
||||
contract asks: along the surface's curve between its positions, in its
|
||||
colour where the surface hides it, hidden past the horizon. Segment colours
|
||||
are dropped (it draws in its style colour) and it runs from its first shown
|
||||
segment to its last (samehkhamis).
|
||||
|
||||
## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language
|
||||
|
||||
@@ -788,7 +899,7 @@
|
||||
|
||||
- Stop one retired bikeshare feed from reporting the whole layer as failed.
|
||||
City feeds are fetched independently, but failure was recorded in a single
|
||||
flag that only a successful *activation* cleared — and an already-loaded city
|
||||
flag that only a successful _activation_ cleared — and an already-loaded city
|
||||
never activates again. A dead feed re-entering camera range therefore latched
|
||||
LOAD FAILED permanently over a map still drawing every other city's stations.
|
||||
Failure is now tracked per city: a city that fails beside others still
|
||||
@@ -1064,7 +1175,7 @@
|
||||
photo a click opens, and the cones, by each photo's projection and upload
|
||||
date. KartaView's SINCE is the upload date (all its server can filter by);
|
||||
a note under the slider says so while KartaView is lit (`sinceBasis:
|
||||
'upload'` in the provider contract).
|
||||
'upload'` in the provider contract).
|
||||
Mapillary's line coverage and sequence cones are now shared by both
|
||||
(`lineCoverage.js`, `sequenceCones.js`).
|
||||
|
||||
@@ -1642,6 +1753,7 @@
|
||||
Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347).
|
||||
|
||||
Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351).
|
||||
|
||||
- New Fire Perimeters layer (Events group): live NIFC WFIGS interagency
|
||||
wildfire incident perimeters as ground-clamped polygons with a
|
||||
containment-colored fire line, refreshed every 5 minutes from the public
|
||||
@@ -1918,7 +2030,6 @@ of current runtime behavior, see [`docs/CURRENT-STATE.md`](docs/CURRENT-STATE.md
|
||||
|
||||
### Other changes
|
||||
|
||||
|
||||
- Add ECMWF IFS model selection to Wind (#464, thanks @beneduzi), with model-scoped forecast-step caches, cancellation of replaced requests, and separate issue/valid timestamps.
|
||||
|
||||
- Add bounded Director feature actions with accessible controls, explicit camera/layer admission and cancellation; restore pack geometry on same-shot seek. Preserve existing scenes and content attribution.
|
||||
@@ -2727,4 +2838,3 @@ represent previously published GitHub Releases.
|
||||
## [0.1.0] — 2026-02-09
|
||||
|
||||
- Initial project version.
|
||||
|
||||
@@ -139,6 +139,7 @@ The highest-leverage places to jump in:
|
||||
|
||||
- **Vue 3 + Pinia for the interface,** [CesiumJS](https://cesium.com/platform/cesiumjs/) for the globe and [Vite](https://vitejs.dev/) to build. See [Building UI](#building-ui).
|
||||
- **Assembly lives in `src/app/`; standalone defaults live in `src/standalone/`.** UI controllers live in `src/ui/`, layer factories in `src/layers/`, portable sources in `src/sources/`, and application operations in `src/services/`. Existing `src/data/<layer>.js` entries retain compatibility; new code belongs with its focused owner.
|
||||
- **Reach the renderer through its contract** ([docs/RENDERER-CONTRACT.md](docs/RENDERER-CONTRACT.md#moving-code-onto-the-contract)): `findDraw`, `findCamera` and the other ports in `src/render/rendererOf.js`, not Cesium or the viewer's `scene`, `camera` or `entities`. Two ratchet tests hold this: only files on `src/render/cesiumAllowList.json` may import Cesium, and `src/render/viewerAccessAllowList.json` caps the viewer accesses each other file still makes. Neither list may grow; when you port code off them, shrink them (`node scripts/viewer-access-baseline.mjs` lowers the second).
|
||||
- Sources acquire records; renderers own Cesium resources. Import `gods-eye-view/layers/<family>/source` when only a source factory is needed. Common voice controls consume the session interface; protocol adapters own connection details.
|
||||
- **Secrets stay server-side.** Anything needing a private key goes through a local proxy under `server/providers/`. The browser only ever sees the Google Maps key (which you restrict) and ephemeral tokens.
|
||||
- `docs/CURRENT-STATE.md` is the authoritative runtime reference — read it first.
|
||||
|
||||
@@ -527,7 +527,7 @@ More reconstructions, interviews and press: [godseyeview.ai/press](https://godse
|
||||
How the globe handles live data:
|
||||
|
||||
- **World-stable icons.** Aircraft and ships point along their _true real-world heading_ at every camera angle — tracked or not, looking straight down or across the horizon — via per-frame screen-space course projection. No spinning, no viewport-locking.
|
||||
- **Smooth motion from choppy data.** Live feeds arrive every 15–30s; the globe renders one interval behind real time and interpolates between known fixes. Dead reckoning fills the gaps.
|
||||
- **Smooth motion from choppy data.** Live feeds arrive every 15–30s, often minutes late; the globe renders as far behind real time as the feed is late (at least one interval) and draws each aircraft along a smooth curve between its known fixes. Dead reckoning fills the gaps.
|
||||
- **Honest satellites.** SGP4 propagation with orbit rings that stay locked to their satellites via GMST realignment — no drift, no per-second flicker.
|
||||
- **Sits on the real ground.** Entity heights are aligned to work with Google 3D tiles, so aircraft park on aprons and cameras stand on street corners instead of floating.
|
||||
- **Caching and request budgets.** An OpenSky credit governor, a TomTom daily tile budget, and disk-cached TLEs reduce repeated requests. These controls do not replace provider quotas or billing controls.
|
||||
@@ -544,7 +544,7 @@ src/
|
||||
├── voice/ # OpenAI Realtime session + 30 voice tools
|
||||
├── layers/ # Layer components — weather, wind, cyclones, transit, ALPR, …
|
||||
├── data/ # One module per layer + orchestration + context store
|
||||
│ ├── iconOrientation.js # Screen-projected headings + horizon cull
|
||||
│ ├── iconOrientation.js # Horizon backdrop for labels (headings: screenRotation.js)
|
||||
│ └── local_data/ # Bundled datasets (per-folder provenance)
|
||||
└── scenes/ # Cinematic scene director
|
||||
```
|
||||
|
||||
@@ -62,6 +62,14 @@ layer's hexagon grid; the complete resolved dependency inventory remains in
|
||||
- Source: <https://github.com/101arrowz/fzstd>
|
||||
- License: MIT
|
||||
|
||||
## kdbush
|
||||
|
||||
- Package: `kdbush` 4.0.2 (the screen index that groups points drawn too
|
||||
close together into clusters)
|
||||
- Author: Copyright (c) 2018, Vladimir Agafonkin
|
||||
- Source: <https://github.com/mourner/kdbush>
|
||||
- License: ISC
|
||||
|
||||
## H3 (h3-js)
|
||||
|
||||
- Package: `h3-js` 4.4.0 (the GNSS Integrity layer's H3 hexagon cells)
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
- Reduce dead-reckoning work for flights already hidden behind the horizon.
|
||||
Hidden contacts update on a staggered one-in-13-ticks rotation (about once a
|
||||
second) while visible contacts and contacts with fleet models retain the full
|
||||
update path (Wilmer Alzate, #870).
|
||||
@@ -0,0 +1,114 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Renderer conformance</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
font:
|
||||
13px/1.4 system-ui,
|
||||
sans-serif;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
background: #0d1117;
|
||||
color: #e6edf3;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid #30363d;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
h1 {
|
||||
font-size: 15px;
|
||||
margin: 0 12px 0 0;
|
||||
}
|
||||
button,
|
||||
select {
|
||||
font: inherit;
|
||||
padding: 4px 10px;
|
||||
}
|
||||
#stage {
|
||||
width: 640px;
|
||||
height: 360px;
|
||||
position: fixed;
|
||||
left: -10000px;
|
||||
top: 0;
|
||||
}
|
||||
main {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
td,
|
||||
th {
|
||||
border-bottom: 1px solid #21262d;
|
||||
padding: 4px 8px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.pass {
|
||||
color: #3fb950;
|
||||
}
|
||||
.fail {
|
||||
color: #f85149;
|
||||
}
|
||||
.skip {
|
||||
color: #8b949e;
|
||||
}
|
||||
.views {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
figure {
|
||||
margin: 0;
|
||||
background: #161b22;
|
||||
border: 1px solid #30363d;
|
||||
padding: 6px;
|
||||
}
|
||||
figure img {
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
figure .row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: 4px;
|
||||
}
|
||||
figcaption {
|
||||
margin-top: 4px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Renderer conformance</h1>
|
||||
<label
|
||||
>Renderer
|
||||
<select id="renderer">
|
||||
<option value="cesium">cesium (scene renderer)</option>
|
||||
</select></label
|
||||
>
|
||||
<button id="logic">Run logic suite (stub)</button>
|
||||
<button id="logicCesium">Run logic suite (cesium)</button>
|
||||
<button id="check">Check scenes</button>
|
||||
<button id="record">Record references</button>
|
||||
<span id="status"></span>
|
||||
</header>
|
||||
<div id="stage"></div>
|
||||
<main>
|
||||
<section id="logicResults"></section>
|
||||
<section class="views" id="views"></section>
|
||||
</main>
|
||||
<script type="module" src="./main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* The conformance page: runs the logic suite in the browser, and draws the
|
||||
* reference scenes on a renderer to check them against the stored
|
||||
* references (or record new ones). Driven by hand or through the
|
||||
* chrome-devtools MCP; `window.conformance` exposes the same actions.
|
||||
*/
|
||||
import {
|
||||
DEFAULT_TOLERANCE,
|
||||
runConformance,
|
||||
} from '../../src/render/conformance/index.js';
|
||||
import {
|
||||
REFERENCE_SCENES,
|
||||
sceneSupport,
|
||||
} from '../../src/render/conformance/scenes.js';
|
||||
import {
|
||||
compareImages,
|
||||
drawScene,
|
||||
referenceName,
|
||||
} from '../../src/render/conformance/visual.js';
|
||||
import { createStubHarness } from '../../src/render/stub/harness.js';
|
||||
import { toEcef } from '../../src/render/stub/math.js';
|
||||
import { createCesiumSceneRenderer } from '../../src/render/cesium/sceneRenderer.js';
|
||||
import {
|
||||
CESIUM_CHECKS,
|
||||
createCesiumHarness,
|
||||
} from '../../src/render/cesium/harness.js';
|
||||
|
||||
const REFERENCES = '/src/render/conformance/goldens/visual/';
|
||||
const SAVE = '/__conformance/references/';
|
||||
const ctx = {
|
||||
toEcef,
|
||||
assets: {
|
||||
model: '/models/fleet/aircraft/c172.glb',
|
||||
// Not served: the model failure check loads it.
|
||||
missingModel: '/models/conformance-missing.glb',
|
||||
},
|
||||
};
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const status = (text) => ($('status').textContent = text);
|
||||
|
||||
const RENDERERS = {
|
||||
cesium: () => createCesiumSceneRenderer({ container: $('stage') }),
|
||||
};
|
||||
|
||||
const HARNESSES = {
|
||||
stub: () => [createStubHarness('stub (browser)'), {}],
|
||||
cesium: () => [
|
||||
createCesiumHarness({
|
||||
model: ctx.assets.model,
|
||||
missingModel: ctx.assets.missingModel,
|
||||
}),
|
||||
{ only: (id) => CESIUM_CHECKS.has(id) },
|
||||
],
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs the logic suite on `which`; `all` runs every check, listed or not;
|
||||
* `only` (check ids) runs just those of them.
|
||||
*/
|
||||
async function runLogic(which = 'stub', { all = false, only } = {}) {
|
||||
status(`running the logic suite on ${which}…`);
|
||||
const [harness, options] = HARNESSES[which]();
|
||||
const listed = all ? () => true : (options.only ?? (() => true));
|
||||
const report = await runConformance(harness, {
|
||||
only: (id) => listed(id) && (!only || only.includes(id)),
|
||||
});
|
||||
$('logicResults').innerHTML =
|
||||
`<p>${report.harness}: <b class="pass">${report.passed} passed</b>, <b class="fail">${report.failed} failed</b>, ${report.skipped} skipped</p>
|
||||
<table>${report.results
|
||||
.filter((r) => r.status !== 'pass')
|
||||
.map(
|
||||
(r) =>
|
||||
`<tr><td class="${r.status}">${r.status}</td><td>${r.id}</td><td>${escape(r.detail ?? '')}</td></tr>`,
|
||||
)
|
||||
.join('')}</table>`;
|
||||
status('');
|
||||
return {
|
||||
passed: report.passed,
|
||||
failed: report.failed,
|
||||
skipped: report.skipped,
|
||||
failures: report.results.filter((r) => r.status === 'fail'),
|
||||
skips: report.results.filter((r) => r.status === 'skip'),
|
||||
};
|
||||
}
|
||||
|
||||
const escape = (s) =>
|
||||
s.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]);
|
||||
|
||||
async function pixels(blob) {
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
|
||||
const g = canvas.getContext('2d');
|
||||
g.drawImage(bitmap, 0, 0);
|
||||
return g.getImageData(0, 0, bitmap.width, bitmap.height);
|
||||
}
|
||||
|
||||
// Object URLs shown for the current run, revoked when the next one starts.
|
||||
let objectUrls = [];
|
||||
function objectUrl(blob) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.push(url);
|
||||
return url;
|
||||
}
|
||||
|
||||
async function toUrl(imageData) {
|
||||
const canvas = new OffscreenCanvas(imageData.width, imageData.height);
|
||||
canvas.getContext('2d').putImageData(imageData, 0, 0);
|
||||
return objectUrl(await canvas.convertToBlob());
|
||||
}
|
||||
|
||||
/** The views the stored manifest lists, or none. */
|
||||
async function storedViews() {
|
||||
try {
|
||||
const res = await fetch(REFERENCES + 'manifest.json', {
|
||||
cache: 'no-store',
|
||||
});
|
||||
return res.ok ? ((await res.json()).views ?? []) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function reference(name) {
|
||||
const res = await fetch(REFERENCES + name, { cache: 'no-store' });
|
||||
return res.ok && res.headers.get('content-type')?.startsWith('image/')
|
||||
? res.blob()
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Draws every scene; records references or compares against them. */
|
||||
async function runScenes({ record = false, only } = {}) {
|
||||
const which = $('renderer').value;
|
||||
const renderer = await RENDERERS[which]();
|
||||
const results = [];
|
||||
$('views').innerHTML = '';
|
||||
for (const url of objectUrls) URL.revokeObjectURL(url);
|
||||
objectUrls = [];
|
||||
try {
|
||||
for (const scene of REFERENCE_SCENES) {
|
||||
if (only && !only.includes(scene.id)) continue;
|
||||
const unsupported = sceneSupport(scene, renderer, ctx);
|
||||
if (unsupported) {
|
||||
results.push({ scene: scene.id, status: 'skip', detail: unsupported });
|
||||
continue;
|
||||
}
|
||||
status(`${scene.id}…`);
|
||||
// A scene the renderer refuses fails alone; the others still draw.
|
||||
try {
|
||||
await drawScene(renderer, scene, ctx, async (view, capture, settle) => {
|
||||
const name = referenceName(scene.id, view.name);
|
||||
const figure = document.createElement('figure');
|
||||
$('views').append(figure);
|
||||
if (settle.state !== 'settled') {
|
||||
const detail = `${settle.state}: ${settle.blockers.join(', ')}`;
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: 'fail',
|
||||
detail,
|
||||
});
|
||||
figure.innerHTML = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: ${escape(detail)}</figcaption>`;
|
||||
return;
|
||||
}
|
||||
if (record) {
|
||||
const res = await fetch(SAVE + name, {
|
||||
method: 'PUT',
|
||||
body: capture,
|
||||
});
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: res.ok ? 'recorded' : 'fail',
|
||||
detail: res.ok ? undefined : `save ${res.status}`,
|
||||
});
|
||||
figure.innerHTML = `<img src="${objectUrl(capture)}"><figcaption>${name}: recorded</figcaption>`;
|
||||
return;
|
||||
}
|
||||
const refBlob = await reference(name);
|
||||
if (!refBlob) {
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: 'fail',
|
||||
detail: 'no reference',
|
||||
});
|
||||
figure.innerHTML = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: no reference</figcaption>`;
|
||||
return;
|
||||
}
|
||||
const [actual, expected] = await Promise.all([
|
||||
pixels(capture),
|
||||
pixels(refBlob),
|
||||
]);
|
||||
const diff = new Uint8ClampedArray(actual.data.length);
|
||||
const outcome = compareImages(actual, expected, { diff });
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: outcome.match ? 'pass' : 'fail',
|
||||
diffFraction: outcome.diffFraction,
|
||||
solidPixels: outcome.solidPixels,
|
||||
mismatchedPixels: outcome.mismatchedPixels,
|
||||
...(outcome.reason ? { detail: outcome.reason } : {}),
|
||||
});
|
||||
const diffUrl = outcome.reason
|
||||
? ''
|
||||
: await toUrl(new ImageData(diff, actual.width, actual.height));
|
||||
figure.innerHTML = `<div class="row"><img src="${objectUrl(capture)}" title="${which}"><img src="${objectUrl(refBlob)}" title="reference"><img src="${diffUrl}" title="difference"></div>
|
||||
<figcaption class="${outcome.match ? 'pass' : 'fail'}">${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}</figcaption>`;
|
||||
});
|
||||
} catch (error) {
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
status: 'fail',
|
||||
detail: String(error?.message ?? error),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (record) {
|
||||
// A partial recording keeps the other scenes' entries.
|
||||
const kept = only
|
||||
? (await storedViews()).filter(
|
||||
(view) => !only.some((id) => view.startsWith(`${id}-`)),
|
||||
)
|
||||
: [];
|
||||
const recorded = results
|
||||
.filter((r) => r.status === 'recorded')
|
||||
.map((r) => referenceName(r.scene, r.view));
|
||||
await fetch(SAVE + 'manifest.json', {
|
||||
method: 'PUT',
|
||||
body:
|
||||
JSON.stringify(
|
||||
{
|
||||
renderer: which,
|
||||
size: {
|
||||
width: renderer.canvas.width,
|
||||
height: renderer.canvas.height,
|
||||
},
|
||||
views: [...kept, ...recorded],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + '\n',
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
renderer.destroy();
|
||||
status('');
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
$('logic').onclick = () => runLogic('stub');
|
||||
$('logicCesium').onclick = () => runLogic('cesium');
|
||||
$('check').onclick = () => runScenes();
|
||||
$('record').onclick = () => runScenes({ record: true });
|
||||
window.conformance = { runLogic, runScenes };
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* The whole application on the stub renderer (`src/render/stub`), with only
|
||||
* the contract's required members: the proof that the application runs on
|
||||
* those members alone, and needs no code that knows which renderer it is.
|
||||
* `scripts/qa-stub-boot.mjs` serves the application's page with this entry
|
||||
* in place of `src/main.js`, boots it headless, runs its data layers and
|
||||
* checks that no Cesium module loads.
|
||||
*
|
||||
* The stub runs nothing on its own: each animation frame here ticks it once.
|
||||
* `window.__stubBoot` exposes the application and the renderer it made.
|
||||
*/
|
||||
import { createStandaloneApplication } from '../../src/standalone/application.js';
|
||||
import { createStubRendererPlugin } from '../../src/render/stub/index.js';
|
||||
|
||||
const renderers = [];
|
||||
|
||||
/** Tick a renderer once per animation frame until it is destroyed. */
|
||||
function drive(renderer) {
|
||||
const step = () => {
|
||||
if (!renderers.includes(renderer)) return;
|
||||
renderer.testing.tick();
|
||||
requestAnimationFrame(step);
|
||||
};
|
||||
requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
// The required tier, no capability at all; `?capabilities=all` gives the
|
||||
// stub every capability, to see what the layers draw with them.
|
||||
const allCapabilities =
|
||||
new URLSearchParams(location.search).get('capabilities') === 'all';
|
||||
|
||||
const plugin = createStubRendererPlugin(
|
||||
allCapabilities ? {} : { capabilities: [] },
|
||||
(renderer) => {
|
||||
renderers.push(renderer);
|
||||
const destroy = renderer.destroy.bind(renderer);
|
||||
renderer.destroy = () => {
|
||||
renderers.splice(renderers.indexOf(renderer), 1);
|
||||
destroy();
|
||||
};
|
||||
drive(renderer);
|
||||
},
|
||||
);
|
||||
|
||||
const application = createStandaloneApplication({
|
||||
renderer: plugin,
|
||||
allowQaRegistration: true,
|
||||
});
|
||||
|
||||
window.__stubBoot = {
|
||||
application,
|
||||
renderers,
|
||||
started: application.start().then(
|
||||
() => ({ ok: true }),
|
||||
(error) => {
|
||||
console.error('Stub application failed to start:', error);
|
||||
return { ok: false, error: String(error?.stack || error) };
|
||||
},
|
||||
),
|
||||
};
|
||||
+118
-1
@@ -43,7 +43,11 @@ await app.destroy();
|
||||
```
|
||||
|
||||
The example's containers and three remaining constructors are supplied by the
|
||||
consumer. The viewer helper preserves the standalone viewer's render settings;
|
||||
caller. The standalone scene also returns `trimStaleCommands()`, which drops
|
||||
the draw commands the Cesium scene keeps after a turned-off layer stops drawing;
|
||||
the application tools call it one frame after each layer disable. A scene
|
||||
without it keeps those commands, and so the layer's memory, until they are
|
||||
overwritten. The viewer helper preserves the standalone viewer's render settings;
|
||||
it neither selects map sources nor reads keys. Supply a visible credit container
|
||||
and retain all attribution required by the chosen sources. Cesium is external to
|
||||
this export: the consuming build must provide the same instance used elsewhere
|
||||
@@ -81,6 +85,119 @@ constructed component objects; the component instances themselves remain mutable
|
||||
`ready` means all constructors have returned. Background feed activity and the
|
||||
standalone share-restoration result keep their existing separate contracts.
|
||||
|
||||
## Pointer input
|
||||
|
||||
`gods-eye-view/input` exports `inputFor(viewer)`, the scene's one input
|
||||
dispatcher. Every layer and tool takes its pointer input from it, and so can
|
||||
the caller: one pointer handler per viewer, and a click picked once and
|
||||
handed to every subscriber.
|
||||
|
||||
```js
|
||||
import { inputFor } from 'gods-eye-view/input';
|
||||
|
||||
const input = inputFor(viewer);
|
||||
const off = input.onClick((event) => {
|
||||
if (event.ownerId === 'flights') showFlight(event.id);
|
||||
});
|
||||
// Later:
|
||||
off();
|
||||
```
|
||||
|
||||
`onClick` runs while no tool holds the pointer (the draw tool, the imagery
|
||||
box), so a vertex placed on an aircraft is not also a click on it. Its event
|
||||
reads lazily; a subscriber that reads nothing costs no pick:
|
||||
|
||||
| Member | What it is |
|
||||
| -------------------- | ------------------------------------------------------------------------- |
|
||||
| `screenPosition` | Where the user clicked, in CSS pixels; for DOM and overlay hit-tests |
|
||||
| `position` | Where that lands in the pick buffer (corrected under sensor styles) |
|
||||
| `gesture` | `{ travelPx, durationMs }` of the press, to tell a click from a drag |
|
||||
| `topHit` | The renderer's `Hit` on top at `position`, or `null` for the map itself |
|
||||
| `drawHit` | `topHit` when it is an item of a draw set, else `null` |
|
||||
| `hit` | `topHit`, or on a coarse pointer the contact under a surface pick |
|
||||
| `id`, `ownerId` | The hit's pick id and the layer that registered it, or `null` |
|
||||
| `meta` | The hit's own metadata, when it carries any |
|
||||
| `surface` | Whether the hit is the map itself |
|
||||
| `drill(limit)` | The draw-set `Hit`s under the click, shared by every subscriber |
|
||||
| `windowHit(w, h)` | `{ id, drawHit, surface }` of a pick over a `w`×`h` window |
|
||||
| `ground()` | The world position under the click, or `null` over the sky |
|
||||
| `native` | The renderer adapter's own `{ pick, pickWindow(w, h), drill(limit) }` |
|
||||
| `pick`, `pickWindow` | `native.pick` and `native.pickWindow`, for code bound to the engine picks |
|
||||
|
||||
A hit is the renderer contract's `Hit` (`src/render/contract/query.d.ts`).
|
||||
Something drawn outside the renderer's draw port is a `Hit` with `set: ''`,
|
||||
named by the adapter. Positions are plain `{ x, y }` objects. The dispatcher
|
||||
takes its pointer events from the renderer's input port and its picks from
|
||||
its query port, so a viewer with no renderer bound needs the Cesium adapter's
|
||||
factories loaded (`gods-eye-view/render/cesium/unbound`), or `inputFor` throws.
|
||||
|
||||
`onPointer(type, fn, { lease })` subscribes to `down`, `move`, `up`, `click`
|
||||
or `dblclick`; with a lease it runs only while that lease is current. A tool
|
||||
takes its lease with `claimPointer(ownerId, { onLost })` from the same export
|
||||
(and gives it back with `releasePointer(lease)`), which also keeps every
|
||||
ambient subscriber off its clicks; `isPointerFree()` and `pointerOwner()`
|
||||
report who holds it. The newest claim takes over, as on the renderer's input
|
||||
port: the tool holding the pointer has its `onLost` called once and turns
|
||||
itself off, and its late release frees nothing. `suspendCamera(reason)` and `suppressStockClicks()` return their
|
||||
own release: camera input and the viewer's stock select and double-click-track
|
||||
come back when the last hold is released, so two holders cannot undo each
|
||||
other. The renderer's input port owns the camera controller's `enableInputs`: a direct
|
||||
write (Cesium's camera flights make one when they start and end) is kept, but
|
||||
reads true only while no hold is out. A caller-supplied `createScene` that creates its own viewer registers
|
||||
`defer(() => inputFor(viewer).destroy())` right after it; the standalone scene
|
||||
does this and returns the dispatcher as `scene.input`.
|
||||
|
||||
## Height queries
|
||||
|
||||
`gods-eye-view/queries/heights` exports `heightsOf(viewer)`, the one place
|
||||
height queries go. Layers, tools and the camera ask it instead of asking the
|
||||
renderer's query port (`sampleHeight`, `sampleHeightNow`, `clampToSurface`)
|
||||
or the scene themselves, so how the renderer answers heights can change
|
||||
without touching them. Pass the viewer the renderer is bound to, not its
|
||||
scene. A viewer with no renderer bound is answered by the Cesium adapter's
|
||||
fallback once the caller has loaded `gods-eye-view/render/cesium/unbound`;
|
||||
until then, every query answers `null`.
|
||||
|
||||
```js
|
||||
import { heightsOf } from 'gods-eye-view/queries/heights';
|
||||
|
||||
const heights = heightsOf(viewer);
|
||||
const ground = heights.now({ lon, lat }, { exclude: [ownSetId] });
|
||||
if (ground !== null) place(ground);
|
||||
```
|
||||
|
||||
| Member | What it answers |
|
||||
| ----------------------------- | ------------------------------------------------------------------------- |
|
||||
| `now(point, opts)` | Height in metres from what is loaded, or `null` |
|
||||
| `clampNow(position, opts)` | The ECEF `{ x, y, z }` moved onto the drawn surface, or `null` |
|
||||
| `batch(points, opts)` | A promise of heights once the most detailed tiles stream; `null` per miss |
|
||||
| `clampBatch(positions, opts)` | A promise of clamped `{ x, y, z }` copies; `null` per miss |
|
||||
| `supported()` | `{ surface, clamp }`: whether the drawn surface can be queried at all |
|
||||
|
||||
A point is `{ lon, lat }` in degrees or `{ longitude, latitude }` in radians.
|
||||
`against: 'surface'` (the default) reads what is drawn, 3D tiles and globe;
|
||||
`against: 'terrain'` reads the loaded terrain alone; `against: 'tiles'` the
|
||||
tiles without the globe. Both `surface` and `tiles` include draw sets drawn
|
||||
with `includeInHeightQueries`; `clampNow` and `clampBatch` always clamp to
|
||||
the surface. `exclude` lists draw set ids to see through, of those drawn with
|
||||
`includeInHeightQueries`; every other draw set is seen through already. Every
|
||||
miss is `null`, and every caller treats it as one; `batch` and `clampBatch`
|
||||
reject when the query itself fails. Without depth-texture support the Cesium
|
||||
renderer answers no `surface` or `tiles` height; `now` still answers
|
||||
`terrain` from the loaded tiles, while `batch` misses terrain too.
|
||||
|
||||
## Cesium internals
|
||||
|
||||
The app reaches private Cesium fields only through
|
||||
`src/render/cesium/internals.js`, one named helper per field (the main and
|
||||
offscreen pick views, a billboard's collection, a cluster's point collection,
|
||||
the widget's render-loop latch, the WebGL context and whether a camera flight
|
||||
is under way). `internals.test.mjs` fails when the installed Cesium stops
|
||||
declaring one of them, and when a private field is reached anywhere else.
|
||||
Imagery that rations its tile requests states the policy as a hook with
|
||||
`withTileRequestHook(provider, { requestImage, credit })` from
|
||||
`src/render/cesium/tileRequests.js`, which leaves the provider untouched.
|
||||
|
||||
## Standalone wiring
|
||||
|
||||
`src/main.js` reads the existing browser configuration and starts
|
||||
|
||||
+25
-1
@@ -33,12 +33,13 @@ export inventory. Use declared exports rather than reaching into internal files.
|
||||
| `src/layers/<family>/` | Source acquisition, records and Cesium resources with explicit controller/renderer owners |
|
||||
| `src/sources/` | Portable protocols and source contracts; request state belongs to each factory instance |
|
||||
| `src/services/` | Supplied application operations; scene construction owns caches and cancellation |
|
||||
| `src/render/` | The renderer contract, the stub renderer, the conformance suite and Cesium renderer pieces |
|
||||
| `src/voice/` | Portable action schemas/session, common controls, action execution and separate protocol adapters |
|
||||
| `server/providers/` | Node route factories, process-scoped provider caches and shutdown cleanup |
|
||||
| `server/standalone/` | Environment, local settings writes and server composition |
|
||||
|
||||
See [application construction](APPLICATION.md) and the
|
||||
[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces.
|
||||
[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces, and the [renderer contract](RENDERER-CONTRACT.md) for what a renderer provides.
|
||||
|
||||
## Import direction gates
|
||||
|
||||
@@ -470,6 +471,13 @@ release listeners; pending action feedback is limited to its current owner.
|
||||
rendering, HUD and share operations. `src/standalone/controls.js` provides the running
|
||||
application's instances. The shell
|
||||
imports no standalone bootstrap or concrete live layer implementation.
|
||||
The shell reaches the renderer through its ports alone, and loads no
|
||||
renderer: given a viewer with no renderer bound, load
|
||||
`./render/cesium/unbound` once first, which also provides the celestial
|
||||
ring's precise ICRF rotation (`src/sky/icrf.js`; until then the ring uses
|
||||
the TEME approximation). Whether Cockpit's aircraft is an entity of the
|
||||
viewer's own is the `viewerDrawsEntity` service's to say; the application
|
||||
scene supplies it.
|
||||
Panel layout, position/drag, notices, recording and deferred UI work have separate
|
||||
owners with synchronous cleanup. Existing scene, share and HUD engines retain
|
||||
their entry points. `ui/styles` loads the ordered stylesheet entry; component
|
||||
@@ -507,6 +515,15 @@ perform no network requests and discover no additional modules.
|
||||
standard sources and their setup/fallback policy. The standalone facade wires
|
||||
these to the application's render governor.
|
||||
|
||||
`maps/imagery`, `maps/terrain` and `maps/3d` are the Cesium renderer's
|
||||
(`src/render/cesium/`). `maps/controller` and `maps/defaults` are
|
||||
Cesium-free: they make their scene changes and build their providers
|
||||
through the map engine the renderer provides as it loads
|
||||
(`src/maps/engine.js`). The application's renderer provides it; with a
|
||||
viewer with no renderer bound, load `./render/cesium/unbound` once first, or pass the
|
||||
engine as the controller's and `createDefaultMapSources`' `engine` option.
|
||||
Without one, constructing a controller throws, naming that export.
|
||||
|
||||
A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`.
|
||||
Each source has a user-facing `descriptor`, availability/reason, and either an
|
||||
`imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`.
|
||||
@@ -571,6 +588,13 @@ separate from standalone setup. Scene construction returns these operations; the
|
||||
catalog and controls use the same surface owner. Layers still own their individual
|
||||
ground-snap caches and model resources.
|
||||
|
||||
The entry is Cesium-free: ground snapping and mesh floor sampling ask the
|
||||
renderer's globe (`isSettled`), camera (`pose`) and query (heights) ports, and
|
||||
see through the caller's draw sets by id. A viewer with no renderer bound needs
|
||||
the Cesium adapter's factories loaded (`gods-eye-view/render/cesium/unbound`)
|
||||
first; until then the snap and the sampler answer nothing and location framing
|
||||
throws, naming that export.
|
||||
|
||||
Terrain cancellation rejects late replies before caching, clears floor queues and
|
||||
removes the map-stack listener. Annotation lookup caches are instance-owned and
|
||||
cleared on cancellation. Geometry selection and floor policies are unchanged.
|
||||
|
||||
+322
-112
@@ -12,16 +12,17 @@ north.
|
||||
|
||||
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 idle render governor (`src/renderGovernor.js`) caps a parked scene at
|
||||
`IDLE_FRAME_RATE` (60) ticks a second, because Cesium still runs the clock,
|
||||
data sources and update listeners on every animation frame even when it skips
|
||||
the draw; the viewer starts at that cap until the governor is installed. The
|
||||
camera holds continuous render from `moveStart` to `moveEnd`, and samples its
|
||||
The Cesium frame port (`src/render/cesium/ports.js`, its `idleFps`) caps a
|
||||
parked scene at `IDLE_FRAME_RATE` (60, `src/renderGovernor.js`) ticks a
|
||||
second while no hold is out, because Cesium still runs the clock, data sources
|
||||
and update listeners on every animation frame even when it skips the draw; the
|
||||
viewer starts at that cap until the frame port takes over. Through the idle
|
||||
render governor, the camera port holds continuous render from `moveStart` to `moveEnd`, and samples its
|
||||
pose every 250 ms in between, so a camera drifting by rounding errors (no
|
||||
`moveEnd`) is released after half a second at rest and held again if it moves. The world clock holds continuous render while
|
||||
it plays away from the live edge (not while it steps or waits for data), so
|
||||
playback draws at the display's rate too. Waits that used to count frames (a followed contact's first
|
||||
position, a shared follow view, a trail's temporary copy) count drawn time
|
||||
position, a shared follow view) count drawn time
|
||||
through `src/time/frameWait.js`, at most 100 ms a frame, so they last the same
|
||||
at any refresh rate and a background tab does not use them up.
|
||||
|
||||
@@ -101,7 +102,7 @@ does nothing, wherever it starts. Rotation drags that start on the planet, and
|
||||
zoom, are unchanged. How much of the frame shows the planet's surface is
|
||||
measured by casting a 32×18 grid of view rays at the ellipsoid; while the scope
|
||||
mask is on (the default) only the rays inside its keyhole count, since the mask
|
||||
hides or dims the rest. Voice tilt and in-place turns of a free 3D camera above
|
||||
hides or dims the rest. Voice tilt and in-place turns of a free camera above
|
||||
1,000 km stop when about a tenth of the frame still shows the surface (or about
|
||||
as much as it showed when it started), never less than about 1% of the visible
|
||||
frame, and a view that already shows less only keeps or gains what it has. A
|
||||
@@ -132,7 +133,7 @@ Views with more surface than that, such as the oblique orbital Director shots,
|
||||
are left as they are, and so are tracked or locked cameras, a camera flight in
|
||||
progress, a Director scene while it plays (holds included), a pointer held
|
||||
down on the globe (a drag held still; with several fingers down, until the
|
||||
last is released) and the 2D and Columbus modes; a check a flight, scene or
|
||||
last is released); a check a flight, scene or
|
||||
held pointer defers runs once it ends. A release outside the window that the
|
||||
page never sees counts as given once the window loses focus, the page is
|
||||
hidden, the canvas loses the pointer's capture, or the pointer moves with no
|
||||
@@ -143,6 +144,11 @@ it is until the next move. A voice turn requested while the camera is tracked is
|
||||
judged by the pose voice's release of the follow camera will leave, before that
|
||||
release, so a refused turn keeps the tracking.
|
||||
|
||||
The app draws only the 3D globe: the renderer it draws through has no 2D or
|
||||
Columbus view. Voice tilt, in-place turns and the move-end recovery above are
|
||||
written for that globe alone and carry no check for the other scene modes,
|
||||
which in Cesium's 2D and Columbus views made them do nothing.
|
||||
|
||||
Analyst region queries resolve unique Natural Earth names offline without
|
||||
geocoding, so Gold Coast and Ivory Coast name the West African natural regions.
|
||||
Duplicate names require a geocoded containment anchor; when several entries for
|
||||
@@ -1019,9 +1025,10 @@ resources and subscriptions. The globe relief helper is enabled with Wind and
|
||||
released when Wind is disabled. It uses terrain vertex normals
|
||||
for view-directed shading, falling back to global globe-curvature shading when
|
||||
normals are unavailable; the fallback does not show local hillshade. Neither mode
|
||||
adds elevation data or represents sunlight. Relief declines to replace an
|
||||
existing globe material, restores the prior empty material only while still
|
||||
owning it, and leaves later owners intact.
|
||||
adds elevation data or represents sunlight. Relief is the globe port's
|
||||
`hillshade` surface shading: the renderer never replaces a globe material
|
||||
someone else holds (it waits until that one is gone), gives the globe back
|
||||
when Wind is disabled, and leaves later owners intact.
|
||||
Source acquisition retains deadlines, body budgets, disconnect cancellation,
|
||||
per-model/field singleflight caching and one-minute failure backoff. Application
|
||||
catalog construction owns each instance.
|
||||
@@ -1225,7 +1232,7 @@ Keyless terrain tiles retry when Re:Earth throttles them. The browser fetches
|
||||
`terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no
|
||||
proxy in this repository sees those requests (`/api/terrain/heights` is the
|
||||
separate point-height endpoint), and the upstream edge answers zoom-out bursts
|
||||
with HTTP 429 under load. `src/maps/terrain.js` hands Cesium a `Resource`
|
||||
with HTTP 429 under load. `src/render/cesium/mapTerrain.js` hands Cesium a `Resource`
|
||||
whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch
|
||||
inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms
|
||||
doubling to a 15 s cap, with every retry waiting behind one shared cooldown
|
||||
@@ -1600,7 +1607,9 @@ unchanged.
|
||||
Polled layer refreshes and the HUD's camera readout pause while the page is
|
||||
hidden. An app embedded inline in a panel keeps both running, because the
|
||||
panel's host can report the page as hidden while it is on screen. This is the
|
||||
same rule the render loop follows (`keepPanelRendering` in `app/embed.js`).
|
||||
same rule the render loop follows (`keepPanelRendering` in
|
||||
`render/cesium/panelRendering.js`, which the Cesium plugin hands the
|
||||
application and the application scene hands the embed views).
|
||||
|
||||
Application scene setup owns request services, terrain/floor caches and annotation
|
||||
lookup state. Controls, layers and voice share those owners, and cancellation
|
||||
@@ -1760,15 +1769,19 @@ 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.
|
||||
|
||||
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames.
|
||||
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.
|
||||
|
||||
Traffic and bikeshare expose factories through `./layers/traffic` and
|
||||
`./layers/bikeshare`. Traffic separates road requests, ingestion, animation,
|
||||
flow matching, styling, viewport lifecycle and development timing. Each source
|
||||
owns its decoded flow cache; cancelled bodies cannot refill it. Bikeshare
|
||||
separates its city registry, station source, parsing, rendering, selection and
|
||||
proximity lifecycle. Existing standalone sources, live/simulated labels, road
|
||||
budgets, station availability and polling behavior are retained.
|
||||
proximity lifecycle; its station dots and selected-station highlight are two
|
||||
renderer draw sets and it no longer reaches Cesium, so a caller handing it a
|
||||
Cesium viewer, with no renderer bound, loads the
|
||||
`./render/cesium/unbound` export once first. Existing standalone sources,
|
||||
live/simulated labels, road budgets, station availability and polling behavior
|
||||
are retained.
|
||||
|
||||
Installations and proximity context now expose `./layers/installations` and
|
||||
`./layers/awareness` factories. Each owns its records, selection, presentation,
|
||||
@@ -1787,7 +1800,17 @@ a fresh winning record. Dense removal clears only its own provenance, and a
|
||||
fresh core rebuild or lifecycle reset replaces the corresponding ownership.
|
||||
Source adapters retain the existing CelesTrak and Launch Library
|
||||
endpoints; standalone entries provide scene services and the satellite dependency.
|
||||
The satellites layer draws through the renderer's draw port and no longer
|
||||
reaches Cesium: the dots are one point set moved in a single write a frame, the
|
||||
tracked satellite's dot a set of its own drawn where the follow camera framed
|
||||
it, and the orbit rings a line set dimmed behind the globe and turned with the
|
||||
Earth each second. A caller handing it a Cesium viewer, with no
|
||||
renderer bound, loads the `./render/cesium/unbound` export once first.
|
||||
The mission factory separates paths, replay, camera, panel, overlays and placement.
|
||||
Its markers, lines, live rings and pad zone are renderer draw sets, and it
|
||||
follows a mission through the camera port, so a caller handing it a Cesium
|
||||
viewer, with no renderer bound, loads the
|
||||
`./render/cesium/unbound` export once first.
|
||||
Launch Library pad coordinates retain unknown values: missing fields use the
|
||||
reported location coordinates when available, and launches without a known pad
|
||||
position stay off the map. Genuine zero coordinates remain valid. Undisclosed
|
||||
@@ -1808,10 +1831,16 @@ and scene services. Disable and teardown cancel pending refreshes; malformed
|
||||
snapshots preserve the last good display. Refresh restoration keeps selection
|
||||
identity without announcing a new user selection. Source/label, LOD thresholds,
|
||||
card limits, fire identities, altitude placement and analyst records are retained.
|
||||
The layer draws its fire glows through the renderer's draw port and no longer
|
||||
reaches Cesium; a caller handing it a Cesium viewer, with no
|
||||
renderer bound, loads the `./render/cesium/unbound` export once first.
|
||||
|
||||
Earthquake rendering is exposed through `./layers/earthquakes`. The layer owns
|
||||
its entities and request lifecycle; the application supplies the overlay host
|
||||
and snapshot source. The standalone adapter keeps the existing USGS daily feed,
|
||||
its renderer draw set and request lifecycle and no longer reaches Cesium; the
|
||||
application supplies the overlay host and snapshot source. A caller handing
|
||||
it a Cesium viewer, with no renderer bound, loads the
|
||||
`./render/cesium/unbound` export once first. `depthColor` returns a renderer
|
||||
colour `[r, g, b, a]` and `depthAccent` its CSS. The standalone adapter keeps the existing USGS daily feed,
|
||||
M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or
|
||||
destroying the layer cancels pending work and ignores late results. While on,
|
||||
the layer registers its quakes of magnitude 6 and up
|
||||
@@ -1822,6 +1851,21 @@ feed's place, cut to 40 characters (`earthquakeMarkLabel` in
|
||||
`src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon
|
||||
Islands`, or `M6.4` with no place).
|
||||
|
||||
Air quality (`./layers/air-quality`) draws its station discs as one renderer
|
||||
draw set of ground-clamped fills and reads the view through the camera port; it
|
||||
no longer reaches Cesium, so a caller handing it a Cesium viewer,
|
||||
with no renderer bound, loads the `./render/cesium/unbound` export once
|
||||
first.
|
||||
|
||||
Cockpit (`./ui/cockpit`) flies the camera through the camera port on the frame
|
||||
port's `preUpdate`, with the shared geo maths, and no longer loads the Cesium
|
||||
camera factory: a caller handing it a Cesium viewer, with no
|
||||
renderer bound, loads the `./render/cesium/unbound` export once first, or its
|
||||
controller throws naming it. Whether the aircraft it flies still draws comes
|
||||
from its `trackedEntityDrawn` service (the shell asks the entity's record,
|
||||
and the application scene's `viewerDrawsEntity` for an entity of the viewer's
|
||||
own); without one, Cockpit takes the aircraft as drawn.
|
||||
|
||||
## Rendered-mesh floor readings — November 9, 2026
|
||||
|
||||
On the photoreal stack the shared floor (`cachedGroundFloor`) answers from
|
||||
@@ -1846,12 +1890,26 @@ directly under a deck or a roof overhang reads the structure above it, and a
|
||||
vehicle between readings takes the nearest one, so its floor steps where the
|
||||
nearest reading changes.
|
||||
|
||||
The sampler and the aircraft ground snap (`src/services/groundSnap.js`) reach
|
||||
the renderer only through its ports: the camera's `pose()` for the probe
|
||||
height gate, the globe's `isGlobeVisible()` (the sampler runs only with
|
||||
the globe hidden) and `isSettled('surface')` (sampler) and
|
||||
`isSettled('tiles')` with `isSettled('surface')` (snap) for whether the tiles
|
||||
have streamed, and the query
|
||||
port's heights, seeing through the caller's draw sets by id. Cockpit's ground
|
||||
probe names the tracked contact's icon and model sets, which the flights and
|
||||
military layers keep on its entity record (`groundSets`).
|
||||
|
||||
## Vessel components and sources
|
||||
|
||||
`src/data/aisLiveVessels.js` assembles `createVesselLayer` from the
|
||||
`./layers/vessels` package entry. The factory owns feed lifecycle, keyed records,
|
||||
rendering, selection, trails and cards in separate components. The standalone
|
||||
entry supplies its AISStream source, scene services and existing row limits.
|
||||
Its ship icons are one renderer icon draw set (held motion, course rotation,
|
||||
focus emphasis, horizon cull) and the entry no longer reaches Cesium, so a
|
||||
caller handing it a Cesium viewer, with no renderer bound,
|
||||
loads the `./render/cesium/unbound` export once first.
|
||||
|
||||
Incomplete observations retain missing keyed vessels for at most five minutes
|
||||
since their last accepted receipt, within the renderer's row budget (plus the
|
||||
@@ -1907,31 +1965,29 @@ A tracked civil or military aircraft's trail (`src/data/trailContinuity.js`) lif
|
||||
the pen, drawing nothing, between two points more than 48 minutes or over 1,500 kt
|
||||
apart (a parked aircraft within 0.1 nm keeps one line for up to three hours) and at a
|
||||
waypoint with no altitude; a ground waypoint is drawn on the ground. The head joins the
|
||||
aircraft only within 150 km. Each trail keeps up to 2,000 points, a full day of history
|
||||
at one fix per minute plus the live session; past that the oldest recorded points go
|
||||
first, and the oldest reports only once none are left. The renderer
|
||||
aircraft only within 150 km. Each trail keeps up to 2,000 reports, a full day of history
|
||||
at one fix per minute plus the live session; past that the oldest go first. The renderer
|
||||
(`src/data/trailRenderer.js`) freezes every chunk of 128 points except the newest into
|
||||
static geometry, so a long trail costs about as much per frame as a short one;
|
||||
`scripts/qa-trail-freeze.mjs` checks that a freeze never shows a blank frame.
|
||||
While an aircraft is tracked, its trail between reports is the path its icon was
|
||||
drawn along: the displayed position is recorded about once a second or every 150 m
|
||||
(`recordTrailPoint`). Recorded points are thinned by shape: one stays only where
|
||||
dropping it would move the line more than 30 m across the track or in height from any
|
||||
position it stood for, or leave a straight piece longer than 10 km, so straight flight
|
||||
adds a vertex every 10 km at most and a turn keeps its curve. A recorded point that
|
||||
would turn the line back sharper than 120° over a short step is dropped. Reports stay
|
||||
in the trail as anchors, in time order. Recorded points never join two reports that are
|
||||
not one flight under the 48-minute and 1,500 kt rules; the points between them go and
|
||||
nothing is recorded across such a pair. A report for a time the display has already
|
||||
passed replaces what was drawn after it, and nothing is recorded until the icon has
|
||||
eased onto it, so the line reads arc, report, corrected path. History from before tracking started, and the backfill, run report to report.
|
||||
A trail holds the aircraft's reports and nothing else, in time order: what the icon was
|
||||
drawn at between them is never kept, so a late report cannot leave a kink. Between two
|
||||
reports that are one flight and both carry a track, the icon is drawn along, and the
|
||||
trail drawn through, one curve (`src/data/fixCurve.js`): a biarc, two constant-rate
|
||||
turns sent to the renderer as contract `arc` segments, passing through both reports and
|
||||
leaving each along its reported track, so the icon sits on its trail with no offset.
|
||||
Pairs with no track, slower than 40 m/s, or with a track more than 75° off the line
|
||||
between them are joined straight. The trail samples the curve at least every degree of
|
||||
turn. History from before tracking started, and the backfill, run report to report the
|
||||
same way.
|
||||
The trail never runs past the icon or through its 3D model, and the head runs from the
|
||||
newest kept point outside the model to the icon (to the model's tail when the model is
|
||||
the visual). A contact with no new report coasts along its reported track for 5 minutes
|
||||
past its last real report, at no more than 1,500 kt and never below known ground, then stops;
|
||||
the visual). A contact with no new report coasts straight on along its reported track for 5 minutes
|
||||
past its last real report (no turn: a turn rate measured over earlier reports outlives
|
||||
the turn), at no more than 1,500 kt and never below known ground, then stops;
|
||||
one that
|
||||
went quiet on the ground, or within 150 m of a known ground floor, holds at its last
|
||||
report, records nothing and draws no head (with the ground unknown, a low barometric
|
||||
report and draws no head (with the ground unknown, a low barometric
|
||||
altitude alone does not hold it). The hold-or-coast choice is made once per report (`staleHoldsForFix`
|
||||
in `src/data/motionModel.js`), and the forward fix built when a repeated position carries
|
||||
new speed or course follows the same rules and is never a trail report. A live report
|
||||
@@ -2275,10 +2331,13 @@ hidden; tilted past the Earth's limb neither the sensor nor the swath
|
||||
reads. A swath is confirmed only on the operator's, an agency's (ESA's
|
||||
eoPortal included) or an academic page for its platform. From
|
||||
16×, with flat imagery on the globe (not Google 3D tiles) and the view at
|
||||
nadir, every 2 s the view asks the base imagery layer for the tiles it will
|
||||
need 5 to 20 s ahead along the ground track (`prefetchImageryAhead` in
|
||||
`src/ui/cockpitOrbitalView.js`), so the browser has them cached when the
|
||||
view arrives. The level is the one Cesium will draw there
|
||||
nadir, every 2 s the Cesium renderer asks the base imagery layer for the
|
||||
tiles the view will need 5 to 20 s ahead along the ground track, so the
|
||||
browser has them cached when the view arrives. The renderer works this from
|
||||
its own camera (`preloadImageryAhead` in
|
||||
`src/render/cesium/imageryLookAhead.js`): a vertical field of view as narrow
|
||||
as an orbital view's at 16× for the camera's height, a look straight down,
|
||||
and the camera's own motion over the ground, which gives the track. The level is the one Cesium will draw there
|
||||
(`imageryLevelForView` in `src/cockpitOrbital.js`, following Cesium's own
|
||||
choice: the terrain level whose error spans at most the globe's maximum
|
||||
screen-space error, then the imagery level whose texels are nearest that
|
||||
@@ -2288,7 +2347,7 @@ at the lowest priority, so a request is declined while the imagery server's
|
||||
slots are taken by the tiles on screen and is the first dropped when the
|
||||
scheduler is full (a declined or dropped tile is asked for again later, one that failed to load is not); it remembers the last 512 tiles asked for and does not ask
|
||||
for those again, starts over on another base map (cancelling the old map's
|
||||
pending requests), and cancels the requests still pending on exit. Across the track it samples the centre line, a third
|
||||
pending requests), and when the view widens (below 16× or on exit) cancels the requests still pending and forgets the tiles asked for. Across the track it samples the centre line, a third
|
||||
out and the frame's edges. While tilted off nadir the view looks away from
|
||||
the track, and with the world clock more than a minute from now (paused or
|
||||
played back) it will not pass where the look-ahead points, so nothing is
|
||||
@@ -2544,6 +2603,14 @@ owners. Tuner calculations have a pure entry, with existing layer exports
|
||||
preserved. Destruction removes listeners and state subscriptions before ending
|
||||
tuning; a delayed Enable result cannot reveal or refocus removed controls.
|
||||
|
||||
The stations, their clusters and the selected marker draw through the
|
||||
renderer's draw port, and the layer no longer reaches Cesium. Stations drawn
|
||||
too close together on screen stand behind one cluster dot, grouped as the
|
||||
default renderer's entity clustering grouped them (`geo/screenCluster.js`,
|
||||
42 px, three or more), reclustered as the camera moves and when the filter
|
||||
changes. A caller handing the layer a Cesium viewer, with no
|
||||
renderer bound, loads the `./render/cesium/unbound` export once first.
|
||||
|
||||
## Giroc / Webcam Romania CCTV source pack
|
||||
|
||||
`config/cctv_sources.romania.json` is an optional single-camera pack for Giroc,
|
||||
@@ -2692,7 +2759,7 @@ and a Denver coordinate underground. Search now resolves the application's
|
||||
ground-floor elevation (bounded wait, same ellipsoidal datum) before framing and
|
||||
warms the cell; after landing, `src/cameraGroundGuard.js` samples the rendered
|
||||
surface under the target and the camera once tiles stream in and lifts the eye
|
||||
to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls and direct camera flights), layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners. `scripts/qa-context-arrivals.mjs` types Camp Mabry
|
||||
to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls), any other caller moving the camera or starting a flight before a retry, layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners; the guard compares the pose it started on rather than wrapping camera methods. `scripts/qa-context-arrivals.mjs` types Camp Mabry
|
||||
and a Denver coordinate and requires at least 60 m clearance.
|
||||
|
||||
## Layer panel ownership
|
||||
@@ -2707,10 +2774,11 @@ provides its confirmed toggle, taxa presets and fixed-order, nonempty legend.
|
||||
|
||||
## Sky background
|
||||
|
||||
`src/sky/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale
|
||||
`src/render/cesium/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale
|
||||
Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers
|
||||
rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with
|
||||
a TEME fallback while Cesium's IAU 2006 tables load. Bundled assets and
|
||||
a TEME fallback while Cesium's IAU 2006 tables load. The precise rotation reaches
|
||||
Cesium-free code (the celestial ring) through `src/sky/icrf.js`. Bundled assets and
|
||||
their provenance are documented in `src/data/local_data/sky/README.md`.
|
||||
|
||||
Anime fades out the Milky Way with its style intensity to avoid cel-shaded
|
||||
@@ -2747,7 +2815,7 @@ during viewer construction, before any tile builds a draw command.
|
||||
|
||||
When the globe stops drawing, the scene chrome says so instead of leaving a
|
||||
black globe behind working controls. `installRenderFailureNotice()`
|
||||
(`src/ui/renderFailure.js`) listens for Cesium's `renderError` and the canvas'
|
||||
(`src/render/cesium/renderFailure.js`) listens for Cesium's `renderError` and the canvas'
|
||||
`webglcontextlost`, logs the error, and publishes a notice that
|
||||
`RenderFailure.vue` shows as an alert dialog with focus on its first action.
|
||||
The app's viewer uses `showRenderLoopErrors: false`, so Cesium's dead-end
|
||||
@@ -2801,11 +2869,14 @@ remain unchanged.
|
||||
|
||||
## Visual effects ownership
|
||||
|
||||
VisualEffects owns style-stage creation, crossfades, animation scheduling, bloom
|
||||
and sharpen. Display supplies actions and renders settings; effect execution has
|
||||
no DOM dependency. Existing presets and the 500 ms transition remain unchanged.
|
||||
Stopping the controller revokes animation before asynchronous UI teardown; final
|
||||
destruction removes its stages and restores the borrowed bloom configuration.
|
||||
VisualEffects keeps the records of the styles, their crossfades, bloom and
|
||||
sharpen, and drives them through the renderer's effects port: it defines each
|
||||
preset there as a style, and the renderer runs the passes and animates the
|
||||
animated ones. Display supplies actions and renders settings; effect execution
|
||||
has no DOM dependency. Existing presets and the 500 ms transition remain
|
||||
unchanged. Stopping the controller revokes animation before asynchronous UI
|
||||
teardown; final destruction removes its styles and turns bloom and sharpen off,
|
||||
and the renderer restores the scene's bloom configuration when it goes.
|
||||
Snow is no longer a visual preset. A share link that names it, in either the
|
||||
long or compact form, opens on Normal and drops the Snow shader parameters. A
|
||||
view passed to embed mode or `show_in_gods_eye_view`, and a saved scene shot,
|
||||
@@ -3681,9 +3752,14 @@ which embeds the MAP_KEY.
|
||||
windows reuse the active load. Disabling or returning Contacts to passive mode
|
||||
clears its anchor; passive refreshes cannot reclaim it. Background repaints
|
||||
refresh context records without publishing a new selection.
|
||||
Installation tiles decode only the `landuse` layer. Reloads keep the Cesium
|
||||
entities of sites whose geometry is unchanged, so outlines and fills do not
|
||||
blink. While Contacts has a subject, the layer loads a window around it
|
||||
Installation tiles decode only the `landuse` layer. The site dots, the
|
||||
selected site's dot (a set of its own, so selecting one redraws no other),
|
||||
their ground outlines and the selected site's fill are renderer draw sets;
|
||||
reloads keep the drawn items of sites whose geometry is unchanged, so
|
||||
outlines and fills do not blink. The layer no longer reaches
|
||||
Cesium; a caller handing it a Cesium viewer, with no
|
||||
renderer bound, loads the `./render/cesium/unbound` export once first.
|
||||
While Contacts has a subject, the layer loads a window around it
|
||||
instead of the camera view (100 km half-width at mid latitudes, shrinking so
|
||||
it fits 16 z9 tiles), moves it only after the subject travels 20 km, and
|
||||
ignores camera `moveEnd`; clearing the subject returns to the viewport. The
|
||||
@@ -3840,9 +3916,12 @@ which embeds the MAP_KEY.
|
||||
> so a turned-off layer's entities stayed reachable (Data Centers kept 116
|
||||
> MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`,
|
||||
> requests one frame through `governorRequestRender` after every layer
|
||||
> disable and then trims those arrays. It reads private Cesium fields;
|
||||
> `src/sceneCommandRelease.test.mjs` pins them and fails if Cesium renames
|
||||
> them or changes which passes it truncates.
|
||||
> disable and then has `src/render/cesium/sceneCommandRelease.js` (handed
|
||||
> handed over by the Cesium plugin through `src/app/scene.js`) trim those
|
||||
> arrays. It reads private Cesium
|
||||
> fields through `src/render/cesium/internals.js`;
|
||||
> `src/render/cesium/sceneCommandRelease.test.mjs` pins them and fails if
|
||||
> Cesium renames them or changes which passes it truncates.
|
||||
|
||||
> **2026-08-08 — performance waves 1+2:** the app idles via an explicit render
|
||||
> governor (`src/renderGovernor.js` — hold/release from every per-frame
|
||||
@@ -4250,7 +4329,7 @@ isCurrent })` gates BOTH halves of the map-stack switch, which is its only
|
||||
> tunnels. Every other layer
|
||||
> is untouched: aircraft, vessels and satellites draw their markers over the
|
||||
> scene on purpose and keep their labels over it. The test runs on the GPU
|
||||
> (`src/data/sceneOcclusionProbe.js`): one occlusion query per contact,
|
||||
> (`src/render/cesium/sceneOcclusionProbe.js`): one occlusion query per contact,
|
||||
> repeated every 100 to 200 ms, answered a frame or two later, with nothing
|
||||
> read back from the GPU and so no stall. A contact hides as soon as a
|
||||
> "hidden" answer arrives and returns 600 ms after its last one, which keeps
|
||||
@@ -4687,18 +4766,22 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> it, and narrow screens retain Cesium's surface with an internal
|
||||
> scroller. The title, close control, links, and persistent Google/Cesium line
|
||||
> remain unchanged and visible.
|
||||
> - **Distant-aircraft recession:** both civilian and military billboard fleets
|
||||
> - **Distant-aircraft recession:** both civilian and military icon sets
|
||||
> retain their locked class/ground scale and `NearFarScalar`, then multiply a
|
||||
> limb-relative taper in the existing ~12 Hz tick. The taper is 1 below 0.5×
|
||||
> limb-relative taper. The sets say so themselves (`SetSpec.recede`, with
|
||||
> the tuning as its parameters, sent again when the tuning changes), and the
|
||||
> renderer works the taper out each frame from `render/recession`. The
|
||||
> taper is 1 below 0.5×
|
||||
> geometric limb distance and smoothsteps to 0.45 scale plus a 0.35 alpha-haze
|
||||
> factor at the limb. That treatment eases continuously back to identity from
|
||||
> 3,500–4,500 km camera height, avoiding a globe-view threshold pop. These
|
||||
> values, the start ratio, blend band, composed floor, and write epsilon remain
|
||||
> runtime tunings. No aircraft is count-culled or made fully transparent.
|
||||
> Focus emphasis and limb haze multiply at one deadband-gated write site, and
|
||||
> their product is clamped to 0.20 before freshness alpha is applied. Ambient
|
||||
> fleet models receive that same composed alpha; class/ground/cockpit repaints
|
||||
> preserve the current limb scale instead of dropping it for a tick.
|
||||
> Focus emphasis and limb haze multiply, and their product is clamped to
|
||||
> 0.20 before freshness alpha is applied. Ambient fleet models receive that
|
||||
> same composed alpha, worked out on each fleet tick from the camera then
|
||||
> and written again once it moves by more than 0.005; their set itself does
|
||||
> not recede. Under the IR boost they draw at full alpha.
|
||||
> - **Focus-aware contact de-emphasis:** civilian/military aircraft and
|
||||
> satellites publish the selected target's padded screen bounds and camera
|
||||
> distance from the same per-frame position cache already consumed by their
|
||||
@@ -4785,10 +4868,13 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> untracking, so a stationary slow press on a plane still selects it. Escape
|
||||
> still releases tracking in place. The 200 px feel needs close-range field
|
||||
> verification; fleet model sizing remains unchanged.
|
||||
> - **Deterministic sprite stacking:** contact collections reassert the stable
|
||||
> bottom-to-top order CCTV, FIRMS, bikeshare, AIS, military, then civilian
|
||||
> flights after every relevant layer init/enable and immediately after FIRMS
|
||||
> lazily registers its detection sprites. Always-visible contact
|
||||
> - **Deterministic sprite stacking:** contact sets are made at draw orders
|
||||
> (`SetSpec.drawOrder`, from `spriteDrawOrder`) that stack them bottom to
|
||||
> top as CCTV, FIRMS, bikeshare, transit, directions, AIS, military, then
|
||||
> civilian flights on top, whichever layer was turned on first; picks
|
||||
> name the topmost first. The orders are negative, so every overlay at the
|
||||
> default order (selection highlights, route endpoints, the tracked plane)
|
||||
> still draws over all of them. Always-visible contact
|
||||
> depth settings are unchanged. Cesium OIT weighted blending may soften strict
|
||||
> alpha layering on some GPUs, so the ordering remains a real-browser check.
|
||||
> - **Deterministic card stacking:** CCTV, FIRMS, vessel, and tracked-target
|
||||
@@ -4945,8 +5031,14 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> celestial ring, annotations SVG, missions frame tick, and traffic).
|
||||
> - **World-label accounting:** All intended label/card migrations use the
|
||||
> shared host. The former native `LabelGraphics` exception for cable reference
|
||||
> labels was retired on 2026-08-18; cable text may render over tile geometry,
|
||||
> so **zero native world-label creation sites remain**. The mission replay DOM vehicle, awareness
|
||||
> labels was retired on 2026-08-18; cable text may render over tile geometry.
|
||||
> The Directions A/B letters (`directions-markers` source) and data-pack media
|
||||
> labels (a pooled `data-pack-labels:<n>` source per pack resource, through
|
||||
> the pack handle's `label`) moved to the host on 2026-11-04, and
|
||||
> `src/noCesiumLabels.test.mjs` no longer keeps an allow-list, so **zero
|
||||
> native world-label creation sites remain**. A media pack shown without an
|
||||
> `overlayHost` fails to load rather than drawing a native label. The mission
|
||||
> replay DOM vehicle, awareness
|
||||
> compass, annotation SVG callouts, and host-owned detection isolation target
|
||||
> are explicit exceptions; the awareness ring and cockpit contact pips are
|
||||
> non-text out-of-scope surfaces. Annotation callout text, geometry, leaders,
|
||||
@@ -4994,7 +5086,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> ambient-label host source. Its getter reads the point's own position, which
|
||||
> moves every frame, eliminating the former second ISS
|
||||
> propagation. Satellite tracking continues to publish exactly one protected
|
||||
> tracked-lane card through `gevLabelModel` and `_trackedDisplayCached`; the
|
||||
> tracked-lane card through its entity record's `labelModel` and `_trackedDisplayCached`; the
|
||||
> tracked entity is point-only. Tracking ISS suppresses the ambient entry and
|
||||
> untracking restores it, preventing duplicate ISS text. Disable, orbit-text
|
||||
> preference changes, catalog rebuild, and destroy clear/hide the source.
|
||||
@@ -5009,7 +5101,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> - **Phase 5 tracked civil aircraft label:** A tracked flight's Cesium entity
|
||||
> is a billboard-only camera target with no native label. The flight source
|
||||
> retains callsign/registration fallback, flight-level/altitude, speed, stale
|
||||
> state, airline/type, and plausible-route formatting in `gevLabelModel`; the
|
||||
> state, airline/type, and plausible-route formatting in the entity record's `labelModel`; the
|
||||
> one protected tracked-lane host card renders that complete model. Its
|
||||
> position getter reads only `_trackedDisplayCached`, the same authoritative
|
||||
> Cartesian already consumed by the tracked visual and camera, and never
|
||||
@@ -5119,8 +5211,11 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> - **Tracked-readout ownership:** `trackedReadout.js` is now a presentation-model
|
||||
> bridge only; it owns no canvas, projection, post-render listener, layout,
|
||||
> keyhole fade, or paint path. Civilian flights, military flights, satellites,
|
||||
> and mapped installations write explicit `gevLabelModel` objects and expose
|
||||
> `gevDisplayPosition` getters backed by their layer-owned frame/display cache.
|
||||
> and mapped installations write explicit `labelModel` objects and
|
||||
> `displayPosition` getters, backed by their layer-owned frame/display cache,
|
||||
> into the app's entity records (`src/data/entityRecords.js`), never onto the
|
||||
> Cesium entity. A layer's private per-entity state goes in its own store from
|
||||
> `createEntityStore()` (ALPR markers: `src/layers/alpr/markerState.js`).
|
||||
> Selected AIS vessels continue using the vessel source's protected selected
|
||||
> card, so they do not create a duplicate tracked readout. The host registers
|
||||
> the active readout in the protected tracked lane with a zero ambient quota;
|
||||
@@ -5531,8 +5626,8 @@ centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap;
|
||||
nearby views share whole-degree cache keys, and a minute poll refreshes data.
|
||||
Counts and bands cover visited views over 30 minutes, including regions now off
|
||||
screen. Cells are H3 resolution-4 hexagons, gpsjam.org's grid, keyed by their H3
|
||||
index (`gnssCellKey`) and drawn from `cellToBoundary` (via `h3-js`) as one ground
|
||||
primitive of polygons, rebuilt only when a cell or band changes; a cell across the
|
||||
index (`gnssCellKey`) and drawn from `cellToBoundary` (via `h3-js`) as clamped
|
||||
polygons in one shapes set of the draw port, redrawn only when a cell or band changes; a cell across the
|
||||
antimeridian is drawn with its longitudes unwrapped around its centre. As on
|
||||
gpsjam.org there is no minimum aircraft count: every cell with an aircraft is
|
||||
shown, and the one-aircraft discount is the only small-sample guard.
|
||||
@@ -6022,13 +6117,14 @@ the same navigation authority as every other camera destination.
|
||||
given; re-arming for the other endpoint reuses that lease rather than asking
|
||||
for a second claim, and every release names the lease, so a superseded instance
|
||||
can never free the claim its replacement holds. The claim is held until
|
||||
the click that uses it has finished being dispatched — every layer binds its
|
||||
own handler to the same canvas and they all run inside one browser event, so a
|
||||
claim dropped the instant the endpoint is placed would hand the rest of that
|
||||
same click to the ambient handlers bound after this one. It is returned on the
|
||||
next tick after placement, and immediately on cancel, Escape, CLEAR, disable
|
||||
and destroy; if another tool already holds it nothing is armed and the row says
|
||||
so. Maneuver-dot selection is an ordinary ambient handler and yields while any
|
||||
the click that uses it has finished being dispatched: the input dispatcher
|
||||
checks the claim once per click, before any subscriber runs, but DOM canvas
|
||||
listeners (the evidence cards) still see the same browser event afterwards, so
|
||||
a claim dropped the instant the endpoint is placed would hand them that click.
|
||||
It is returned on the next tick after placement, and immediately on cancel, Escape, CLEAR, disable
|
||||
and destroy. The newest claim takes over: arming takes the pointer from a tool
|
||||
holding it, which is told and turns itself off, and a newer tool taking it
|
||||
disarms the layer as Escape would. Maneuver-dot selection is an ordinary ambient handler and yields while any
|
||||
tool holds the pointer. FLY runs through the UI shell's immediate-navigation
|
||||
facade — the same camera authority validated voice destinations use — and is
|
||||
handed the shared ground-floor read and corridor warm, so the dolly does not
|
||||
@@ -6223,11 +6319,27 @@ synchronizes visible playback before its next frame.
|
||||
Playback reserves numeric scratch before the first sample, including unknown
|
||||
heights, and reuses caller-owned sample and segment storage.
|
||||
|
||||
**Scene work.** Stationary and animated billboards use separate, adjacent
|
||||
collections above CCTV and Bikeshare. Traffic, Bikeshare and Transit share camera
|
||||
sensitivity claims; the original sensitivity returns after the last release.
|
||||
Visibility checks combine the camera frustum and ellipsoid occlusion at no more
|
||||
than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals
|
||||
**Scene work.** Stationary and animated vehicles are two draw-port icon sets
|
||||
(`transit:<n>:still` and `transit:<n>:moving`), made at adjacent draw orders
|
||||
from the sprite order (`spriteDrawOrder`), above CCTV and Bikeshare. Each marker
|
||||
is a plain record (position, show, image, size, colour, rotation); a frame
|
||||
writes the changed ones to their set in one batched upsert, markers taken out
|
||||
in one task go in one removal, and a marker that starts or stops moving moves
|
||||
between the sets. The renderer moves and turns an icon without restyling it.
|
||||
Rotation is computed in screen space through the query port's projection
|
||||
(`perspectiveCourseRotation`), as before. Clicks read the draw-port hit. The
|
||||
layer no longer reaches Cesium, so a caller handing it a Cesium viewer,
|
||||
with no renderer bound, loads the `./render/cesium/unbound` export
|
||||
once first. Transit listens to the camera port at its own `changed` threshold
|
||||
(0.05); the port measures each listener separately, so no layer changes
|
||||
another's camera trigger.
|
||||
Visibility checks combine the camera port's frustum and the query port's
|
||||
ellipsoid occlusion at no more than 4 Hz; missing map bounds do not admit the
|
||||
globe's far side. Whether the globe is the bare ellipsoid is asked of the
|
||||
height service at the camera's subpoint each time the globe's surface
|
||||
changes; the answer comes asynchronously, the last one holds until then, and
|
||||
floors are read again when it flips.
|
||||
Camera arrivals
|
||||
rebuild an unprepared or cold marker corridor during that visibility sweep,
|
||||
adopt a loaded surface, and update both heightPending and surfaceReady diagnostics.
|
||||
A resolved display sample clears its pending-height gate without waiting for a poll. Frame work
|
||||
@@ -6258,7 +6370,8 @@ it does not establish Google 3D acceptance.
|
||||
The full run samples completed frames at 1920×1080 CSS pixels, records DPR, and
|
||||
measures moving fleets of 800 and 3,000 vehicles with 128 fixes each and DETECT
|
||||
on. Street/metro targets are respectively: transit frame CPU p95 ≤1/4 ms, frame
|
||||
interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame, and retained
|
||||
interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame (counted by
|
||||
`src/render/cesium/uploadProbe.js` for the two marker sets), and retained
|
||||
heap growth ≤24/48 MiB. The 3,000-vehicle CPU budget is 4 ms (recorded browser
|
||||
measurement 3.4 ms); the 800-vehicle budget stays at 1 ms (measured 0.9 ms).
|
||||
Transit-authored frame allocation is ≤8 KiB/frame at both fleets, attributed
|
||||
@@ -6896,7 +7009,7 @@ silently demoting every later lookup for the session.
|
||||
|
||||
- The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected.
|
||||
- The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies.
|
||||
- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft.
|
||||
- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved.
|
||||
- `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width.
|
||||
- The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility.
|
||||
- Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. Outside Cyber, the two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. Cyber keeps its separately framed mode buttons, its red panel titles, and in layout-focus a framed, centred standby card over its radar art.
|
||||
@@ -6907,7 +7020,7 @@ silently demoting every later lookup for the session.
|
||||
- On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification.
|
||||
- A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated.
|
||||
- Contacts rows and the Cockpit Contact counts name each cohort's provider: the source of the last snapshot, marked `FALLBACK` or `STALE` as its layer row would be. A poll in flight keeps the mark, where the layer row shows `LOADING`. A flight snapshot from the adsb.lol regional fallback reads `adsb.lol · FALLBACK`, not `OpenSky`.
|
||||
- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for, drawn as an unpickable primitive rather than an entity so a click or tap on its edge reaches the contact underneath (headless viewers without a primitive collection get a static entity instead); it is rebuilt when the subject moves. Three dim sonar pulses (3 px with a 1 px dark outline, same colours, at most 60% opacity) grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius. One unpickable 250 km disc draws both the pulse lines and the gradient, its shader reading the pulse radii and opacities each frame, so a click or tap near a pulse still reaches the contact underneath; the disc follows the subject by a model-matrix rotation and is rebuilt only after the subject moves 20 km, and not at all while the pulses rest. While the camera is below the disc's 2.5 km height, where it would sweep across the sky, the pulses rest: the disc is hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the disc and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one render request 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`), so they repaint at about 12.5 fps and never beat the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or in a scene without primitives or preRender and postRender hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m.
|
||||
- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline whose outer 1 px, half a pixel on each side, is a dark halo around a 3 px Context-blue core, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. Fronts and band are fixed in the world, so they step every 80 ms however many frames are drawn and look the same whether the camera moves or not; crossing the 2.5 km rim height shows or hides them at once. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m.
|
||||
- For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop.
|
||||
- Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff.
|
||||
- Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk.
|
||||
@@ -6923,8 +7036,8 @@ silently demoting every later lookup for the session.
|
||||
|
||||
### Motion & Symbology Correctness (June 10, 2026)
|
||||
|
||||
- **Flights (commercial + military)** render one poll interval behind real time (30s/15s) and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The display latency is an intentional product decision — do not "fix" it away. The fleet dead-reckons at ~12Hz (1m² write gating); a contact already hidden behind the horizon whose last position still is re-reckons on a staggered one-in-13-ticks rotation (about once a second) instead, so the worldwide feed's ~13k contacts no longer cost a full pass when well under 1% are on screen. Anything that position puts in view, and any contact with a fleet model, takes the full pass immediately, and hidden-inclusive proximity queries read positions at most about a second old; aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.”
|
||||
- **World-space headings at every angle** (`src/data/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder.
|
||||
- **Flights (commercial + military)** render behind real time and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The delay (`src/data/displayDelay.js`) follows how late the feed is: the 90th percentile of the newest 256 lags (a report's receipt time less the same contact's previous report time) plus 5 s, never under the layer's floor (30 s civil, 15 s military) nor over five minutes, so the anonymous OpenSky feed, whose reports arrive about 90 s old every 30 s, draws about two minutes behind. Before 16 lags, first reports' ages plus a poll interval stand in. The delay moves toward that aim by at most 0.2 s per second up and 0.05 s per second down (an aim within 2 s leaves it be), and takes it at once only while nothing is drawn; deliveries following the world clock, or replacing the world at another time, leave it alone and draw with no delay. Every consumer (icons, the renderer's live motion clock, labels, HUD, detection, the tracked camera and trail) reads the one delay. When a newer report puts a moving contact elsewhere than it is drawn (it was coasting past its newest report), it eases onto the new path over at least 3 s, at most 30% faster than its speed and within 20 s, from where it would have been that frame; more than 5 km off, it jumps. The display latency is an intentional product decision — do not "fix" it away. The whole fleet dead-reckons at ~12Hz (1m² write gating); aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.”
|
||||
- **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder.
|
||||
- **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them.
|
||||
- **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode.
|
||||
- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class.
|
||||
@@ -7576,8 +7689,8 @@ request viewbox and continues searching without that geographic preference.
|
||||
|
||||
- UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone.
|
||||
- **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too.
|
||||
- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the Cesium handler, the preview data source, the borrowed click actions and the `window.__gevDrawTool` handle. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam.
|
||||
- **The pointer, for an application's own tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner)` takes the pointer as Draw does and returns its lease, or `null` while another tool holds it; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. An owner without a name in `pointerOwnerNames.js` is named by its id when another tool reports who holds the pointer.
|
||||
- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band, dashed behind the surface too through the line's `depthFail` style, and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam.
|
||||
- **The pointer, for any other tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner, { onLost })` takes the pointer as Draw does, from any tool holding it, and returns its lease; `onLost` is called once when a newer claim takes it, and the tool turns itself off there; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do.
|
||||
- **Row actions are an application's own.** `createApplicationTools({ drawMarkActions })` hands `initDrawTool` buttons for drawn areas' and lines' rows; the standalone shell passes none, so the open-source build shows no new button and makes no new request. Each action (`drawMarkActions` in `src/annotations/drawMarks.js`) is `{ id, icon, label(name), shapes: ['area', 'line'], accepts?(geometry, shape), run({ id, shape, name, title, geometry }) }`: the icon a Material Symbols name, the label worded by the application, `name` the person's own and `title` the row's (the name, else `Area` or `Line · 950 m`), the geometry `drawMarkGeometry`'s `[lon, lat]` `Polygon` (closed; a `MultiPolygon` for an area handle with several parts) or `LineString`, longitudes wrapped into [-180, 180]. A pin, and a shape that crosses the antimeridian or has a part that cannot be given whole, has no geometry and is offered nothing. Malformed actions and repeated ids are dropped once, at construction. What `run` returns or resolves to is a note under the row (`role=status`; past 200 characters it is cut at a word with an ellipsis); the row is busy (`aria-disabled`, no second press) until it settles, a rejection or a throw clears the note and is logged (so an action words its own refusals and resolves with them), and a shape's note goes with the shape, so a late answer never lands on a removed one.
|
||||
- Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins.
|
||||
- **A vertex is a lon/lat, and the mark is DRAPED.** Clicks are picked through `pickWorldFromScreen` — one of two scene helpers the annotation resolver factory (`src/annotations/resolver.js`) exposes alongside `sampleGroundHeight`, so the app has ONE depth-aware pick cascade rather than a second written beside it — which returns the height the pick landed on as well as the coordinate, so the live preview hangs on the roof or hillside under the pointer instead of sinking to sea level. The world renderer draws areas and routes with `clampToGround`, so the height is dropped at finish in one place (`finishSpec`) rather than being carried downstream and discarded silently: what you get is the outline you drew, lying on the surface beneath it.
|
||||
@@ -7587,9 +7700,10 @@ request viewbox and continues searching without that geographic preference.
|
||||
- **Measurements and centres are computed on unwrapped longitudes** (`unwrapLongitudes` / `wrapLongitude` in `drawMode.js`, used by `ringAreaM2`, `ringCentroid` and the engine's manual-area anchor). A ~50,000 m² rectangle straddling the antimeridian reads its 0.002° width as 359.998° under raw arithmetic: it measured thousands of square kilometres and anchored on the Greenwich meridian, half a world from the shape. Path length was already safe — haversine is periodic in the longitude delta — and a test pins that so a "fix" cannot break it.
|
||||
- **Bounds.** One shape holds at most `MAX_VERTICES` = 512 points; two clicks within 0.5 m are one vertex (that is what makes a double-click finish without leaving a stray point); a vertex that is not a finite on-globe coordinate is refused. A shape that encloses nothing is refused rather than placed: three collinear points are not an area and a line under a metre long is not a line, and the hint says which.
|
||||
- Drawn-area measures round before choosing m², ha or km², so 9,999.6 m² displays as `1.0 ha`, not `10000 m²`, and 999,960 m² as `1.00 km²`, not `100.0 ha`.
|
||||
- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`) and **every** ambient scene selection handler — the shared tracking click gesture behind flights, military and CCTV, plus vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers and the CCTV calibration gizmo — returns before picking. A vertex over an aircraft is a vertex, not a selection.
|
||||
- **The claim is a LEASE.** `claimPointer(owner)` returns an opaque token or `null`; `releasePointer(lease)` takes that token. A second claim fails even under the same owner name, because two live instances of one tool — an old one mid-teardown and its replacement — are two owners; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease now releases nothing.
|
||||
- **Cesium's own click actions are borrowed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. Both are removed for the session and restored, as the same function objects, when it ends or the tool is destroyed.
|
||||
- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`), and the scene's input dispatcher (`src/input/dispatcher.js`) hands its clicks, moves and double clicks to the draw tool's leased subscriptions only: **every** ambient subscriber — flights, military, CCTV and its calibration gizmo, vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers — is skipped for that event before anything is picked. A vertex over an aircraft is a vertex, not a selection.
|
||||
- The input dispatcher no longer reaches Cesium. It takes its pointer events from the renderer's input port (`findInput`, `src/render/rendererOf.js`) and its picks, drills and ground points from the query port, with positions as plain `{x, y}`. A click's hits are the contract's `Hit`; something drawn outside the draw port is a `Hit` with `set: ''` that the Cesium adapter names (`src/render/cesium/nativeClick.js`), which also hangs the engine's own picks on `event.native` (`pick`, `pickWindow`, `drill`, through the follow helper) for layers still bound to them. The adapter's pick reuses the query port's pass for the same pixel, window and frame, so an empty click still costs one pick pass; a sky click makes no depth pass unless a globe tile is on its ray. A touch tap's contact search drills Cesium's own picks, eight deep, so something drawn outside the draw port still stops it or is found by it.
|
||||
- **The claim is a LEASE, and the newest claim takes over.** `claimPointer(owner, { onLost })` returns an opaque token; `releasePointer(lease)` takes that token. A second claim, even under the same owner name, ends the lease out, and its holder's `onLost` is called once, after the new lease holds the pointer: Draw turns off as if toggled off (the half-drawn shape and preview go, the stock clicks come back), the imagery box cancels, and Directions disarms. Two live instances of one tool — an old one mid-teardown and its replacement — are two owners, so the replacement wins; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease releases nothing. This is the renderer contract's rule (`input.claimPointer`), and the two are one: each scene's input dispatcher bridges its renderer's input port (`bridgePointer`), so the port holds a lease while a tool holds the pointer (the port is not free), and a claim made on the port itself takes over from the tool like any newer claim. That lease takes no press itself: the dispatcher decides who hears each event when it arrives, as each layer's own handler used to (a click reaches ambient selection only if no tool holds the pointer then, and a tool's subscribers only while its lease is current), and Cesium's own select and double-click follow run unless the tool holds them off (`suppressStockClicks`: Draw and the imagery box do, Directions does not).
|
||||
- **Cesium's own click actions are suppressed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. The tool takes the dispatcher's `suppressStockClicks()` hold for the session; both actions come back, as the same function objects, when the last hold is released (the imagery box takes the same hold).
|
||||
- **Enter belongs to whatever has the keyboard.** The finish key is taken only from the canvas and the page body. With a control focused — Clear, a shape button — Enter activates that control, as a keyboard user expects; it does not quietly finish the shape.
|
||||
- Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`.
|
||||
- The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`.
|
||||
@@ -7614,14 +7728,14 @@ request viewbox and continues searching without that geographic preference.
|
||||
- Only a new head costs REST calls: one recursive tree and one commit. An optional `GITHUB_TOKEN` raises the REST limit.
|
||||
- After an upstream outage, a successful branch-head check clears the error and pushes a recovered catalog even when the commit is unchanged. Cached products stay in place; subsequent healthy unchanged checks stay silent.
|
||||
- The new catalog goes to `.gev-cache/ghostmaps/catalog.json` and to every open page over server-sent events (`/api/ghostmaps/events`, 25 s heartbeat, at most 64 subscribers). Default products are downloaded at once.
|
||||
- The layer reloads only products whose blob changed. The new edition's data source is added before the old one is removed. A product that leaves the catalog leaves the globe.
|
||||
- The layer reloads only products whose blob changed. The new edition's draw sets are added before the old ones are removed. A product that leaves the catalog leaves the globe.
|
||||
- The row reads `LIVE` while the stream is open. A five-minute catalog read is the backstop.
|
||||
- **Files.** `/api/ghostmaps/file/{product}` serves only catalog products. Files are downloaded by commit-pinned raw URLs, so a CDN cannot return an older edition. They are cached on disk by blob sha, and blobs no current product uses are pruned. A request whose `?v=` names the current blob is `immutable`. Repository paths never reach the page.
|
||||
- **Source ownership.** The application catalog receives `sources['s2-ghostmaps']` through the shared source contracts; an omitted or null source stays unavailable without opening a stream or fetching. The standalone source factory supplies the same-origin implementation and accepts replacements. Packed-image URLs are released on cancelled or failed product construction, and remain owned by a successfully loaded product until it is removed.
|
||||
- **Voice and locales.** S2 can be toggled through its registered id and aliases. The model already sees the S2 GhostMaps brand in the id, and compact alias-hint separators keep the complete voice prompt within its existing 52,000-character limit; accepted aliases are unchanged. The row and reports are translated in Spanish, Russian and Simplified Chinese.
|
||||
- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into one `CustomDataSource` per product.
|
||||
- Points become ground-clamped billboards with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves.
|
||||
- Lines and polygon outlines are ground-clamped polylines.
|
||||
- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into renderer draw sets (icons, lines and shapes) per product edition. The layer no longer reaches Cesium, so a caller handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first.
|
||||
- Points become ground-clamped icons with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves.
|
||||
- Lines and polygon outlines are ground-clamped lines; polygon fills are ground-clamped shapes.
|
||||
- Styles, StyleMaps and inline styles are honoured. Icons come only from images packed in the same KMZ and at most 512 KB. Anything else uses a per-product round marker.
|
||||
- Network links, overlays, models and remote hrefs are never followed. Hidden placemarks are skipped. Bounds are 20,000 placemarks and 250,000 positions per product.
|
||||
- **Reports.** Clicking a marker opens a card with the product, folder, edition date and the placemark's report fields. `src/layers/ghostMaps/records.js` reads ArcGIS popup tables as text only: `<Null>` and internal fields are dropped and values are capped. Description markup is never inserted into the page. The first `http(s)` research link opens from the card. The card is `stateless`, so it comes and goes with the click, as CCTV cards do. It is also `horizonCull`ed, so it hides when its marker turns behind the planet. Picks are registered under `s2-ghostmaps`.
|
||||
@@ -7630,14 +7744,15 @@ request viewbox and continues searching without that geographic preference.
|
||||
### Import Your Own Files (October 2026)
|
||||
|
||||
- UTILITIES ▸ **Import** reads GeoJSON (`.geojson`/`.json`), KML, KMZ and GPX from the picker or a file drop anywhere in the app. Each file gets show/hide, Fly-to and Remove controls. GeoJSON and GPX use the row's color; KML/KMZ retain their styles and show a hatched swatch. The file bytes remain on the device for the page session. Rendered overlays can appear in map screenshots sent through voice or other existing screenshot tools.
|
||||
- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 against loaded terrain and, in the nearby camera footprint on photoreal maps, `clampToHeightMostDetailed`, then draw in one owned native BillboardCollection per file, with static positions and no per-frame point Entity visualizer or clamping callbacks. Point metadata remains in `dataSource.importedEntities` for framing/style inspection; non-point geometry stays in the normal source collection. Pin collections mount only after source admission, follow file show/hide, and are destroyed on removal. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy.
|
||||
- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 through the height service: the loaded terrain's height (0 on the bare ellipsoid, whose coarse tiles can sag far below it) and, in the nearby camera footprint on photoreal maps, the mesh height (`clampBatch`). They then draw as static icons in the file's own draw sets (pins, lines and shapes), with no per-frame clamping callbacks. GeoJSON lines and polygon edges follow rhumb lines, split into steps of at most half a degree. Each file's sets mount only after admission, follow its show/hide, and are removed with it. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy.
|
||||
- **Navigation.** Row Fly-to uses `runImmediateNavigation('file', …)`; Cockpit can refuse it and existing follow/track ownership is released first. Automatic Fly-to is stamped when a batch is submitted and reasserted before flying. Pointer/wheel gestures and newer navigation supersede it, including time spent in the queue. Framing uses every finite visible point/path/polygon-hole/wall vertex plus rotated overlay bounds, with viewport-aware range and a nadir view. The target uses available terrain/cached ground height and the ground guard on arrival. Empty footprints never fall back to deferred `viewer.flyTo`.
|
||||
- **Clock.** Imports expose no source clock and no entity availability. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged.
|
||||
- **Input handling.** Coordinates and GeoJSON geometry types are checked before Cesium allocation. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits.
|
||||
- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, native labels and descriptions are removed, and generated pins share one lossless image URL per canvas.
|
||||
- **Clock.** Imports keep no clock and no time ranges: everything in a file draws at all times. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged.
|
||||
- **Input handling.** Coordinates and GeoJSON geometry types are checked before anything is drawn. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits.
|
||||
- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, labels and descriptions are removed; only a short plain name reaches a drawn item. The default pins are shared SVG images.
|
||||
- **Bounds.** File size ≤50 MiB; inflated KMZ ≤120 MiB; ≤20,000 entities (including multipart children and Folder containers); ≤250,000 positions; ≤2,000 normalized style definitions and distinct image links; ≤12 files per session. Exact repeated styles share definitions without changing inheritance or inline overrides. Files of 20–30 MB fit the byte budget, subject to geometry/image limits. Refusals name a reason and batches continue; with multiple failures the hint shows the first reason.
|
||||
- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes data sources, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import.
|
||||
- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, native style/image equivalence, large-file painted output and frame times. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules.
|
||||
- **Code layout.** `src/data/geoFileImport.js` reads, bounds and sanitizes the files. `src/data/geoImportFeatures.js` turns the sanitized KML or GeoJSON into plain features (pins, lines, walls, polygons and ground overlays) with the styles Cesium's KML and GeoJSON loaders gave them: icon, scale, colour, heading and hot spot; line and polygon colours and widths; extruded or clamped geometry. `src/data/geoImportPins.js` draws those features through the renderer's draw port (`drawOf`), settles ground pins through the height service and frames the file for Fly-to. None of the three reaches Cesium, so the Cesium allow-list is empty. `src/data/geoImportShared.js` holds the error, limits, deadline and feature names they use.
|
||||
- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes each file's draw sets, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import.
|
||||
- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, that what the import draws matches Cesium's own `KmlDataSource` reading of the same file (positions, scale, heading, colours, widths, fills), large-file painted output and frame times. The QA scripts read what a file drew through `window.__gevGeoImport.drawn(id)`. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules.
|
||||
|
||||
### Recent Imagery (September 2026)
|
||||
|
||||
@@ -7652,7 +7767,7 @@ pins and share links already supply complete boxes.
|
||||
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
|
||||
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
|
||||
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
|
||||
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
|
||||
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
|
||||
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
|
||||
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
|
||||
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
|
||||
@@ -7681,7 +7796,7 @@ pins and share links already supply complete boxes.
|
||||
- Fleet model eligibility is distance-based with on-screen priority and hard caps (`MODEL_MAX`, `MODEL_MAX_ALL`) to avoid draw-call explosions. Each model owns its own `modelMatrix`; shared scratch matrices are forbidden because they caused stacking/flicker.
|
||||
- Tracked aircraft use standalone model primitives driven from the already-settled dead-reckoned display position, while the tracked Cesium entity remains billboard-backed so `viewer.trackedEntity` always has a ready bounding sphere.
|
||||
- Flights and military layers mirror the same tracking invariants: no warm-up freeze/jump, altitude-scaled framing, trail head glued to the displayed plane, no pull-out when switching targets, and no cross-layer orphan when switching between commercial and military tracks.
|
||||
- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. Arrival-rotation checks observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget that sits inside the one-second idle fallback, rather than assuming the 80 ms fleet cadence fits inside four rendered frames; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers.
|
||||
- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. The harness reads what the app draws through its own seams: what the camera follows through `src/data/followed.js`, icons from the draw port's icon sets as the renderer holds them, and models by their `{set, id}` pick ids. Arrival-rotation checks read the drawn rows' course (the icon sets turn each icon along it on the GPU every frame, so there is no CPU rotation pass to repair a stale nose) and observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers.
|
||||
|
||||
### TR-3B conversion Easter egg (August 2026)
|
||||
|
||||
@@ -7970,6 +8085,76 @@ easier to meet (detection is now on more often), but does not create it.
|
||||
above and the DISPLAY-rail entry below (was `OFF`).
|
||||
- Style shader starting params: CRT/NVG/FLIR pixelation `1.2` (just above the native `1.0` floor); thermal/FLIR ships an optional Ironbow "Predator" palette (`palette` uniform, default `0` = accurate grayscale).
|
||||
|
||||
## Renderer contract
|
||||
|
||||
`src/render/contract/` types the renderer contract, version `0`: nine ports
|
||||
(frame, globe, draw, camera, query, input, effects, credits and quality),
|
||||
plus the renderer itself. `PORTS` lists every member at run time, and
|
||||
`contract.test.mjs` keeps that list and the types in step.
|
||||
`src/render/stub/` is a renderer that draws nothing, with the default
|
||||
camera's exact maths. `src/render/conformance/` is the suite: logic checks
|
||||
in Node, plus camera traces recorded from Cesium's own `Camera` into
|
||||
`goldens/camera.json`. It also holds the reference scenes, whose views are
|
||||
checked against `goldens/visual/` on the `/dev/conformance/` page.
|
||||
`npm run qa:conformance` runs the logic checks on the Cesium renderer in
|
||||
headless Chromium, in CI too. After `destroy()` the Cesium renderer's
|
||||
handles do nothing, and `renderOnce` and `capture` reject. See
|
||||
[RENDERER-CONTRACT.md](RENDERER-CONTRACT.md).
|
||||
|
||||
### The application and its renderer
|
||||
|
||||
The application starts on whichever `RendererPlugin` it is given
|
||||
(`createStandaloneApplication({ renderer })`), and on Cesium when none is.
|
||||
`src/app/scene.js` loads the Cesium adapter (`src/render/cesium/application.js`)
|
||||
only then, with `import()`; the standalone page starts that load as it
|
||||
starts, beside its own setup. Outside `src/render/` no code reaches a
|
||||
renderer's own objects: the record of files that still did,
|
||||
`src/render/viewerAccessAllowList.json`, is empty.
|
||||
|
||||
- What every layer and tool is handed is the scene object
|
||||
(`createSceneHost`), bound to the renderer: its container, and whether it
|
||||
is destroyed. Everything else goes through the renderer's ports.
|
||||
- What a renderer's own plugin adds beside the contract (stale draw-command
|
||||
trims, inline panel drawing, the zoom-out guard, its own map engine, the
|
||||
detection overlay's occlusion probe, what QA scripts read) it hands through `src/render/applicationHooks.js`; the
|
||||
application uses each where given and does without where not.
|
||||
Renderer-only startup (Cesium's free-look limit, credit keyboard access)
|
||||
runs in that plugin's `create`.
|
||||
- The map stacks switch through the plugin's map engine, else the globe
|
||||
port (`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, Cesium
|
||||
ion imagery as `world` imagery, terrain as `world` terrain, or the
|
||||
ellipsoid where no keyless terrain is offered, and photoreal as the port's
|
||||
photoreal base. A photoreal base that fails to come back leaves the globe
|
||||
shown.
|
||||
- The renderer follows its container's size (`Renderer.resize`, from a
|
||||
`ResizeObserver`).
|
||||
- The credits: the Cesium renderer's plugin says it shows them in a display
|
||||
of its own (`ownCreditDisplay`; `#cesium-credits`), which it keeps. On the
|
||||
stub, the application shows what the credits port lists in its own line
|
||||
at the bottom left (`#gev-credits`, `src/ui/creditsView.js`): the inline
|
||||
credits on the line, the rest (the layers' data credits among them) in
|
||||
the "Data attribution" list it opens, a keyboard button with Escape to
|
||||
close.
|
||||
|
||||
`npm run qa:stub-boot` boots the whole application on the stub with only
|
||||
the contract's required members (`dev/stub-app/main.js`, served in place of
|
||||
`src/main.js` on the application's own page), headless. It fails if
|
||||
the credits line is not shown or its list is empty, if Cesium's code is
|
||||
requested (the one stylesheet `vite-plugin-cesium` links
|
||||
into every page is reported), on any page or console error, or if a data
|
||||
layer (flights, military aircraft, transit, traffic, CCTV, AIS vessels,
|
||||
weather radar and satellite, wind, satellites, FIRMS, wildlife, shipwrecks,
|
||||
news) fails to turn on or off. A
|
||||
feed's failed response (no key, no network) is reported, not failed;
|
||||
`--strict` also fails a layer that drew nothing, and `--all-capabilities`
|
||||
gives the stub every capability. CI runs it in the browser job.
|
||||
|
||||
`src/geo/` (export `./geo`) is the Cesium-free maths: WGS84, ECEF and
|
||||
geodetic conversions, surface normals and east-north-up frames, as plain
|
||||
`{x, y, z}` objects. It follows Cesium's formulas step for step, and
|
||||
`geo.test.mjs` checks it against Cesium. The stub renderer's maths is built
|
||||
on it.
|
||||
|
||||
## Operational Notes
|
||||
|
||||
- **Earthquake discs are STATIC geometry.** Every quake is a `CLAMP_TO_GROUND`
|
||||
@@ -8226,8 +8411,9 @@ easier to meet (detection is now on more often), but does not create it.
|
||||
Every failed read cancels its body and aborts its owned request, including
|
||||
declared and streaming byte-cap failures.
|
||||
- Development captures opened with `?trafficDebug=1` mint an interaction anchor
|
||||
from the exact `camera.changed` event that arms each debounced load, then emit
|
||||
scheduling-correlated User Timing entries for production `response.json`, road
|
||||
from the exact camera-port `changed` event that arms each debounced load,
|
||||
then emit scheduling-correlated User Timing entries for production
|
||||
`response.json`, road
|
||||
parse, dot construction, heat-line rebuild, and next-post-render
|
||||
boundaries. Every trace is paired with the exact camera-change that scheduled
|
||||
its load; mismatches are counted drops. Cesium's `moveEnd` remains a diagnostic
|
||||
@@ -8562,6 +8748,25 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security
|
||||
Policy unchanged. Ion attribution and Bing's per-tile credits are preserved;
|
||||
other ion imagery assets continue through the SDK's standard ion factory.
|
||||
|
||||
The imagery, terrain and 3D factories are the Cesium renderer's
|
||||
(`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the
|
||||
package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point
|
||||
there). The catalog, the default registry and the controller are
|
||||
Cesium-free: they reach those factories, and the scene operations a
|
||||
switch makes (imagery layers, terrain, the globe's visibility, tilesets),
|
||||
through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The
|
||||
Cesium plugin hands the application its own engine with each renderer it makes
|
||||
(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`),
|
||||
and the application scene loads the photoreal base through it too. A renderer
|
||||
whose plugin hands none switches through its globe port
|
||||
(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world
|
||||
imagery as `world` imagery, photoreal as the port's photoreal base (turned off
|
||||
while hidden, on again when shown), and world terrain, or without a key
|
||||
Re:Earth's keyless terrain as `quantizedMesh` terrain at its URL
|
||||
(`src/maps/keylessTerrain.js`), as the Cesium engine draws it; a renderer
|
||||
without the `terrain` capability keeps the ellipsoid. A viewer with no renderer bound gets the Cesium engine, with the
|
||||
other unbound ports, from the package's `./render/cesium/unbound` export.
|
||||
|
||||
The controller accepts other source registries without adding provider branches.
|
||||
Each instance caches source construction, ignores superseded scene changes and
|
||||
releases imagery layers/listeners on replacement. Destroy invalidates pending
|
||||
@@ -8629,7 +8834,12 @@ product's next frame until that frame loads (for at most eight seconds), so
|
||||
every frame shows. Hidden documents, reduced motion and unavailable imagery
|
||||
hosts suspend products. Re-enabling or
|
||||
restoring a host joins the retained history target. The wind row explicitly says
|
||||
“Forecast · does not follow history” while the observed clock is in history mode.
|
||||
“Forecast · does not follow history” while the observed clock is in history mode,
|
||||
unless a host follows the world clock for `wind` (`weatherClock.follows('wind')`):
|
||||
its source then follows the timeline and the row says nothing of it. In history
|
||||
mode, frame ages and the “Source observations delayed” status are measured from
|
||||
the timeline time rather than the wall clock, and the timeline readout shows the
|
||||
time alone; live, they count from now as before.
|
||||
The Weather panel's frame time shows the newest frame and its age while live
|
||||
(each product's newest, suspended products included), and the timeline time
|
||||
alone at a past time.
|
||||
|
||||
@@ -95,6 +95,11 @@ registry of source functions. Each receives `{ path, signal, maxBytes }` and
|
||||
returns `{ bytes: Uint8Array, mimeType }`. Custom transports must honor the
|
||||
signal, bound reads and return the real MIME type. They remain application code,
|
||||
not scene document fields. Without registrations, referenced sources fail closed.
|
||||
A standalone `SceneDirector` also passes `dataPacks.overlayHost`, the
|
||||
world-overlay host that draws pack world text such as a media pack's label (an
|
||||
object with `setEntries(sourceId, entries)` and `clearSource(sourceId)`);
|
||||
without it a media pack fails to load. `createApplicationTools` passes the
|
||||
application's shared host.
|
||||
|
||||
The portable session receives format adapters separately. Each adapter receives
|
||||
`{ pack, asset, anchors, signal }` and returns a resource with an idempotent
|
||||
|
||||
@@ -31,8 +31,9 @@ const layers = createInfrastructureLayers({
|
||||
| `overlayHost.clearSource` | `(sourceId)`; remove that source's overlay entries |
|
||||
| `registerEntityContext` | `(entity, metadata)`; register selectable feature metadata, including the owning layer and data source |
|
||||
| `selectEntityContext` | `(entity)`; select that registered feature |
|
||||
| `clearSelectedEntityContextForLayer` | `(layerId)`; clear selection only if owned by this layer |
|
||||
| `removeEntityContextsForLayer` | `(layerId)`; remove records owned by the layer on destruction or failed setup |
|
||||
| `clearSelectedEntityContextForLayer` | `(layerId, { evicted })`; clear selection only if owned by this layer; `evicted` when its feature left the data |
|
||||
| `removeEntityContextsForLayer` | `(layerId, { retainIds })`; remove records owned by the layer on destruction or failed setup, or those a new feature set no longer has |
|
||||
| `getSelectedEntityContext` | optional; `()` the selected record, so `replaceFeatures` keeps a selection the new set still has |
|
||||
| `governorRequestRender` | `(reason)`; request a frame through the existing render scheduler |
|
||||
|
||||
Each returned layer supports `init(viewer)`, `enable(viewer)`, `disable(viewer)`,
|
||||
@@ -45,18 +46,43 @@ Callbacks must be ready before enable and remain usable through destruction.
|
||||
|
||||
Disable retains the loaded dataset for reuse and clears selection and listeners.
|
||||
Concurrent enables share one load. Destroy is permanent, aborts pending fetches,
|
||||
discards late results, and clears the owned data source, context records, overlays,
|
||||
discards late results, and clears the owned draw sets, context records, overlays,
|
||||
input handler and listeners. The layer never creates an application context store,
|
||||
overlay host, viewer, or render scheduler. The consumer must resolve one compatible
|
||||
Cesium installation shared with its viewer; it must not bundle separate copies.
|
||||
|
||||
The layers draw, size their stems and fly the camera through the renderer's
|
||||
ports. A viewer the application has bound a renderer to needs nothing more; a
|
||||
Cesium viewer with no renderer bound loads
|
||||
`gods-eye-view/render/cesium/unbound` once first; until then the layer reports
|
||||
an error naming it, as it does for a dataset it cannot load.
|
||||
A selected feature is the context record its draw item carries as `meta`; the
|
||||
layer no longer sets the viewer's `selectedEntity`.
|
||||
Features keep their own simplestyle `fill`, `fill-opacity`, `stroke`,
|
||||
`stroke-opacity`, `stroke-width`, `marker-color` and `marker-size`, given as
|
||||
hex, `rgb()` or `hsl()` colours or by the CSS colour names the default renderer
|
||||
knows (it has no `rebeccapurple`, and spells `lavenderblush` `lavendar_blush`);
|
||||
a `marker-symbol` is stamped on the pin as the default renderer stamped it: a
|
||||
one-character string as bold upper-case text, any other value as the Maki icon
|
||||
of that id from the renderer's assets, the plain pin when the icon cannot be
|
||||
loaded. The assets are found as the renderer finds them from a page script: the
|
||||
`CESIUM_BASE_URL` global, else the folder `Cesium.js` is loaded from; a
|
||||
page bundling Cesium as modules sets `CESIUM_BASE_URL` for icon pins. Polygons with heights are drawn at them, outlined; points with
|
||||
heights stand their pin on the stem's tip. Edges follow rhumb lines.
|
||||
|
||||
`gods-eye-view/infrastructure/geojson` exports the lower-level
|
||||
`createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay
|
||||
helpers. `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers.
|
||||
helpers. Its options also take `loadFeatures({ signal })`, a loader resolving to
|
||||
GeoJSON features in place of `url`, and `featureColor(properties)`, a CSS colour
|
||||
per feature for its fill, stem, dot, pin and label accent. The layer it returns
|
||||
also has `dropCachedFeatures()`, so the next `enable` loads again, and
|
||||
`replaceFeatures(viewer, features)`, which draws a new feature set in place of
|
||||
the current one: the current one stays drawn until the new one is built, and
|
||||
stays if that fails (the call then rejects). `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers.
|
||||
Consumers use the package exports, which do not import standalone application
|
||||
globals.
|
||||
|
||||
Dataset files and source/license notices remain under `src/data/local_data/`.
|
||||
Their input counts are 4,352 datacenter features and 704 dam features. Cesium may
|
||||
expand multipart geometries into multiple entities; entity and stem counts are
|
||||
different measurements. This change does not refresh or relicense the datasets.
|
||||
Their input counts are 4,352 datacenter features and 704 dam features. A multipart
|
||||
geometry draws as several parts, each with its own stem; part and stem counts are
|
||||
different measurements from feature counts. This change does not refresh or relicense the datasets.
|
||||
+2
-1
@@ -34,7 +34,8 @@ hardware-rendered overlay scenes.
|
||||
|
||||
These frame rates were measured when the globe was capped at 60 FPS. It now
|
||||
draws at the display's refresh rate while anything moves and ticks at most 60
|
||||
times a second when parked (`src/renderGovernor.js`).
|
||||
times a second when parked (the Cesium frame port's idle rate,
|
||||
`IDLE_FRAME_RATE` in `src/renderGovernor.js`).
|
||||
|
||||
The initial-settle measurement is the more useful launch reference because it
|
||||
includes the first visual and data settling window. All three samples reached
|
||||
|
||||
@@ -0,0 +1,746 @@
|
||||
# Renderer contract
|
||||
|
||||
The renderer contract is what the application asks of a 3D renderer. The
|
||||
Cesium renderer draws the application through it, and the stub renderer
|
||||
stands in for it in tests. The contract is version `0`. Today the application
|
||||
still drives Cesium directly; later work moves the layers onto the contract
|
||||
one family at a time.
|
||||
|
||||
The package exports these modules:
|
||||
|
||||
| Export | What it is |
|
||||
| ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check |
|
||||
| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests |
|
||||
| `gods-eye-view/render/camera/events` | The camera port's events: `changed` per listener, `moveStart`/`moveEnd`, command hooks |
|
||||
| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison |
|
||||
|
||||
The pieces that do not depend on Cesium are exported too, each with its
|
||||
own `.d.ts`:
|
||||
|
||||
- `gods-eye-view/render/input/router`: the input port's leases and routing;
|
||||
- `gods-eye-view/render/stub/camera`, `.../stub/viewRectangle` and
|
||||
`.../stub/harness`: the stub's camera, its view rectangle and its
|
||||
conformance harness;
|
||||
- `gods-eye-view/render/motion`: where a moving icon is drawn at a time;
|
||||
- `gods-eye-view/render/vectorBase`: the vector base painter;
|
||||
- `gods-eye-view/render/iconSegment`: icon motion segments;
|
||||
- `gods-eye-view/render/recession`: how a set that recedes shrinks and
|
||||
fades its items toward the limb;
|
||||
- `gods-eye-view/render/windStreamlines`: the wind field's streamlines;
|
||||
- `gods-eye-view/geo/screenCluster`: screen-space clustering.
|
||||
|
||||
`src/render/neutralExports.test.mjs` checks that each is declared, that its
|
||||
names match what it exports, that it type-checks under strict TypeScript and
|
||||
that it imports no Cesium.
|
||||
|
||||
A camera controller takes the camera events from `render/camera/events`
|
||||
and the geodesy it needs (`geodesicAt`, `horizonFrom` and the rest) from
|
||||
`gods-eye-view/geo`, so it measures and fires exactly as the stub does. `CameraControllerFactory`
|
||||
(`camera.d.ts`) types such a controller: what it is given (`NativeCamera`)
|
||||
and what it gives back (the camera port and its two frame steps).
|
||||
|
||||
## Ports
|
||||
|
||||
A renderer is created by a `RendererPlugin` (`{ id, create(options) }`). It
|
||||
exposes nine ports, each typed in its own file in `src/render/contract/`:
|
||||
|
||||
| Port | File | Covers |
|
||||
| --------- | -------------- | ----------------------------------------------------------------------- |
|
||||
| `frame` | `frame.d.ts` | The render-on-demand loop, frame phases, continuous holds, scene time |
|
||||
| `globe` | `globe.d.ts` | Base (photoreal, terrain, vector, imagery), imagery layers, split, sky |
|
||||
| `draw` | `draw.d.ts` | Draw sets: icons, points, lines, shapes, models, quads, meshes, fields |
|
||||
| `camera` | `camera.d.ts` | Pose, views, flights, `lookAt`, follow, user controls, events, matrices |
|
||||
| `query` | `query.d.ts` | Picks, projection, rays, heights |
|
||||
| `input` | `input.d.ts` | Pointer events with their pick made, leases, stock behaviours |
|
||||
| `effects` | `effects.d.ts` | Screen styles, bloom, sharpen, screen modulation |
|
||||
| `credits` | `credits.d.ts` | Data credits owed |
|
||||
| `quality` | `quality.d.ts` | Quality knobs, device facts, frame signals |
|
||||
|
||||
Version `0` is still being shaped, and not only by additions. Members
|
||||
were removed or replaced (among them `camera.move`, `look`,
|
||||
`rotateAround` and `zoom`, now step views placed with `setView`;
|
||||
`query.sampleHeightNowMany`; `input.ctrlWheelZoom`, now the `ctrlWheel`
|
||||
zoom input), `depthFailColor` and `depthFailDash` became one `depthFail`
|
||||
style, and quality settings became detail only. The Cesium port and the
|
||||
stub follow those changes.
|
||||
|
||||
Some members and options were added to version `0` later. Each is
|
||||
optional:
|
||||
|
||||
- `globe.isGlobeVisible()` (capability `globeVisibility`) reads back whether
|
||||
the globe surface is shown, for code that holds only the scene.
|
||||
- `camera.followFrame()` (capability `followFrame`) reads the frame the eye
|
||||
is placed in, as a column-major 4×4 matrix to ECEF: a follow's own frame
|
||||
(east-north-up, or the orbit frame `autodetect` chose), a `lookAt`
|
||||
target's east-north-up frame, or the identity. `setView` keeps that frame
|
||||
while it places a world pose. A share link's follow offset is
|
||||
re-expressed in it, satellites included.
|
||||
- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that
|
||||
changes whenever what surface heights answer against changes (base,
|
||||
terrain or photoreal route swapped, the globe shown or hidden) and never
|
||||
otherwise (not on camera moves or tile loads), so the application can key cached
|
||||
heights by it. `isSettled('surface')` says whether that surface has
|
||||
loaded what is in view; a renderer without it answers `surface` as `base`.
|
||||
- `SurfaceShading` is `hillshade`: view-lit shading of the drawn terrain's
|
||||
own relief (the ellipsoid's curvature where terrain has no normals) that
|
||||
only darkens, at most `strength` opacity. The Cesium port draws it as a
|
||||
globe material it takes only while no one else holds the globe's
|
||||
material.
|
||||
- Fields: `windStreamlines` takes `alpha` (changed without a rebuild) and
|
||||
`paused`; `rasterShell` replaces `detailWindow` with
|
||||
`detail: {image, rectangle}`, a sharper image drawn in place of the base
|
||||
one, and says how shells stack, blend and update. `FieldHandle.on('drawn')`
|
||||
says once per spec or `update` that it is drawn, never while hidden. These
|
||||
change `fields` itself rather than add to it, so the renderer follows
|
||||
them where it lists `fields`. The Cesium adapter lists `fields` and
|
||||
draws `rasterShell` and `windStreamlines`. It reads the grid's samples as
|
||||
points, the first column at `rectangle.west` and the first row at
|
||||
`rectangle.north`, rows running south. Over the whole globe its paths
|
||||
wrap east and west; over part of it they seed inside the rectangle,
|
||||
equal-area, and stop at its edges.
|
||||
- `ModulationSector` gains `radius` and `floor` and says what it modulates:
|
||||
icons, points and models dimmed toward `floor` outside the band, the map,
|
||||
lines and shapes as they are, picks unchanged. Its pass is named
|
||||
`screenModulation`. This changes `screenModulation` itself; only the stub
|
||||
lists it, and the Cesium adapter does not draw it yet.
|
||||
- `camera.on('changed', cb, { threshold })` measures each listener by its
|
||||
own threshold under the capability `cameraChangeThreshold`; a renderer
|
||||
without it fires every `changed` listener at 0.5.
|
||||
- A line item's `depthFail` style, solid or dashed, draws the parts behind
|
||||
the surface (the Draw tool's rubber band is dashed there too); without one
|
||||
they are hidden.
|
||||
- A solid line's `outline.widthPx` is the outline's whole width, half on
|
||||
each side, inside the line's own width: an 8 px line with a 4 px outline
|
||||
is 2 px of outline, 4 px of colour and 2 px of outline, as Cesium draws
|
||||
it. The check `draw.lines.outline` pins it.
|
||||
- A shape's `lit` chooses shading by the renderer's fixed light (true) or a
|
||||
flat colour (false); omitted, extruded shapes are lit and the rest flat,
|
||||
as before. The Cesium port lights unclamped shapes only
|
||||
(clamped ones drape unlit). The `shapes-lit` scene draws both.
|
||||
- `SetSpec.recede` (`RecedeSpec`, for icon and model sets) makes a set's
|
||||
items shrink and fade toward the globe's limb, replacing the icon item's
|
||||
own `recede` flag. Its parameters (each optional: where receding starts
|
||||
as a share of the limb's distance, the scale and haze reached at the
|
||||
limb, the least focus × haze draws with, and the eye heights over which
|
||||
it all eases off for a view of the whole globe) and the maths are
|
||||
`render/recession`'s, so the renderer draws exactly those factors: an icon
|
||||
draws at its scale times the scale factor, and an icon or model at its
|
||||
alpha times `max(combinedAlphaFloor, focus × haze)`. `ModelItem.focus`
|
||||
dims a model as `IconItem.focus` dims an icon. It changes live
|
||||
(`setOptions`). The Cesium port draws a receding icon set on the GPU,
|
||||
the factors worked out in its shader, and fades a receding model set's
|
||||
models each frame before the scene draws, writing a model's colour again
|
||||
once its focus and haze move by more than 0.005. The check
|
||||
`draw.sets.recede` makes and changes both kinds, and
|
||||
`draw.sets.recede.models` reads a receding model's pixels: at focus 0.25
|
||||
it draws faded, and a `combinedAlphaFloor` of 1, set live, brings it back.
|
||||
- `SetSpec.drawOrder` stacks sets drawn over depth: a higher one draws over
|
||||
a lower one and is picked first; equal ones keep the order they were
|
||||
made in. The Cesium port stacks opaque icons and points by it;
|
||||
translucent ones blend order-independently there.
|
||||
- A rectangle shape's `rotation` (radians counter-clockwise) turns it about
|
||||
its centre in longitude and latitude, as a KML ground overlay turns, and
|
||||
its image fill turns with it. The Cesium port drapes image fills too, each
|
||||
on a ground primitive of its own.
|
||||
- `camera.controls.keepEarthFramed` (capability `keepEarthFramed`) stops
|
||||
the user's outward zooms at a whole-Earth view (about 40,000 km, or
|
||||
higher where a camera command left the eye) and, from high up, turns the
|
||||
view down toward the globe so the whole Earth stays in frame; camera
|
||||
commands are not held to it and end its turn. The Cesium port eases the
|
||||
view until the Earth's limb is 8° below its centre line above 300 km
|
||||
(`zoomOutGuard.js`). The application turns it on where a renderer has it.
|
||||
- `query.occlusionTest()` (capability `occlusionTest`) tests many points
|
||||
against the depth of the frames drawn without waiting for the GPU; the
|
||||
detection overlay leaves out the street vehicles it finds hidden. The
|
||||
Cesium port builds its test with `gods-eye-view/render/occlusion`
|
||||
(`createDepthOcclusionTest`, given a `DepthSource`: depth packed into
|
||||
RGBA8 or a depth texture, standard or logarithmic, with the view it was
|
||||
drawn from).
|
||||
- `RendererPlugin.applicationHooks(renderer)` hands the application what
|
||||
lies beside the contract (`ApplicationHooks`); see
|
||||
[The application and its renderer](#the-application-and-its-renderer).
|
||||
- `frame.renderNow()` throws when the frame fails to draw. With
|
||||
`{ifDue: true}` it runs one tick of the loop now, as the loop's own would
|
||||
(camera flight, input, clock), and draws only a frame that is due.
|
||||
|
||||
The Cesium port lists `gpuTiming` where its context has
|
||||
`EXT_disjoint_timer_query_webgl2`: while anyone listens to frame signals,
|
||||
each drawn frame is timed on the GPU from `preRender` to `postRender`, and a
|
||||
signal carries `gpuMs` of the newest frame whose timing has come back (a
|
||||
frame or more late; a disjoint timing is dropped). Without the extension it
|
||||
answers `gpuTiming: 'none'` and lists no capability. The check
|
||||
`quality.signals.gpuTiming` pins both.
|
||||
|
||||
The Cesium port lists `modelAtmosphere`: Cesium scatters drawn models
|
||||
through the atmosphere in the same stage as its distance fog, so models take
|
||||
it while `globe.sky`'s `fog` is on.
|
||||
|
||||
`weather` adds `globe.weather`: clouds, fog, haze, rain and snow drawn
|
||||
around the view, each a strength from 0 to 1, with the wind they drift on.
|
||||
`src/render/weather.js` (exported as `./render/weather`) keeps and clamps
|
||||
them (`mergeWeather`), and `./weather/effects`
|
||||
turns a weather observation into strengths (`deriveWeatherEffectProfile`).
|
||||
The application sets none, and the Cesium port does not list it. The strengths say what
|
||||
is observed (`clouds` is the fraction of the sky covered), not how it is
|
||||
drawn: the renderer draws clouds, fog and haze its own way, with clouds
|
||||
placed by scene time and the wind, and shading the ground under them where
|
||||
the sun lights it. The checks `globe.weather`, `globe.weather.drawn` and
|
||||
`globe.weather.sceneTime` (pixel checks) pin it.
|
||||
|
||||
How the sky, atmosphere, haze, lighting and the frame's tone mapping and
|
||||
exposure look is the renderer's own: `globe.sky` switches parts on and
|
||||
off, and no check compares colours. With
|
||||
`atmosphere`, `fog` and `lighting` off and clear weather a renderer applies
|
||||
none of its look, so the checks that read an exact colour (`bareSky` in
|
||||
`checks/ports.js`) set that sky first. The
|
||||
reference images under `src/render/conformance/goldens/visual/` are the
|
||||
Cesium renderer's own, for checking it against itself.
|
||||
|
||||
The Cesium port lists `followAutodetect`: an `autodetect` follow is
|
||||
Cesium's own AUTODETECT tracking frame, east-north-up on a still or slow
|
||||
target and an orbit frame (x along the inertial motion, z up) on a fast
|
||||
one. The stub's is a frame along the ground track, so an autodetect
|
||||
`viewFrom` reads differently on each; the check `camera.follow.autodetect`
|
||||
pins what both share (the range kept, north-up when still, the frame on the
|
||||
target standing up).
|
||||
|
||||
A follow target's `transitionS` makes the first framing a move instead of a
|
||||
jump: from its first frame the eye is in the target's frame, and over
|
||||
`transitionS` seconds of wall time it goes from where it stood to
|
||||
`viewFrom`, by the one rule in `src/render/camera/followTransition.js`
|
||||
(its offset and its view each turned and eased with smoothstep, the view
|
||||
ending on the target with no roll). The Cesium port, the stub and a camera
|
||||
controller import that rule rather than restating it. The tracked aircraft
|
||||
and followed trains use it with a `viewFrom` taken from the camera
|
||||
at the click: the eye's own view direction at its own range from the target,
|
||||
so neither changes and only the eye's place moves, sliding the target to the
|
||||
centre. The check `camera.follow.transition` pins it.
|
||||
|
||||
The Cesium port draws clamped shapes of every kind. A clamped outline is a
|
||||
draped line (a ground polyline a ring, under the shape's pick id; an outlined
|
||||
clamped shape is rebuilt on any change; a pulsing one pulses through its line's
|
||||
material, as an image fill pulses through its image material's colour). What
|
||||
a ground primitive cannot drape stands on the surface unclamped, the surface
|
||||
read when the set is built: an extruded shape from the lowest surface height
|
||||
under it up to its `extrudeHeight`, a wall with its foot on the surface under
|
||||
each position and its heights above it, and an image fill where the scene
|
||||
cannot drape materials (no depth textures). The check `draw.shapes.clamped`
|
||||
draws each.
|
||||
|
||||
The Cesium port takes every kind of `ImageRef` wherever an image is drawn
|
||||
(icons on billboards and on the GPU, line patterns, shape fills, quads and
|
||||
raster shells): a URL, SVG, a blob (by an object URL made once per blob,
|
||||
revoked once the blob itself has been collected; a material drawing a blob,
|
||||
a quad's among them, holds it while it lives, since a material loads its image
|
||||
on its first draw, even after the atlas slot it came from has a new one; a
|
||||
quad given another source lets the old blob go with its old material, once the
|
||||
frame has drawn), a
|
||||
keyed canvas, and an atlas slot as the image it holds (an icon waits for an
|
||||
unregistered slot; anything else refuses it). The check `draw.icons.images`
|
||||
draws each kind on still icons and in a set that recedes.
|
||||
|
||||
Icon sets with `cluster` (`ClusterSpec`) cluster the same way on every
|
||||
renderer: `clusterScreenPoints` (`src/geo/screenCluster.js`) over the shown
|
||||
icons in front of the eye and above the horizon, in the set's order, boxed at
|
||||
their drawn size, the last pass's clusters kept. A cluster draws one icon at
|
||||
the mean of its members' positions in place of its members (`icon(count)`,
|
||||
else a default badge with the count, at the seed's size). A pick on it
|
||||
answers one hit a member, seed first, each with the member's own `set`, `id`
|
||||
and `meta` and the cluster's position, so `pick` gives the seed and
|
||||
`drillPick` every member. Clusters are made again in the frames drawn after
|
||||
the camera moves or the set changes, never on a timer. The Cesium port draws
|
||||
a set's cluster icons in a billboard collection of their own and hides the
|
||||
members' billboards. A set on the GPU (`columns`, a set that recedes, or moving,
|
||||
proxy-picked or level-of-detail icons) clusters its rows where their segments
|
||||
(and ground) put them at the frame's motion-clock time, hiding the members'
|
||||
rows; while rows still move it clusters again every frame. The checks
|
||||
`draw.icons.cluster` and `draw.motion.cluster` (members coming to rest on
|
||||
their segments) draw a cluster, pick it, and part it by moving in.
|
||||
|
||||
Icon sets on the Cesium GPU path draw what its billboards draw: pixel offsets, `bottom` and `top` anchors, screen and axis
|
||||
rotations (turned as Cesium's billboards turn), `fadeByDistance`,
|
||||
`displayRange`, and `clampGround` / `relativeGround` heights. Each row reads
|
||||
these from a float texture by instance, so the 16 vertex attributes hold;
|
||||
WebGL 1 has no such fetch and refuses them. A clamped row stands on the
|
||||
ground taken between the heights under its segment's two ends, sampled after
|
||||
a frame draws, 256 ends a frame across the port's sets: loaded terrain first,
|
||||
then (but for `clampTo: 'terrain'`) the drawn surface, eight a frame. They are
|
||||
sampled again when the globe's tiles finish loading and, clamped to more than
|
||||
terrain, every 5 s. The check `draw.motion.look` draws each on a moving icon.
|
||||
|
||||
A set's `blend` holds for every kind of set: omitted, opaque parts draw
|
||||
opaque with depth writes and translucent ones blend without; `opaque` draws
|
||||
every item opaque, its alpha ignored, with depth writes; `translucent` blends
|
||||
every item without depth writes, even at alpha 1; `additive` adds each item's
|
||||
colour times its alpha, without depth writes and still depth-tested. It
|
||||
changes live (`setOptions`, from the next frame; models do not load again).
|
||||
The Cesium port builds billboards and points in Cesium's blend options, and
|
||||
turns every set's draw commands to its blend each frame before the scene
|
||||
sorts them (`src/render/cesium/setBlend.js`): additive ones draw after every
|
||||
opaque command and before the translucent pass, which blends
|
||||
order-independently and would undo the addition; ground commands keep their
|
||||
pass and stencil and only blend differently. The checks `draw.sets.blend`
|
||||
(points, icons, lines, shapes) and `draw.models.blend` read the pixels.
|
||||
|
||||
A model item may bring its glTF bytes (`gltf`): the renderer builds it from
|
||||
them and never fetches its `url`, which stays the model's identity, so a
|
||||
model set loaded up front (the procedural fleet models, GLBs compressed with
|
||||
`EXT_meshopt_compression` and `KHR_mesh_quantization`) is never fetched
|
||||
mid-session. `axisScale` stretches a model along its own glTF axes on top of
|
||||
`scale` (a hull drawn at its reported beam), `maskColor` paints a colour
|
||||
where the model's `_TINT` vertex attribute marks it (a vehicle in its route's
|
||||
colour), and `clip: 'belowOrigin'` draws only what is above the horizontal
|
||||
plane through its position (a hull above its waterline). Each changes live.
|
||||
The Cesium port passes the bytes as the model's `gltf` with its url as the
|
||||
base path, scales its model matrix along the axes Cesium's glTF axis
|
||||
correction turns them to, paints the mask in a custom shader per colour
|
||||
(unlit under `unlit` shading, left out under `thermal`), and clips with a
|
||||
clipping plane through the model's origin. The checks `draw.models.bytes`
|
||||
and `draw.models.fleet` cover them.
|
||||
|
||||
The Cesium port draws timed imagery (`imageryFrames`): a layer given a timed
|
||||
source hides its own imagery and draws each frame its clock shows as a Cesium
|
||||
imagery layer just above it (in `blend` mode the later frame over the earlier
|
||||
at its share of the way, as a layer's `alpha` blends), with the next
|
||||
`prefetch` frames (1 by default) loading unseen at alpha 0. A video source is
|
||||
seen every 250 ms of each segment (at most 1,200 times a segment), each tile
|
||||
the video its URL names for it (or one video over the layer's rectangle for a
|
||||
`single-image` layer), seeked to the time's share of its length. A layer
|
||||
keeps its 48 most recently seen tile videos; a tile waiting on one it lets
|
||||
go, or on a seek that takes over 10 s (60 s for the seek past its end that
|
||||
learns the length of a video that does not state it), fails rather than
|
||||
waiting. A video whose seek did not end is let go, so the next tile loads a
|
||||
fresh one; one that failed to load (or to say how long it is) fails its tiles
|
||||
at once for 3 minutes, then loads again. `frameReady`
|
||||
names the nearest frame's time once every globe tile drawn shows that
|
||||
frame's own imagery (`src/render/cesium/imageryFrames.js`). The checks
|
||||
`globe.imagery.frames` and `globe.imagery.video` cover both.
|
||||
|
||||
Every Cesium draw set takes `setColumns` (`columns`): icon sets on the GPU,
|
||||
any other as the rows the columns make over the items it holds, each row the
|
||||
item of that id with the columns' fields over it, replacing every item as
|
||||
`set` does (`columnRows` in `src/render/cesium/draw.js`, as the stub does).
|
||||
`renderer.shape` holds on Cesium.
|
||||
|
||||
The Cesium port also draws `pattern` line styles (the image repeated
|
||||
`repeat` times along the line, in the translucent pass; draped too), lines in the
|
||||
`inertial` frame (turned each frame by the set's motion clock, a depth-fail
|
||||
style included; never batched; a draped one is draped where the sky is,
|
||||
turned into the fixed frame, and draped again each second of its clock),
|
||||
segment colours and shows
|
||||
on lines of every mode and style (a draped solid line as ground instances,
|
||||
any other as a primitive a segment with a material of its own, recoloured
|
||||
and shown in place; an arrow's head on its last segment, a pattern keeping
|
||||
its image; the check `draw.lines.segmentStyles`), and image fills on clamped ellipses, cut finely so a
|
||||
round image (the launch pad zone's rim) runs round. A clamped colour fill
|
||||
whose geometry alone changes (an annotation's target ring, resized as the
|
||||
camera climbs) is drawn alone where it now is, in the same frame. A hidden
|
||||
line that cannot settle into a static batch leaves its polyline collection
|
||||
until it shows again, since the collection draws every line it holds.
|
||||
|
||||
The renderer itself (`renderer.d.ts`) adds capture, pixel reads, settling,
|
||||
resize, context loss and `destroy`. `common.d.ts` holds the shared shapes
|
||||
(ECEF positions, colours, listener semantics) and the capability list.
|
||||
|
||||
The rules that hold everywhere:
|
||||
|
||||
- **The application keeps its own records.** It never reads a renderer to learn its own
|
||||
state, only what the renderer measures: picks, depth, heights and
|
||||
readiness.
|
||||
- **Capabilities.** An optional member (`?`) exists only with the capability
|
||||
its documentation names first. A required member that names a capability
|
||||
always exists, and without the capability it answers null or empty.
|
||||
Quality support is listed by `quality.knobs()`, not by capabilities.
|
||||
- **Picks see the scene before effects.** A style that moves pixels does not
|
||||
move what is picked, so the application maps a pointer through its own
|
||||
style first
|
||||
(`src/input/sensorPick.js`). A bounded `drillPick` (`limit`) also bounds
|
||||
its work: it looks through at most `max(limit, 16)` things under the
|
||||
pointer.
|
||||
- **Heights are physical.** All heights are metres above the ellipsoid,
|
||||
unexaggerated. Only drawing follows exaggerated terrain.
|
||||
- **Listeners** run in subscription order. A listener removed during
|
||||
delivery does not run; one added during delivery runs from the next event.
|
||||
A listener that throws is reported to the renderer's `error` event, or to
|
||||
the platform's `reportError` when nothing listens for errors. The other
|
||||
listeners, and the frame, still run.
|
||||
- **The frame order is fixed:** camera flight → input → camera `changed` →
|
||||
follow → `preUpdate` → move detection → `preRender` → render →
|
||||
`postRender`, the default renderer's own. A camera move made by follow or
|
||||
in `preUpdate` is reported by `changed` on the next frame.
|
||||
- **Destroy ends everything.** After `destroy()`, every handle does
|
||||
nothing: a set's or field's methods neither draw nor throw, and a set or
|
||||
field asked for afterwards is such a handle. The same holds for one handle
|
||||
after its own `dispose()`. `frame.renderOnce()` and `capture()` reject
|
||||
with a "renderer destroyed" error, and a `renderOnce` still waiting at
|
||||
destroy rejects rather than hang.
|
||||
- **Results are read-only.** `camera.matrices()` and `followFrame()` may
|
||||
hand the same arrays again while they hold, and hand new ones once they
|
||||
change, so one kept from an earlier frame stays as it was.
|
||||
- **Reading the frame.** `capture()` and `readPixels()` read the last
|
||||
presented frame; neither draws one of its own when the frame is kept.
|
||||
Whether to keep the drawing buffer is the renderer's own business, not a
|
||||
creation option. The creation options a renderer takes are `msaa`, `sky`
|
||||
and `time`, set before the first frame, and `clock`, which its frame
|
||||
ticks, the camera's `moveEnd` wait, its input and its flights read, and
|
||||
its inertia where the renderer times that itself: on Cesium, inertia
|
||||
keeps Cesium's own timing.
|
||||
- **Leases:** a tool takes the pointer with `claimPointer`. With `grab`, it
|
||||
takes only the presses it grabs on `down`; the rest, and wheel and pinch,
|
||||
stay with the camera and everyone else. The newest claim takes over: it
|
||||
ends the previous lease, whose `onLost` is called once, after the new lease
|
||||
holds the pointer, so that tool turns itself off. A lease its holder
|
||||
releases is never told, and an ended lease's release frees nothing.
|
||||
The application's own tools (Draw, the imagery box, Directions) claim through
|
||||
`src/data/inputOwnership.js`, which the input dispatcher bridges onto the
|
||||
port, so a claim on either takes over from the other. The bridge's lease
|
||||
grabs no press: the dispatcher decides who hears each event when it
|
||||
arrives, and the renderer's stock select and double-click follow run
|
||||
unless a tool holds them off.
|
||||
|
||||
`src/render/contract/index.js` lists every member of every port in `PORTS`,
|
||||
along with `CAPABILITIES`, `FRAME_STEPS` and `QUALITY_KEYS`.
|
||||
`checkRendererShape(renderer)` names each required member that is missing,
|
||||
and each capability member present without its capability.
|
||||
`contract.test.mjs` type-checks the contract under strict TypeScript, and
|
||||
fails when `PORTS` and the types disagree on a single member.
|
||||
|
||||
### The vector base painter
|
||||
|
||||
`vectorBase` (`BaseSpec.vector = { styleUrl }`) draws a MapLibre style
|
||||
document's vector tiles as the globe's base. They are painted in shared,
|
||||
Cesium-free code, `src/render/vectorBase/`, which the renderer draws as
|
||||
imagery:
|
||||
|
||||
- `loadVectorStyle(styleUrl, fetch)` fetches the style and the TileJSON its
|
||||
vector sources name (a source's `url`; inline `tiles` are used as given,
|
||||
resolved against the style), compiles every layer, and returns the
|
||||
sources (tile templates, `minzoom`, `maxzoom`, `xyz` or `tms`), the layers
|
||||
it draws, the background, the sources' attributions, and `skipped`: each
|
||||
layer it does not draw, with why.
|
||||
- `paintVectorTile(style, z, x, y, { size, fetch, signal, canvas })` paints
|
||||
one Web Mercator tile on a canvas at style zoom `z + log2(size / 512)` (at
|
||||
least 0). A source past its `maxzoom` is drawn from its deepest tile,
|
||||
overzoomed; below its `minzoom` it draws nothing. Decoded source tiles
|
||||
(gzipped ones inflated) are kept per style, the last 128.
|
||||
|
||||
What it draws of the style specification:
|
||||
|
||||
- Layers: `background` (`background-color`, `background-opacity`); `fill`
|
||||
(`fill-color`, `fill-opacity`, `fill-outline-color`); `line`
|
||||
(`line-color`, `line-width`, `line-opacity`, `line-dasharray`,
|
||||
`line-cap`, `line-join`, and `line-gap-width` drawn as one line the full
|
||||
cased width); `circle` (`circle-radius`, `circle-color`,
|
||||
`circle-opacity`, `circle-stroke-width`, `circle-stroke-color`,
|
||||
`circle-stroke-opacity`); `symbol` text only (`text-field` as an
|
||||
expression or with `{name}` tokens, `text-size`, `text-font` as the
|
||||
system's sans-serif or serif in bold or italic as its name says,
|
||||
`text-color`, `text-opacity`, `text-halo-color`, `text-halo-width`,
|
||||
`text-transform`, `text-anchor`, `text-offset`, `text-max-width`).
|
||||
Layer `minzoom`, `maxzoom`, `filter` and `visibility` hold.
|
||||
- Labels are painted into the tiles: top layer first (within a layer, its
|
||||
features in their order in the tile), each clear of those placed before
|
||||
it and wholly inside its tile (one across a tile edge is
|
||||
left out). A point labels at itself, a line halfway along it (level, not
|
||||
along the line), a polygon at its outer ring's bounding-box centre.
|
||||
- Filters in both syntaxes (legacy, with `$type` and `$id`, and
|
||||
expressions). Legacy `{stops, base, property, type}` functions
|
||||
(exponential, interval, categorical, identity; not zoom-and-property);
|
||||
one without a `type` is exponential on a property that interpolates (a
|
||||
number or colour) and interval on any other (`line-cap`, `line-join`,
|
||||
`text-font`, `text-transform`, `text-anchor`, ...), as the specification
|
||||
says. `has`, `get` and legacy filters see a feature's own properties only.
|
||||
- Expressions: `literal`, `get`, `has`, `id`, `geometry-type`, `zoom`,
|
||||
`properties`, `!`, `all`, `any`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`,
|
||||
`case`, `match`, `coalesce`, `step`, `interpolate` (`linear` and
|
||||
`exponential`; `-hcl` and `-lab` blend in RGB), `to-string`,
|
||||
`to-number`, `to-boolean`, `to-color`, `number`, `string`, `boolean`,
|
||||
`rgb`, `rgba`, `concat`, `format` (its text), `upcase`, `downcase`,
|
||||
`length`, `at`, and arithmetic (`+ - * / % ^`, `min`, `max`, `abs`,
|
||||
`floor`, `ceil`, `round`, `sqrt`, `ln`, `log10`, `log2`).
|
||||
- Skipped whole: `fill-extrusion`, `raster`, `hillshade`, `heatmap` and
|
||||
`sky` layers; layers on raster sources; layers setting a pattern
|
||||
(`fill-pattern`, `line-pattern`, `background-pattern`), `line-offset`,
|
||||
`line-gradient` or a translation; layers whose values use an expression
|
||||
not listed (or are malformed). As MapLibre does, a paint or layout value
|
||||
that cannot be evaluated for a feature (a type that does not fit, a
|
||||
`step` or `interpolate` over what is not a number) or is not of the
|
||||
property's kind (null; not a finite number, a string included, where a
|
||||
number is needed; not a colour `parseColor` reads, which takes the CSS
|
||||
colour names; not one of the property's keywords) is the property's
|
||||
default; a legacy function's miss is its `default`, else the property's.
|
||||
A feature whose filter cannot be evaluated is left out. Nothing
|
||||
unsupported throws.
|
||||
- Ignored: icons (`icon-image`, sprites: a symbol layer draws its text
|
||||
alone), text along lines (drawn level), `glyphs` (system fonts), and any
|
||||
other paint or layout property not listed above.
|
||||
|
||||
The Cesium port loads the style before the base changes (a style that fails
|
||||
leaves the base as it was; a later `setBase`, or disposal, aborts the load and
|
||||
the overtaken call changes nothing, resolving with `imagery: []` and
|
||||
`settled: false`; `settled` is whether, when the call resolves, its base is
|
||||
still the one drawn and has settled, so an earlier call that resolves while a
|
||||
later call's style is still loading, or after that style fails, is settled,
|
||||
and one that resolves after a later call changed the base is not), draws it as Web Mercator imagery under the
|
||||
base's other imagery (`src/render/cesium/vectorBase.js`, 256 px tiles to
|
||||
level 20, transparent where the style paints no opaque background; a tile
|
||||
whose request is cancelled, its layer removed, is not painted), and credits each source's attribution as plain text. The stub
|
||||
loads the style and paints nothing. The check `globe.base.vector` serves a
|
||||
style and a tile from data URLs and reads the drawn fill.
|
||||
|
||||
### What a renderer does, by role
|
||||
|
||||
A renderer is more than a drawing surface: it is a whole globe engine. The
|
||||
application keeps the data (providers, records, layers and their
|
||||
behaviour). The renderer owns everything from a source spec or a draw set
|
||||
down to the pixels. The ports follow the API's shape; `ROLES` in
|
||||
`src/render/contract/index.js` names what the engine behind them does, and
|
||||
puts every member of `PORTS` in exactly one role. It changes no member.
|
||||
|
||||
| Role | What it does | Members |
|
||||
| --------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `surface` | Streams, decodes and builds the globe from map sources: imagery, terrain, photoreal 3D tiles, draped layers | `globe`, `imageryLayer`, `credits` |
|
||||
| `scene` | Draws the application's data as keyed, retained sets | `draw`, `drawSet` |
|
||||
| `view` | Places and moves the camera, hands pointer input to the application | `camera`, `flight`, `input`, `lease` |
|
||||
| `queries` | Picks, surface positions and heights, rays, projection, occlusion | `query` |
|
||||
| `look` | Sky and atmosphere, surface shading, per-layer lighting, styles and screen effects | `effects`, `globe.sky`, `globe.weather`, `globe.setSurfaceShading`, `imageryLayer.lit` |
|
||||
| `host` | Canvas and life cycle, the frame loop and scene time, quality, capture, settling | `renderer`, `frame`, `quality` |
|
||||
|
||||
An entry is a port or a `port.member` prefix; the most specific one wins, so
|
||||
`roleOf('globe', 'sky.set')` is `'look'` while `roleOf('globe', 'setBase')`
|
||||
is `'surface'`. `contract.test.mjs` fails when a member has no role, when
|
||||
two roles claim the same entry, or when an entry names no member.
|
||||
|
||||
## Moving code onto the contract
|
||||
|
||||
Two ratchet tests keep code that has moved onto the contract from drifting
|
||||
back to Cesium. Both lists only ever shrink.
|
||||
|
||||
- `src/render/cesiumAllowList.json` lists the files outside the Cesium
|
||||
adapter (`src/render/cesium/`) that may still import or be handed Cesium
|
||||
(`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list
|
||||
when it no longer drives Cesium at all; nothing is added. The list is
|
||||
empty: no file outside the adapter reaches Cesium. Two files name
|
||||
the adapter by design and are not on it: the application scene
|
||||
(`src/app/scene.js`), the composition root that picks the default renderer
|
||||
when it is given none, may import `src/render/cesium/application.js` (only
|
||||
then, so a page on the stub never loads Cesium) and nothing else of
|
||||
the adapter; the conformance page (`dev/conformance/main.js`) may import the
|
||||
adapter's harness and scene renderer. The test names both
|
||||
(`ADAPTER_ENTRIES`), and that list is never grown.
|
||||
- `src/render/viewerAccessAllowList.json` counts, per file off that list,
|
||||
the Cesium-shaped accesses through the viewer it still makes (none: the
|
||||
list is empty, so no file may make one)
|
||||
(`src/render/viewerAccess.test.mjs`): the viewer's `entities`,
|
||||
`dataSources`, `scene`, `camera`, `clock`, `imageryLayers`,
|
||||
`terrainProvider`, `trackedEntity` and `canvas`, and the scene's
|
||||
`primitives`, `pick`, `drillPick`, `pickPosition`, `globe`, `preRender`,
|
||||
`postRender`, `preUpdate`, `postUpdate`, `canvas`, `requestRender` and
|
||||
`camera`, written plainly, with `?.`, in brackets or destructured.
|
||||
`viewer.container` is a DOM element and does not count; reach the canvas
|
||||
through `canvasOf(viewer)`. Comments and tests do not count.
|
||||
`src/testSupport/viewerAccess.mjs` is the matcher.
|
||||
A file may not make more accesses than recorded (a file not listed may
|
||||
make none), and a count higher than the file now needs fails too. So a
|
||||
file that leaves the Cesium list must port its viewer accesses in the
|
||||
same change: it cannot be added to the count. After
|
||||
porting accesses away, run `node scripts/viewer-access-baseline.mjs` (or
|
||||
`--check` to see what it would change): it lowers counts and drops
|
||||
entries, and never adds or raises one.
|
||||
|
||||
## The application and its renderer
|
||||
|
||||
The application runs on a renderer with only the contract's required
|
||||
members (the stub proves it below); nothing outside `src/render/<renderer>/` asks which renderer it runs
|
||||
on (no `renderer.id`, no engine type, no engine object's presence).
|
||||
|
||||
- **The scene object.** `createApplicationScene` (`src/app/scene.js`) takes a
|
||||
`RendererPlugin`, or a promise of one (default: Cesium, imported only then;
|
||||
`loadDefaultRenderer` starts that import as the standalone page starts),
|
||||
creates the renderer in the page's container, and hands every layer and
|
||||
tool the application's own scene object (`createSceneHost` in
|
||||
`src/render/rendererOf.js`): the container and `isDestroyed()`, bound to
|
||||
the renderer. Code reaches the renderer's
|
||||
ports through it (`findCamera`, `drawOf`, `canvasOf`...).
|
||||
- **What only the Cesium renderer needs at startup** is done in its
|
||||
plugin's `create`: the free-look height limit and keyboard access to its
|
||||
credits' expand link (`src/render/cesium/appRenderer.js`).
|
||||
- **What a plugin may hand the application beside the contract** is its
|
||||
`applicationHooks(renderer)` (`ApplicationHooks`,
|
||||
`src/render/contract/renderer.d.ts`), asked once as the scene creates the
|
||||
renderer and recorded for the application (`src/render/applicationHooks.js`):
|
||||
a map engine of its own, stale command trimming, whether an entity is its
|
||||
own, whether it shows its credits in a display of its own
|
||||
(`ownCreditDisplay`; otherwise the application's own line,
|
||||
`src/ui/creditsView.js`, shows the credits port's list), and what QA
|
||||
scripts read from `window.__godsEyeView` (Cesium's viewer there, for the
|
||||
scripts that drive it). Each is optional, none is a contract member, and
|
||||
a renderer without them runs the application without that behaviour.
|
||||
- **What the renderer should do is in the ports**, each through the
|
||||
application's own code: outward zooms stop at a whole-Earth view that
|
||||
stays framed (`camera.controls.keepEarthFramed`, which the scene turns
|
||||
on; Cesium's is `src/render/cesium/zoomOutGuard.js`); the detection
|
||||
overlay leaves out street vehicles something stands in front of through
|
||||
`query.occlusionTest()` under the `occlusionTest` capability (the GPU
|
||||
probe is `src/render/occlusion/depthProbe.js`, which Cesium's
|
||||
`src/render/cesium/sceneOcclusionProbe.js` feeds; without it every such
|
||||
vehicle's bracket shows); and an inline panel whose host stops animation
|
||||
frames keeps running through `resize` and `frame.renderNow({ifDue: true})`
|
||||
(`src/app/panelRendering.js`), so flights, input and the clock go on as
|
||||
in the renderer's own loop, stopping at a frame that throws.
|
||||
- **The map stacks** switch through the renderer's own map engine when its
|
||||
plugin hands one, else through its globe port (`src/maps/globeEngine.js`);
|
||||
see `docs/CURRENT-STATE.md` § Map source factories and coordination.
|
||||
- **The proof.** `npm run qa:stub-boot` (`scripts/qa-stub-boot.mjs`) serves
|
||||
the application's page with `dev/stub-app/main.js` as its entry: the whole
|
||||
application on the stub with no capability at all. It fails when the page
|
||||
requests any Cesium module or asset, when the credits line is not shown
|
||||
with its data credits, on a page or console error, or when a
|
||||
data layer (flights, military aircraft, transit, traffic, CCTV, vessels,
|
||||
weather, wind, satellites, FIRMS, wildlife, shipwrecks, news) fails to
|
||||
turn on or off; `--strict` also fails
|
||||
a layer that draws nothing on the stub (it needs the live feeds).
|
||||
`src/app/scene.test.mjs` runs the scene itself on the stub in Node.
|
||||
|
||||
## The stub renderer
|
||||
|
||||
`createStubRenderer({ capabilities, viewport, time, container })` implements
|
||||
every port in memory and draws nothing. Given a `container` (in a page), its
|
||||
canvas is a real canvas filling it, which `resize()` follows; otherwise a
|
||||
stand-in that takes event listeners. `createStubRendererPlugin(options,
|
||||
onCreate)` is the stub as a `RendererPlugin`. It has:
|
||||
|
||||
- the default camera's exact maths: views, `lookAt`, flights with their
|
||||
height arc and easing, `changed` thresholds and follows;
|
||||
- picks against what was drawn, or a scripted table;
|
||||
- scripted heights;
|
||||
- a virtual clock that nothing advances on its own;
|
||||
- models that load at once, but for urls under `stub-fail:`
|
||||
(`STUB_FAILING_MODEL_SCHEME`), which fire `loadFailed` instead of `ready`
|
||||
(they are still picked where they are).
|
||||
|
||||
`renderer.testing` drives it with `tick()`, `advance(ms)`, `pointer(type, x, y)`,
|
||||
`scriptPicks`, `setHeights` and `cacheHeight`, and records its calls.
|
||||
`testing.drawnPosition({ set, id }, aheadMs)` is where it draws an item now
|
||||
(or `aheadMs` from now), so a
|
||||
camera controller over the stub can follow drawn items there.
|
||||
A listener that throws with nothing subscribed to `error` goes to
|
||||
`reportError`; Node has none, so the stub rethrows it on a microtask and
|
||||
`node:test` fails the running test. A test that expects a throw subscribes
|
||||
to `error`.
|
||||
The stub passes the whole conformance suite (`src/render/stub/stub.test.mjs`).
|
||||
|
||||
## Conformance suite
|
||||
|
||||
`runConformance(harness)` runs every check against the Cesium renderer or
|
||||
the stub through the contract alone and reports each one as passed, failed or skipped. It runs in
|
||||
Node and in a browser page. A harness tells the suite how to drive the
|
||||
renderer under test:
|
||||
|
||||
- `create({ viewport, capabilities })`;
|
||||
- `frame(r)`: one frame, 1/60 s on a virtual clock;
|
||||
- `now(r)` and `toEcef(p)`;
|
||||
- `tolerance` and `flightPaths`.
|
||||
|
||||
Optional members widen what is checked: `pointer` for synthetic input,
|
||||
`cameraInput` (the camera answers that input: the drag and wheel traces
|
||||
run), `scriptHeights`, `resizeContainer` (sizes the element the renderer
|
||||
fills, for the `resize` check, which skips without it), `assets.model`, and
|
||||
`assets.missingModel` (a model url that fails to load, for the `loadFailed`
|
||||
check). `pixels: false` says
|
||||
the renderer draws nothing but models into its pixels, as the stub: the
|
||||
checks that read drawn icons, lines and fields then skip. Without it they
|
||||
run, and the renderer fails them if it draws nothing there.
|
||||
|
||||
There are two layers of checks.
|
||||
|
||||
**Logic checks** run in CI. They cover:
|
||||
|
||||
- the shape check;
|
||||
- listener semantics and the frame loop;
|
||||
- draw-set bookkeeping, picks and the `meta` round-trip;
|
||||
- projection, rays and heights;
|
||||
- leases and click picks;
|
||||
- imagery order, sky, styles, credits and quality knobs;
|
||||
- the camera traces.
|
||||
|
||||
**Camera traces.** `cameraScripts.js` lists camera scripts in the contract's
|
||||
terms. `scripts/record-camera-goldens.mjs` runs them on Cesium's own
|
||||
`Camera`, headless, on a virtual clock, and writes
|
||||
`src/render/conformance/goldens/camera.json`. A renderer under test must
|
||||
match each recorded pose:
|
||||
|
||||
- within 1 mm in position, 1e-9 in unit vectors and angles, and 1e-3 px on
|
||||
screen;
|
||||
- with every flight ending within one frame of the recording.
|
||||
|
||||
Some scripts move the camera by user input: left, middle, Shift and Ctrl
|
||||
drags, and wheels in pixel and line mode. The recorder runs those on
|
||||
Cesium's own `ScreenSpaceCameraController`, fed the DOM events the script
|
||||
describes, with `Date` on the virtual clock too (its coasting reads it). A
|
||||
renderer under test gets them through its harness's `pointer`, a wheel as
|
||||
the input port's lines. Only a harness with `cameraInput` runs them: the
|
||||
stub's camera takes no gestures, so it skips them; a camera controller
|
||||
over the stub would run them. `cameraPort.test.mjs` runs them on Cesium's
|
||||
controls under the Cesium camera port, each wheel sent back as lines.
|
||||
|
||||
A wheel's `delta` is lines as Cesium counts them: a pixel-mode wheel at
|
||||
40 px a line and a page at 3 lines (`src/render/input/wheel.js`). Turning
|
||||
lines back into pixels at 40 px a line gives Cesium's own wheel in every
|
||||
mode, so a controller that does that zooms as Cesium does in Chrome (pixel
|
||||
mode) and Firefox (line mode) alike.
|
||||
|
||||
`src/render/cesium/cameraGoldens.test.mjs` fails when the installed Cesium
|
||||
no longer records the committed traces. After a Cesium upgrade or a script
|
||||
change, run `node scripts/record-camera-goldens.mjs` and review the diff.
|
||||
|
||||
**Visual checks** run in the browser. The reference scenes
|
||||
(`src/render/conformance/scenes.js`) are built from contract calls only:
|
||||
|
||||
- one scene per primitive family;
|
||||
- a city scene;
|
||||
- a calibration path from orbit down to the street.
|
||||
|
||||
The scenes load nothing from the network.
|
||||
|
||||
`npm run dev`, then open `/dev/conformance/`. The page can:
|
||||
|
||||
- **Run logic suite (stub)** runs the logic checks in the browser.
|
||||
- **Record references** draws every scene the chosen renderer supports.
|
||||
It saves each view to `src/render/conformance/goldens/visual/`, through a
|
||||
dev-server-only endpoint.
|
||||
- **Check scenes** draws the scenes again and compares each capture with its
|
||||
reference. Pixels are compared as pixelmatch compares them: by YIQ
|
||||
difference (threshold 0.1), with antialiasing in either image excused. A
|
||||
capture matches when at most 250 pixels are unexcused and at most 2 are
|
||||
solid (a differing pixel whose four neighbours differ too). Between them
|
||||
the two catch a dropped 4 px point, a dropped 2 px line and a 1 px shift
|
||||
of the view, and pass any MSAA setting. A change nowhere 3 px thick (a
|
||||
thin line gone, an item moved a pixel or two) that covers at most 250 px
|
||||
passes. `visual.js` has the measurements.
|
||||
The page shows the capture, the reference and the difference side by side.
|
||||
|
||||
`window.conformance.runScenes()` and `runLogic()` do the same from a script.
|
||||
|
||||
`npm run qa:conformance` runs the logic checks on the Cesium renderer in
|
||||
headless Chromium (software WebGL, no GPU needed). It starts its own Vite
|
||||
server unless given `--url`; `--only id,id` runs just those checks and
|
||||
`--json path` writes the report. It fails on any failed check and on any
|
||||
skip it does not expect (`query.heights`, which needs scripted heights, is
|
||||
the one it expects). CI runs it in the `street-level-browser` job.
|
||||
Browser checks use the chrome-devtools MCP against a page in its own window.
|
||||
|
||||
The Cesium scene renderer (`src/render/cesium/sceneRenderer.js`) draws
|
||||
every scene (icons, points, lines, shapes, models, quads, meshes, fields
|
||||
and the city), and the references were recorded with it, on a GPU: a
|
||||
software rasterizer such as SwiftShader draws the glow line differently.
|
||||
It has only the members the scenes need.
|
||||
|
||||
Some behaviour is only drawn, so the logic checks cannot see it: course
|
||||
easing (`courseGlide`), and a hidden row keeping its eased
|
||||
course. The stub keeps no drawn course. These wait for scenes that capture
|
||||
an icon mid-turn. Height queries that count a set
|
||||
(`includeInHeightQueries`) are not checked either: the stub's heights are
|
||||
scripted, so it does not model them. Nor are video frames (a check needs a
|
||||
video) or `fetchTile` (the stub fetches nothing).
|
||||
Generated
+16
@@ -19,6 +19,7 @@
|
||||
"h3-js": "^4.4.0",
|
||||
"hls.js": "^1.7.3",
|
||||
"hyparquet": "1.31.2",
|
||||
"kdbush": "^4.0.2",
|
||||
"mapillary-js": "^4.1.2",
|
||||
"mgrs": "^2.1.0",
|
||||
"pbf": "^5.1.2",
|
||||
@@ -36,6 +37,7 @@
|
||||
"prettier": "3.9.6",
|
||||
"puppeteer": "^25.16.0",
|
||||
"sharp": "^0.35.4",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "^6.4.4",
|
||||
"vite-plugin-cesium": "^1.2.23",
|
||||
"ws": "^8.21.0"
|
||||
@@ -3579,6 +3581,20 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.9.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
||||
|
||||
+35
-5
@@ -2,7 +2,7 @@
|
||||
"name": "gods-eye-view",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"description": "A real-time intelligence console for planet Earth \u2014 photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.",
|
||||
"description": "A real-time intelligence console for planet Earth — photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"author": "Bilawal Sidhu",
|
||||
@@ -53,6 +53,8 @@
|
||||
"test": "node scripts/run-unit-tests.mjs",
|
||||
"test:perf": "node scripts/run-perf-tests.mjs",
|
||||
"test:track": "node scripts/track-regression.mjs",
|
||||
"qa:stub-boot": "node scripts/qa-stub-boot.mjs",
|
||||
"qa:conformance": "node scripts/qa-conformance.mjs",
|
||||
"qa:map-source-tray": "node scripts/qa-map-source-tray.mjs",
|
||||
"qa:street-level": "node scripts/qa-street-level.mjs",
|
||||
"qa:street-level:fixtures": "node scripts/qa-street-level.mjs --fixtures",
|
||||
@@ -72,6 +74,7 @@
|
||||
"h3-js": "^4.4.0",
|
||||
"hls.js": "^1.7.3",
|
||||
"hyparquet": "1.31.2",
|
||||
"kdbush": "^4.0.2",
|
||||
"mapillary-js": "^4.1.2",
|
||||
"mgrs": "^2.1.0",
|
||||
"pbf": "^5.1.2",
|
||||
@@ -89,6 +92,7 @@
|
||||
"prettier": "3.9.6",
|
||||
"puppeteer": "^25.16.0",
|
||||
"sharp": "^0.35.4",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "^6.4.4",
|
||||
"vite-plugin-cesium": "^1.2.23",
|
||||
"ws": "^8.21.0"
|
||||
@@ -98,7 +102,7 @@
|
||||
"./infrastructure/geojson": "./src/data/localGeojsonCore.js",
|
||||
"./infrastructure/lod": "./src/data/localGeojsonLod.js",
|
||||
"./application": "./src/app/application.js",
|
||||
"./application/viewer": "./src/app/viewer.js",
|
||||
"./application/viewer": "./src/render/cesium/applicationViewer.js",
|
||||
"./time": "./src/time/worldClock.js",
|
||||
"./i18n": "./src/i18n/page.js",
|
||||
"./build/vite": {
|
||||
@@ -162,6 +166,7 @@
|
||||
"./ui/layout": "./src/ui/panelRails.js",
|
||||
"./ui/input": "./src/ui/visualInput.js",
|
||||
"./ui/display": "./src/ui/displayControls.js",
|
||||
"./ui/display/groups": "./src/ui/displayGroups.js",
|
||||
"./ui/effects": "./src/ui/effects.js",
|
||||
"./ui/effects/bloom": "./src/bloom.js",
|
||||
"./ui/maps": "./src/ui/mapSource.js",
|
||||
@@ -213,9 +218,9 @@
|
||||
"./geography/neighborhoods": "./src/data/neighborhoodPolygons.js",
|
||||
"./maps/controller": "./src/maps/controller.js",
|
||||
"./maps/catalog": "./src/maps/catalog.js",
|
||||
"./maps/imagery": "./src/maps/imagery.js",
|
||||
"./maps/terrain": "./src/maps/terrain.js",
|
||||
"./maps/3d": "./src/maps/google3d.js",
|
||||
"./maps/imagery": "./src/render/cesium/mapImagery.js",
|
||||
"./maps/terrain": "./src/render/cesium/mapTerrain.js",
|
||||
"./maps/3d": "./src/render/cesium/google3d.js",
|
||||
"./maps/defaults": "./src/maps/defaultSources.js",
|
||||
"./voice/controller": "./src/voice/realtimeController.js",
|
||||
"./voice/control": "./src/voice/control.js",
|
||||
@@ -244,6 +249,9 @@
|
||||
"./standalone/catalog": "./src/standalone/catalog.js",
|
||||
"./application/layers": "./src/app/constructCatalog.js",
|
||||
"./application/operations": "./src/app/operations.js",
|
||||
"./data/entity-records": "./src/data/entityRecords.js",
|
||||
"./input": "./src/input/dispatcher.js",
|
||||
"./queries/heights": "./src/queries/heights.js",
|
||||
"./data/lifecycle": "./src/data/lifecycle.js",
|
||||
"./ui/navigation": "./src/ui/navigationController.js",
|
||||
"./ui/share-restoration": "./src/ui/shareRestoration.js",
|
||||
@@ -316,6 +324,28 @@
|
||||
"./tools/services": "./src/tools/services.js",
|
||||
"./view": "./src/view/index.js",
|
||||
"./agent/world-packet": "./src/agent/worldPacket.js",
|
||||
"./geo": "./src/geo/index.js",
|
||||
"./sky": "./src/sky/index.js",
|
||||
"./render/contract": "./src/render/contract/index.js",
|
||||
"./render/stub": "./src/render/stub/index.js",
|
||||
"./render/occlusion": "./src/render/occlusion/index.js",
|
||||
"./render/camera/events": "./src/render/camera/events.js",
|
||||
"./render/camera/followTransition": "./src/render/camera/followTransition.js",
|
||||
"./render/cesium/plugin": "./src/render/cesium/plugin.js",
|
||||
"./render/cesium/unbound": "./src/render/cesium/unbound.js",
|
||||
"./render/conformance": "./src/render/conformance/index.js",
|
||||
"./render/input/router": "./src/render/input/router.js",
|
||||
"./render/stub/camera": "./src/render/stub/camera.js",
|
||||
"./render/stub/viewRectangle": "./src/render/stub/viewRectangle.js",
|
||||
"./render/stub/harness": "./src/render/stub/harness.js",
|
||||
"./render/motion": "./src/render/motion/iconMotion.js",
|
||||
"./render/vectorBase": "./src/render/vectorBase/index.js",
|
||||
"./render/iconSegment": "./src/data/iconSegment.js",
|
||||
"./render/recession": "./src/render/recession.js",
|
||||
"./render/windStreamlines": "./src/layers/wind/streamlines.js",
|
||||
"./render/weather": "./src/render/weather.js",
|
||||
"./weather/effects": "./src/weatherEffectsMath.js",
|
||||
"./geo/screenCluster": "./src/geo/screenCluster.js",
|
||||
"./layers/wildlife-sightings": "./src/layers/wildlifeSightings/index.js",
|
||||
"./layers/wildlife-sightings/source": "./src/layers/wildlifeSightings/source.js"
|
||||
}
|
||||
|
||||
@@ -15,6 +15,11 @@ const tests = (file) =>
|
||||
file.endsWith('.test.mjs') ||
|
||||
file.startsWith('src/testSupport/') ||
|
||||
file.startsWith('src/tooling/') ||
|
||||
// Test doubles outside src/testSupport, imported by tests only.
|
||||
file === 'src/input/testDoubles.mjs' ||
|
||||
file === 'src/layers/recentImagery/testDoubles.mjs' ||
|
||||
file === 'src/voice/voiceWorkflowHarness.mjs' ||
|
||||
file === 'src/layers/wildlifeSightings/renderPerformanceFixtures.mjs' ||
|
||||
file === 'src/overlays/worldOverlayAllocation.worker.mjs';
|
||||
const source = (file) =>
|
||||
file.startsWith('src/sources/') ||
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
advanceSpriteFocus,
|
||||
} from '../src/data/focusDeemphasis.js';
|
||||
import {
|
||||
applyAircraftBillboardTreatment,
|
||||
} from '../src/data/aircraftRecession.js';
|
||||
import { advanceSpriteFocus } from '../src/data/focusDeemphasis.js';
|
||||
import { aircraftTreatmentAlpha } from '../src/data/aircraftRecession.js';
|
||||
import { createIconSet } from '../src/data/iconSet.js';
|
||||
|
||||
if (typeof global.gc !== 'function') {
|
||||
throw new Error('focus-allocation-check.mjs requires node --expose-gc');
|
||||
@@ -66,17 +63,14 @@ const focusInput = {
|
||||
target,
|
||||
};
|
||||
|
||||
const baseColor = { withAlpha: (alpha) => ({ alpha }) };
|
||||
const billboard = { scale: 1, color: { alpha: 1 } };
|
||||
const aircraftInput = {
|
||||
billboard,
|
||||
baseScale: 1,
|
||||
baseAlpha: 1,
|
||||
baseColor,
|
||||
focusFactor: 1,
|
||||
cameraDistanceM: 100,
|
||||
cameraHeightM: 1000,
|
||||
};
|
||||
const icons = createIconSet({ capacity: 4 });
|
||||
const row = icons.add('sprite', {});
|
||||
|
||||
const baseline = bytesPerCall(() => focusInput.nowMs);
|
||||
const focus = netOfLoopBaseline(
|
||||
@@ -84,30 +78,22 @@ const focus = netOfLoopBaseline(
|
||||
baseline,
|
||||
);
|
||||
const aircraft = netOfLoopBaseline(
|
||||
bytesPerCall(() => applyAircraftBillboardTreatment(aircraftInput).alpha),
|
||||
bytesPerCall(() => aircraftTreatmentAlpha(aircraftInput)),
|
||||
baseline,
|
||||
);
|
||||
const productionSpriteTick = netOfLoopBaseline(
|
||||
bytesPerCall(() => {
|
||||
// Match the hot civilian/military sprite path: the caller constructs fresh
|
||||
// option literals, consumes the shared focus result immediately, and then
|
||||
// constructs the composed aircraft-treatment options for the same sprite.
|
||||
// Match the hot icon-set focus pass: the caller constructs a fresh option
|
||||
// literal, consumes the shared focus result immediately and writes it to
|
||||
// the row's focus column (the shader composes it with limb recession).
|
||||
const focusResult = advanceSpriteFocus(sprite, {
|
||||
screenPosition: focusInput.screenPosition,
|
||||
cameraDistance: focusInput.cameraDistance,
|
||||
nowMs: focusInput.nowMs,
|
||||
target,
|
||||
});
|
||||
const treatment = applyAircraftBillboardTreatment({
|
||||
billboard,
|
||||
baseScale: aircraftInput.baseScale,
|
||||
baseAlpha: aircraftInput.baseAlpha,
|
||||
baseColor,
|
||||
focusFactor: focusResult.factor,
|
||||
cameraDistanceM: aircraftInput.cameraDistanceM,
|
||||
cameraHeightM: aircraftInput.cameraHeightM,
|
||||
});
|
||||
return focusResult.factor + treatment.alpha;
|
||||
icons.setFocus(row, focusResult.factor);
|
||||
return focusResult.factor;
|
||||
}),
|
||||
baseline,
|
||||
);
|
||||
@@ -118,22 +104,24 @@ assert.ok(
|
||||
);
|
||||
assert.ok(
|
||||
aircraft.roundedMedian <= PURE_CALL_BUDGET,
|
||||
`applyAircraftBillboardTreatment allocated ${aircraft.rawMedian.toFixed(3)} B/call median`,
|
||||
`aircraftTreatmentAlpha allocated ${aircraft.rawMedian.toFixed(3)} B/call median`,
|
||||
);
|
||||
assert.ok(
|
||||
productionSpriteTick.roundedMedian <= PRODUCTION_SPRITE_TICK_BUDGET,
|
||||
`production sprite tick allocated ${productionSpriteTick.rawMedian.toFixed(3)} B/call median`,
|
||||
);
|
||||
|
||||
console.log(JSON.stringify({
|
||||
callsPerTrial: CALLS,
|
||||
trials: TRIALS,
|
||||
budgets: {
|
||||
pureCall: PURE_CALL_BUDGET,
|
||||
productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET,
|
||||
},
|
||||
loopBaseline: baseline,
|
||||
advanceSpriteFocus: focus,
|
||||
applyAircraftBillboardTreatment: aircraft,
|
||||
productionSpriteTick,
|
||||
}));
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
callsPerTrial: CALLS,
|
||||
trials: TRIALS,
|
||||
budgets: {
|
||||
pureCall: PURE_CALL_BUDGET,
|
||||
productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET,
|
||||
},
|
||||
loopBaseline: baseline,
|
||||
advanceSpriteFocus: focus,
|
||||
aircraftTreatmentAlpha: aircraft,
|
||||
productionSpriteTick,
|
||||
}),
|
||||
);
|
||||
+100
-18
@@ -43,6 +43,34 @@
|
||||
"scripts/build-admin-packs.mjs",
|
||||
"scripts/qa-admin-outlines.mjs",
|
||||
"src/data/inputOwnership.test.mjs",
|
||||
"src/input/dispatcher.test.mjs",
|
||||
"src/input/testDoubles.mjs",
|
||||
"src/input/sensorPick.js",
|
||||
"src/input/dispatcher.js",
|
||||
"src/queries/heights.js",
|
||||
"src/render/cesium/internals.js",
|
||||
"src/render/cesium/cameraInput.js",
|
||||
"src/render/cesium/ctrlWheelZoom.js",
|
||||
"src/render/cesium/input.js",
|
||||
"src/render/cesium/nativeClick.js",
|
||||
"src/render/cesium/nativeClick.test.mjs",
|
||||
"src/render/cesium/pickMemo.js",
|
||||
"src/render/cesium/input.test.mjs",
|
||||
"src/render/cesium/cameraInput.test.mjs",
|
||||
"src/render/cesium/cameraControls.js",
|
||||
"src/render/cesium/cameraControls.test.mjs",
|
||||
"src/render/input/router.js",
|
||||
"src/render/input/router.test.mjs",
|
||||
"src/render/motion/iconMotion.test.mjs",
|
||||
"src/render/motion/iconBook.test.mjs",
|
||||
"src/render/camera/poseSignature.test.mjs",
|
||||
"src/render/cesium/internals.test.mjs",
|
||||
"src/render/cesium/uploadProbe.js",
|
||||
"src/render/cesium/uploadProbe.test.mjs",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
"src/render/cesium/tileRequests.test.mjs",
|
||||
"src/queries/heights.test.mjs",
|
||||
"src/render/cesium/heights.test.mjs",
|
||||
"docs/CODE-BOUNDARIES.md",
|
||||
"src/main.js",
|
||||
"docs/APPLICATION.md",
|
||||
@@ -56,10 +84,8 @@
|
||||
"src/app/application.test.mjs",
|
||||
"src/app/mapLifecycle.test.mjs",
|
||||
"src/app/startupCamera.test.mjs",
|
||||
"src/app/viewer.js",
|
||||
"src/app/zoomOutGuard.test.mjs",
|
||||
"src/app/controls.test.mjs",
|
||||
"scripts/qa-zoom-out-guard.mjs",
|
||||
"src/render/cesium/applicationViewer.js",
|
||||
"src/sky/icrf.js",
|
||||
"src/app/atmosphereCompat.test.mjs",
|
||||
"src/standalone/application.js",
|
||||
"src/standalone/controls.js",
|
||||
@@ -358,7 +384,6 @@
|
||||
"src/layers/flights/tracking.js",
|
||||
"src/layers/flights/rendering.js",
|
||||
"src/layers/flights/testing.js",
|
||||
"src/layers/flights/hiddenContactRotation.test.mjs",
|
||||
"src/layers/flights/evidence.js",
|
||||
"src/layers/flights/ingestion.js",
|
||||
"src/layers/flights/queries.js",
|
||||
@@ -538,6 +563,8 @@
|
||||
"src/layers/traffic/model.js",
|
||||
"src/layers/traffic/timing.js",
|
||||
"src/layers/traffic/style.js",
|
||||
"src/layers/traffic/style.test.mjs",
|
||||
"src/layers/traffic/timing.test.mjs",
|
||||
"src/layers/bikeshare/lifecycle.js",
|
||||
"src/layers/bikeshare/viewport.js",
|
||||
"src/layers/bikeshare/registry.js",
|
||||
@@ -563,13 +590,13 @@
|
||||
"src/ui/frameRateMonitor.js",
|
||||
"src/ui/frameRateMonitor.test.mjs",
|
||||
"src/ui/frameRateView.test.mjs",
|
||||
"src/ui/renderFailure.test.mjs",
|
||||
"src/render/cesium/renderFailure.test.mjs",
|
||||
"src/ui/renderFailureView.test.mjs",
|
||||
"src/ui/renderFailureLoopErrors.test.mjs",
|
||||
"src/ui/renderFailureEventRetry.test.mjs",
|
||||
"src/render/cesium/renderFailureLoopErrors.test.mjs",
|
||||
"src/render/cesium/renderFailureEventRetry.test.mjs",
|
||||
"src/app/renderFailureInlineRetry.test.mjs",
|
||||
"src/ui/renderFailureSecondLoop.test.mjs",
|
||||
"src/ui/renderLoopFixture.mjs",
|
||||
"src/render/cesium/renderFailureSecondLoop.test.mjs",
|
||||
"src/render/cesium/renderLoopFixture.mjs",
|
||||
"src/layers/cctv/lifecycle.js",
|
||||
"src/layers/cctv/controls.js",
|
||||
"src/layers/cctv/geometry.js",
|
||||
@@ -650,6 +677,7 @@
|
||||
"src/layers/radio/volume.js",
|
||||
"src/data/radio.js",
|
||||
"src/layers/radio/source.test.mjs",
|
||||
"src/layers/radio/lifecycle.test.mjs",
|
||||
"src/layers/submarineCables/bundledSource.js",
|
||||
"src/layers/submarineCables/geometry.js",
|
||||
"src/layers/submarineCables/index.js",
|
||||
@@ -674,10 +702,14 @@
|
||||
"src/maps/imageryComparison.js",
|
||||
"src/maps/credits.js",
|
||||
"src/maps/defaultSources.js",
|
||||
"src/maps/google3d.js",
|
||||
"src/maps/imagery.js",
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/mapImagery.js",
|
||||
"src/maps/registry.js",
|
||||
"src/maps/terrain.js",
|
||||
"src/render/cesium/mapTerrain.js",
|
||||
"src/maps/engine.js",
|
||||
"src/maps/startupRoute.js",
|
||||
"src/maps/attribution.js",
|
||||
"src/render/cesium/mapEngine.js",
|
||||
"src/maps/terrainRetry.js",
|
||||
"src/maps/terrainRetry.test.mjs",
|
||||
"src/mapStackController.js",
|
||||
@@ -685,7 +717,7 @@
|
||||
"src/mapStackChips.test.mjs",
|
||||
"src/mapStackUnavailableReason.test.mjs",
|
||||
"src/mapStartup.test.mjs",
|
||||
"src/maps/sourceFactories.test.mjs",
|
||||
"src/render/cesium/mapSources.test.mjs",
|
||||
"src/search/geospatial.js",
|
||||
"src/search/http.js",
|
||||
"src/search/defaults.js",
|
||||
@@ -702,6 +734,16 @@
|
||||
"src/services/application.js",
|
||||
"src/services/requests.js",
|
||||
"src/app/scene.js",
|
||||
"src/render/cesium/appRenderer.test.mjs",
|
||||
"src/render/noCesiumOutsideRender.test.mjs",
|
||||
"src/render/cesiumAllowList.json",
|
||||
"src/render/viewerAccess.test.mjs",
|
||||
"src/render/viewerAccessAllowList.json",
|
||||
"src/testSupport/viewerAccess.mjs",
|
||||
"scripts/viewer-access-baseline.mjs",
|
||||
"src/geo/geo.test.mjs",
|
||||
"src/geo/celestial.test.mjs",
|
||||
"src/geo/quaternion.test.mjs",
|
||||
"src/app/controls.js",
|
||||
"src/app/data.js",
|
||||
"src/app/tools.js",
|
||||
@@ -757,6 +799,7 @@
|
||||
"src/layers/flights/snapshotRenderer.js",
|
||||
"src/layers/flights/records.test.mjs",
|
||||
"src/layers/flights/ingestion.test.mjs",
|
||||
"src/layers/flights/controller.test.mjs",
|
||||
"src/layers/military/records.js",
|
||||
"src/layers/military/recordPolicy.js",
|
||||
"src/layers/military/snapshotRenderer.js",
|
||||
@@ -840,7 +883,6 @@
|
||||
"src/tooling/transitProvider.test.mjs",
|
||||
"src/app/layers/transit.js",
|
||||
"src/data/transitIcons.js",
|
||||
"src/data/cameraSensitivity.js",
|
||||
"src/data/contactPlayback.js",
|
||||
"src/data/contactTrailRenderer.js",
|
||||
"src/data/contactTrailRenderer.test.mjs",
|
||||
@@ -912,6 +954,10 @@
|
||||
"src/layers/weather/rendering.js",
|
||||
"src/layers/weather/shellRendering.js",
|
||||
"src/layers/weather/shellRendering.test.mjs",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawFields.test.mjs",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/render/cesium/drawStreamlines.test.mjs",
|
||||
"src/layers/weather/infraredAlpha.js",
|
||||
"src/layers/weather/infraredAlpha.test.mjs",
|
||||
"src/layers/weather/infraredImage.js",
|
||||
@@ -1130,7 +1176,6 @@
|
||||
"src/layers/traffic/roadModes.test.mjs",
|
||||
"scripts/qa-traffic-motion.mjs",
|
||||
"src/layers/traffic/motion.test.mjs",
|
||||
"src/layers/traffic/lineRebuild.test.mjs",
|
||||
"scripts/qa-journey-recorder.mjs",
|
||||
"scripts/qa-alpr-journey.mjs",
|
||||
"scripts/qa-context-arrivals.mjs",
|
||||
@@ -1163,6 +1208,9 @@
|
||||
"src/view/index.test.mjs",
|
||||
"src/tools/views.test.mjs",
|
||||
"src/app/embed.test.mjs",
|
||||
"src/app/panelRendering.js",
|
||||
"src/render/cesium/application.js",
|
||||
"src/app/panelRendering.test.mjs",
|
||||
"src/tools/globePanel.test.mjs",
|
||||
"src/costEndpointThrottle.test.mjs",
|
||||
"src/sources/gbfsStations.test.mjs",
|
||||
@@ -1179,7 +1227,7 @@
|
||||
"scripts/build-bright-stars.mjs",
|
||||
"scripts/build-milky-way.mjs",
|
||||
"src/sky/stars.test.mjs",
|
||||
"src/sky/starrySky.test.mjs",
|
||||
"src/render/cesium/starrySky.test.mjs",
|
||||
"src/tooling/skyAssets.test.mjs",
|
||||
"src/tooling/skyAssets.paintOut.test.mjs",
|
||||
"src/tooling/responseCompression.test.mjs",
|
||||
@@ -1197,6 +1245,31 @@
|
||||
"src/ui/shellFacade.test.mjs",
|
||||
"src/voice/globeResetConfirmation.test.mjs",
|
||||
"src/hudDms.test.mjs",
|
||||
"server/providers/common/rateLimitKeys.test.mjs",
|
||||
"src/render/contract/contract.test.mjs",
|
||||
"src/render/contract/common.d.ts",
|
||||
"src/render/contract/renderer.d.ts",
|
||||
"src/render/contract/frame.d.ts",
|
||||
"src/render/contract/globe.d.ts",
|
||||
"src/render/contract/draw.d.ts",
|
||||
"src/render/contract/camera.d.ts",
|
||||
"src/render/contract/query.d.ts",
|
||||
"src/render/contract/input.d.ts",
|
||||
"src/render/contract/effects.d.ts",
|
||||
"src/render/contract/credits.d.ts",
|
||||
"src/render/contract/quality.d.ts",
|
||||
"src/render/contract/index.d.ts",
|
||||
"src/render/stub/stub.test.mjs",
|
||||
"src/render/conformance/scenes.test.mjs",
|
||||
"src/render/cesium/cameraGoldens.test.mjs",
|
||||
"scripts/record-camera-goldens.mjs",
|
||||
"server/standalone/conformance-references.js",
|
||||
"dev/conformance/index.html",
|
||||
"dev/conformance/main.js",
|
||||
"docs/RENDERER-CONTRACT.md",
|
||||
"src/render/cesium/zoomOutGuard.test.mjs",
|
||||
"src/app/controls.test.mjs",
|
||||
"scripts/qa-zoom-out-guard.mjs",
|
||||
"src/hudSummaryGate.test.mjs",
|
||||
"src/hudSummaryLine.test.mjs",
|
||||
"src/testSupport/stubMgrs.mjs",
|
||||
@@ -1302,7 +1375,6 @@
|
||||
"src/tooling/nominatimGuardLifecycle.test.mjs",
|
||||
"src/tooling/nominatimLockOwnership.test.mjs",
|
||||
"src/tooling/nominatimOutlineRoute.test.mjs",
|
||||
"server/providers/common/rateLimitKeys.test.mjs",
|
||||
"src/voice/areaCandidateContract.js",
|
||||
"src/voice/layerActionOwnership.js",
|
||||
"src/data/areaGeometry.test.mjs",
|
||||
@@ -1345,6 +1417,7 @@
|
||||
"src/layers/shipwrecks/index.test.mjs",
|
||||
"src/layers/shipwrecks/source.test.mjs",
|
||||
"src/data/shipwrecksProxy.test.mjs",
|
||||
"src/data/aircraftIconLayer.test.mjs",
|
||||
"src/app/sourceComposition.js",
|
||||
"src/app/sourceComposition.test.mjs",
|
||||
"src/data/dataCredits.js",
|
||||
@@ -1440,6 +1513,15 @@
|
||||
"src/data/placePacksLoading.test.mjs",
|
||||
"src/ui/placePacksLoading.js",
|
||||
"src/ui/placePacksLoading.test.mjs",
|
||||
"src/render/applicationHooks.js",
|
||||
"src/maps/globeEngine.js",
|
||||
"src/maps/globeEngine.test.mjs",
|
||||
"src/render/cesium/viewers.js",
|
||||
"src/app/scene.test.mjs",
|
||||
"dev/stub-app/main.js",
|
||||
"scripts/qa-stub-boot.mjs",
|
||||
"src/ui/creditsView.js",
|
||||
"src/ui/creditsView.test.mjs",
|
||||
"src/cockpitSubjectProviders.js",
|
||||
"src/cockpitSubjectProviders.test.mjs",
|
||||
"src/cockpitProgress.js",
|
||||
|
||||
+2
-1
@@ -479,7 +479,8 @@ function readMarkup(file) {
|
||||
|
||||
// Text that never reaches the page as UI: tool results and descriptions for
|
||||
// AI clients (MCP and the voice model).
|
||||
const NOT_UI = [/^src\/tools\//];
|
||||
// The conformance suite's check titles are developer output, not UI.
|
||||
const NOT_UI = [/^src\/tools\//, /^src\/render\/conformance\//];
|
||||
|
||||
function sourceFiles() {
|
||||
return trackedFiles(
|
||||
|
||||
+2344
-213
File diff suppressed because it is too large.
Load diff
+113
-48
@@ -12,10 +12,11 @@
|
||||
* and finally Brandenburg (Berlin is a hole) and Hawaii (eight islands).
|
||||
*
|
||||
* Asserts for every outline: it resolves from the bundled packs (no geocode,
|
||||
* boundary or Overpass request), is drawn as a draped outline within the
|
||||
* budget, and holds still — no rebuilt primitives and no new entities while
|
||||
* the camera is still. The whole journey must log zero console/page errors and
|
||||
* send zero requests to any Overpass host or nominatim.openstreetmap.org.
|
||||
* boundary or Overpass request), shows its first frame within the budget,
|
||||
* has its draped fill and outline built (their time is reported), and holds
|
||||
* still — none of its primitives rebuilt while the camera is still. The whole
|
||||
* journey must log zero console/page errors and send zero requests to any
|
||||
* Overpass host or nominatim.openstreetmap.org.
|
||||
*
|
||||
* Evidence in qa-shots/ (gitignored): admin-outlines-<step>.png screenshots,
|
||||
* admin-outlines-journey.mp4 (CDP screencast at ~24 fps, frames re-timed from
|
||||
@@ -210,56 +211,84 @@ try {
|
||||
requestAnimationFrame(step);
|
||||
});
|
||||
},
|
||||
annotationSource() {
|
||||
for (let i = 0; i < viewer.dataSources.length; i++) {
|
||||
const source = viewer.dataSources.get(i);
|
||||
if (source.name === 'gev-annotations') return source;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
groundPrimitives() {
|
||||
/**
|
||||
* The annotations' primitives in the scene, each with the marks its
|
||||
* instances draw (their pick ids carry `meta.annotation`); only those
|
||||
* of `mark` when given.
|
||||
*/
|
||||
annotationPrimitives(mark) {
|
||||
const marksOf = (primitive) => {
|
||||
let inner = primitive;
|
||||
for (let depth = 0; inner && depth < 4; depth++) {
|
||||
if (Array.isArray(inner._instanceIds))
|
||||
return inner._instanceIds
|
||||
.map((id) => id?.meta?.annotation)
|
||||
.filter((id) => id !== undefined);
|
||||
inner = inner._primitive;
|
||||
}
|
||||
return [];
|
||||
};
|
||||
const list = [];
|
||||
const walk = (collection) => {
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const item = collection.get(i);
|
||||
if (item?.length !== undefined && typeof item.get === 'function')
|
||||
walk(item);
|
||||
else list.push(item);
|
||||
else {
|
||||
const marks = marksOf(item);
|
||||
if (marks.length && (mark === undefined || marks.includes(mark)))
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(viewer.scene.groundPrimitives);
|
||||
walk(viewer.scene.primitives);
|
||||
return list;
|
||||
},
|
||||
snapshot() {
|
||||
const source = this.annotationSource();
|
||||
const entities = source ? source.entities.values : [];
|
||||
const primitives = this.groundPrimitives();
|
||||
/** What `mark` draws (every annotation's, without one). */
|
||||
snapshot(mark) {
|
||||
const primitives = this.annotationPrimitives(mark);
|
||||
window.__qaPrimitiveIds ??= new WeakMap();
|
||||
let next = window.__qaPrimitiveNext ?? 1;
|
||||
const ids = primitives.map((primitive) => {
|
||||
if (!window.__qaPrimitiveIds.has(primitive))
|
||||
window.__qaPrimitiveIds.set(primitive, next++);
|
||||
return window.__qaPrimitiveIds.get(primitive);
|
||||
});
|
||||
// By identity only: hosts may trade places without a rebuild.
|
||||
const ids = primitives
|
||||
.map((primitive) => {
|
||||
if (!window.__qaPrimitiveIds.has(primitive))
|
||||
window.__qaPrimitiveIds.set(primitive, next++);
|
||||
return window.__qaPrimitiveIds.get(primitive);
|
||||
})
|
||||
.sort((a, b) => a - b);
|
||||
window.__qaPrimitiveNext = next;
|
||||
return {
|
||||
entities: entities.length,
|
||||
polygons: entities.filter((e) => e.polygon).length,
|
||||
polylines: entities.filter((e) => e.polyline).length,
|
||||
primitives: primitives.length,
|
||||
fills: primitives.filter((p) => p instanceof Cesium.GroundPrimitive)
|
||||
.length,
|
||||
lines: primitives.filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
).length,
|
||||
// Draped on terrain and tiles alike.
|
||||
draped:
|
||||
entities.every(
|
||||
(e) =>
|
||||
!e.polygon ||
|
||||
e.polygon.classificationType?.getValue() ===
|
||||
Cesium.ClassificationType.BOTH,
|
||||
) &&
|
||||
entities.every(
|
||||
(e) => !e.polyline || e.polyline.clampToGround?.getValue(),
|
||||
primitives.length > 0 &&
|
||||
primitives.every(
|
||||
(p) => p.classificationType === Cesium.ClassificationType.BOTH,
|
||||
),
|
||||
primitiveIds: ids,
|
||||
ready: viewer.dataSourceDisplay.ready,
|
||||
ready: primitives.every((p) => p.ready),
|
||||
};
|
||||
},
|
||||
/** The annotations drawn under the middle of the view. */
|
||||
marksAtCentre() {
|
||||
const { canvas } = viewer.scene;
|
||||
const centre = new Cesium.Cartesian2(
|
||||
canvas.clientWidth / 2,
|
||||
canvas.clientHeight / 2,
|
||||
);
|
||||
const marks = new Set();
|
||||
for (const hit of viewer.scene.drillPick(centre, 16)) {
|
||||
const mark = hit?.id?.meta?.annotation;
|
||||
if (mark !== undefined) marks.add(mark);
|
||||
}
|
||||
return [...marks];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -313,17 +342,31 @@ try {
|
||||
{ flyTo },
|
||||
);
|
||||
const resolvedMs = performance.now() - started;
|
||||
// "Drawn" = the first rendered frame after the entity visualizers have
|
||||
// built the mark's primitives (each tick updates them before render).
|
||||
// "Drawn" = the first rendered frame after the mark is drawn (as
|
||||
// before, when it was the entities' first frame); "ready" = the first
|
||||
// with its primitives all built, which may wait on Cesium's workers.
|
||||
const { viewer } = window.__godsEyeView;
|
||||
const markId = response.ids?.[0];
|
||||
let drawnMs = null;
|
||||
let readyMs = null;
|
||||
await new Promise((resolve) => {
|
||||
const off = viewer.scene.postRender.addEventListener(() => {
|
||||
if (!viewer.dataSourceDisplay.ready) return;
|
||||
const giveUp = setTimeout(done, 15_000);
|
||||
function done() {
|
||||
clearTimeout(giveUp);
|
||||
off();
|
||||
resolve();
|
||||
}
|
||||
const off = viewer.scene.postRender.addEventListener(() => {
|
||||
const now = performance.now() - started;
|
||||
drawnMs ??= now;
|
||||
const drawn = window.__qaOutlines.annotationPrimitives(markId);
|
||||
if (drawn.length && drawn.every((p) => p.ready)) {
|
||||
readyMs = now;
|
||||
done();
|
||||
}
|
||||
});
|
||||
viewer.scene.requestRender();
|
||||
});
|
||||
const drawnMs = performance.now() - started;
|
||||
const mark = window.__godsEyeView.annotations
|
||||
.list()
|
||||
.find((m) => m.id === response.ids?.[0]);
|
||||
@@ -331,6 +374,7 @@ try {
|
||||
response: response.results?.[0] ?? null,
|
||||
resolvedMs,
|
||||
drawnMs,
|
||||
readyMs,
|
||||
parts: mark?.polygons?.length ?? (mark?.ring ? 1 : 0),
|
||||
holes: (mark?.polygons ?? []).reduce(
|
||||
(n, part) => n + part.length - 1,
|
||||
@@ -338,6 +382,7 @@ try {
|
||||
),
|
||||
ringVertices: mark?.ring?.length ?? 0,
|
||||
pending: Boolean(mark?.pendingOutline),
|
||||
markId,
|
||||
};
|
||||
},
|
||||
target,
|
||||
@@ -347,23 +392,29 @@ try {
|
||||
await settle();
|
||||
// Hold still: the drawn mark must not rebuild or grow.
|
||||
marker = `still:${name}`;
|
||||
const before = await page.evaluate(() => window.__qaOutlines.snapshot());
|
||||
const before = await page.evaluate(
|
||||
(mark) => window.__qaOutlines.snapshot(mark),
|
||||
timing.markId,
|
||||
);
|
||||
const stillStart = frames.length;
|
||||
const times = await page.evaluate(
|
||||
(ms) => window.__qaOutlines.frameTimes(ms),
|
||||
STILL_MS,
|
||||
);
|
||||
const after = await page.evaluate(() => window.__qaOutlines.snapshot());
|
||||
const after = await page.evaluate(
|
||||
(mark) => window.__qaOutlines.snapshot(mark),
|
||||
timing.markId,
|
||||
);
|
||||
const step = {
|
||||
step: `outline:${name}`,
|
||||
target,
|
||||
...timing,
|
||||
entities: after.entities,
|
||||
polygons: after.polygons,
|
||||
polylines: after.polylines,
|
||||
primitives: after.primitives,
|
||||
fills: after.fills,
|
||||
lines: after.lines,
|
||||
draped: after.draped,
|
||||
stableWhileStill:
|
||||
before.entities === after.entities &&
|
||||
after.primitives > 0 &&
|
||||
JSON.stringify(before.primitiveIds) ===
|
||||
JSON.stringify(after.primitiveIds),
|
||||
stillFrameTimes: stats(times),
|
||||
@@ -375,6 +426,7 @@ try {
|
||||
result.steps.push(step);
|
||||
console.log(
|
||||
`${name}: resolved ${timing.resolvedMs.toFixed(0)} ms, drawn ${timing.drawnMs.toFixed(0)} ms, ` +
|
||||
`ready ${timing.readyMs?.toFixed(0)} ms, ` +
|
||||
`${timing.parts} part(s), ${timing.holes} hole(s), via ${timing.response?.resolvedVia}; ` +
|
||||
`still p50/p95 ${step.stillFrameTimes.p50}/${step.stillFrameTimes.p95} ms; ` +
|
||||
`stable=${step.stableWhileStill}`,
|
||||
@@ -387,6 +439,11 @@ try {
|
||||
timing.drawnMs < OUTLINE_BUDGET_MS,
|
||||
`${name}: drawn in ${timing.drawnMs} ms`,
|
||||
);
|
||||
assert.notEqual(timing.readyMs, null, `${name}: its primitives built`);
|
||||
assert.ok(
|
||||
step.fills > 0 && step.lines > 0,
|
||||
`${name}: drawn as a fill and an outline`,
|
||||
);
|
||||
assert.equal(step.draped, true, `${name}: draped on terrain/tiles`);
|
||||
assert.equal(step.stableWhileStill, true, `${name}: no redraw when still`);
|
||||
assert.deepEqual(step.lookups, [], `${name}: no network lookups`);
|
||||
@@ -512,8 +569,15 @@ try {
|
||||
await move(name, { lat, lon, height, pitch: -90 }, 1);
|
||||
await outline(name, target);
|
||||
await shot(name);
|
||||
const rendered = await page.evaluate(() => window.__qaOutlines.snapshot());
|
||||
assert.ok(rendered.polygons > 0, `${target} polygon renders`);
|
||||
const rendered = await page.evaluate(() => ({
|
||||
marks: window.__godsEyeView.annotations.list().map((m) => m.id),
|
||||
atCentre: window.__qaOutlines.marksAtCentre(),
|
||||
}));
|
||||
assert.ok(
|
||||
rendered.marks.length === 1 &&
|
||||
rendered.atCentre.includes(rendered.marks[0]),
|
||||
`${target} polygon renders`,
|
||||
);
|
||||
}
|
||||
|
||||
if (recordVideo) {
|
||||
@@ -632,6 +696,7 @@ console.table(
|
||||
step: s.step,
|
||||
resolvedMs: s.resolvedMs?.toFixed(0),
|
||||
drawnMs: s.drawnMs?.toFixed(0),
|
||||
readyMs: s.readyMs?.toFixed(0),
|
||||
parts: s.parts,
|
||||
stable: s.stableWhileStill,
|
||||
p50: (s.stillFrameTimes || s.frameTimes)?.p50,
|
||||
|
||||
@@ -127,7 +127,7 @@ try {
|
||||
let animeOn = false;
|
||||
for (let i = 0; i < s.postProcessStages.length; i++) {
|
||||
const stage = s.postProcessStages.get(i);
|
||||
if (stage.name === 'godsEyeView_anime')
|
||||
if (stage.name === 'effects_style_anime')
|
||||
animeOn = stage.enabled && stage.uniforms.intensity > 0.99;
|
||||
}
|
||||
return {
|
||||
|
||||
+61
-67
@@ -263,32 +263,30 @@ function installRenderFramesHelper(page) {
|
||||
|
||||
// In-page helper (stringified and re-defined inside each evaluate that needs
|
||||
// it, since functions can't cross the puppeteer boundary): serializes the
|
||||
// 5 frustum polylines + plane position/orientation/dimensions for a camera
|
||||
// into plain arrays of numbers, using only the camera's own clock time (no
|
||||
// Cesium namespace needed — Property.getValue just needs *a* JulianDate,
|
||||
// and the viewer's own clock.currentTime is a valid live instance of one).
|
||||
// 5 frustum lines + plane position/orientation/dimensions for a camera
|
||||
// into plain arrays of numbers, from what the layer reports it draws.
|
||||
const SERIALIZE_GEOM_SRC = `
|
||||
function serializeGeom(camId) {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const time = viewer.clock.currentTime;
|
||||
const drawn = window.__godsEyeView.dataManager.layers
|
||||
.get('cctv')
|
||||
.module._cctvDrawnForTest();
|
||||
const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap'];
|
||||
const poly = {};
|
||||
for (const role of roles) {
|
||||
const ent = viewer.entities.getById('cctv-' + camId + '-' + role);
|
||||
poly[role] = ent && ent.polyline
|
||||
? ent.polyline.positions.getValue(time).map((p) => [p.x, p.y, p.z])
|
||||
const line = drawn.coverage['cctv-' + camId + '-' + role];
|
||||
poly[role] = line?.positions
|
||||
? line.positions.map((p) => [p.x, p.y, p.z])
|
||||
: null;
|
||||
}
|
||||
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane');
|
||||
const quad = drawn.planes['cctv-' + camId + '-plane'];
|
||||
let plane = null;
|
||||
if (planeEnt) {
|
||||
const pos = planeEnt.position.getValue(time);
|
||||
const orient = planeEnt.orientation.getValue(time);
|
||||
const dims = planeEnt.plane.dimensions.getValue(time);
|
||||
if (quad) {
|
||||
const pos = quad.center;
|
||||
const orient = quad.orientation;
|
||||
plane = {
|
||||
position: [pos.x, pos.y, pos.z],
|
||||
orientation: [orient.x, orient.y, orient.z, orient.w],
|
||||
dimensions: [dims.x, dims.y],
|
||||
dimensions: [quad.size[0], quad.size[1]],
|
||||
};
|
||||
}
|
||||
return { poly, plane };
|
||||
@@ -695,10 +693,9 @@ async function main() {
|
||||
const camera = dataManager.layers
|
||||
.get('cctv')
|
||||
.module.getUIState().activeCamera;
|
||||
const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`);
|
||||
const mount = ray?.polyline?.positions.getValue(
|
||||
viewer.clock.currentTime,
|
||||
)?.[0];
|
||||
const ray = dataManager.layers.get('cctv').module._cctvDrawnForTest()
|
||||
.coverage[`cctv-${camera.id}-ray-tl`];
|
||||
const mount = ray?.positions?.[0];
|
||||
const height =
|
||||
mount &&
|
||||
viewer.scene.globe.ellipsoid.cartesianToCartographic(mount)
|
||||
@@ -849,8 +846,10 @@ async function main() {
|
||||
// source. Assert the migrated surface via the host diagnostics.
|
||||
const diag = window.__gevWorldOverlay?.getDiagnostics?.();
|
||||
g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1;
|
||||
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane');
|
||||
g.planeShow = planeEnt ? planeEnt.show : null;
|
||||
const quad = window.__godsEyeView.dataManager.layers
|
||||
.get('cctv')
|
||||
.module._cctvDrawnForTest().planes['cctv-' + camId + '-plane'];
|
||||
g.planeShow = quad ? quad.show : null;
|
||||
return g;
|
||||
})(${JSON.stringify(activeId)})`);
|
||||
|
||||
@@ -1212,26 +1211,22 @@ async function main() {
|
||||
console.log(
|
||||
'Checking frame-loop health (placeholder -> frame swap, URL family)...',
|
||||
);
|
||||
// The plane's material.image is always defined (placeholder canvas from
|
||||
// the moment the runtime is created, real frame content painted onto the
|
||||
// The plane's image is always defined (placeholder canvas from the
|
||||
// moment the runtime is created, real frame content painted onto the
|
||||
// same canvas/video reference once the fetch resolves) — assert it's
|
||||
// never null/undefined once the runtime exists, i.e. there's no gap where
|
||||
// the plane shows nothing.
|
||||
const materialInfo = await page.evaluate((camId) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const time = viewer.clock.currentTime;
|
||||
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane');
|
||||
const mat = planeEnt?.plane?.material;
|
||||
const image = mat?.image;
|
||||
const resolved =
|
||||
image && typeof image.getValue === 'function'
|
||||
? image.getValue(time)
|
||||
: image;
|
||||
const quad = window.__godsEyeView.dataManager.layers
|
||||
.get('cctv')
|
||||
.module._cctvDrawnForTest().planes['cctv-' + camId + '-plane'];
|
||||
const source = quad?.source;
|
||||
const resolved = source?.video || source?.canvas || source?.image;
|
||||
return {
|
||||
hasMaterial: !!mat,
|
||||
hasMaterial: !!source,
|
||||
hasImage: !!resolved,
|
||||
tagName: resolved?.tagName || null,
|
||||
show: planeEnt?.show,
|
||||
show: quad?.show,
|
||||
};
|
||||
}, activeId);
|
||||
record(
|
||||
@@ -1665,14 +1660,12 @@ async function main() {
|
||||
'Checking viewshed mode (coverage tri-state + color-coded volumes)...',
|
||||
);
|
||||
const countVolumes = () =>
|
||||
page.evaluate(() => {
|
||||
const prims = window.__godsEyeView.viewer.scene.primitives;
|
||||
let n = 0;
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
if (prims.get(i) && prims.get(i)._gevViewshed) n += 1;
|
||||
}
|
||||
return n;
|
||||
});
|
||||
page.evaluate(
|
||||
() =>
|
||||
window.__godsEyeView.dataManager.layers
|
||||
.get('cctv')
|
||||
.module._cctvDrawnForTest().viewsheds.length,
|
||||
);
|
||||
|
||||
const cBeforeViewshed = await readCounters();
|
||||
const modeAfterSet = await page.evaluate(() => {
|
||||
@@ -1725,26 +1718,26 @@ async function main() {
|
||||
mod.setParams({ coverageMode: 'viewshed' });
|
||||
});
|
||||
await sleep(400);
|
||||
await page.evaluate(() => {
|
||||
const prims = window.__godsEyeView.viewer.scene.primitives;
|
||||
window.__qaViewshedRefs = [];
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
if (prims.get(i) && prims.get(i)._gevViewshed)
|
||||
window.__qaViewshedRefs.push(prims.get(i));
|
||||
}
|
||||
});
|
||||
// Volumes are draw-port mesh items: "no churn" is no volume written.
|
||||
const drawnViewsheds = () =>
|
||||
page.evaluate(() => {
|
||||
const drawn = window.__godsEyeView.dataManager.layers
|
||||
.get('cctv')
|
||||
.module._cctvDrawnForTest();
|
||||
return { ids: drawn.viewsheds, writes: drawn.viewshedWrites };
|
||||
});
|
||||
const viewshedsBefore = await drawnViewsheds();
|
||||
await sleep(8000);
|
||||
const viewshedIdle = await page.evaluate(() => {
|
||||
const prims = window.__godsEyeView.viewer.scene.primitives;
|
||||
const now = [];
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
if (prims.get(i) && prims.get(i)._gevViewshed) now.push(prims.get(i));
|
||||
}
|
||||
const before = window.__qaViewshedRefs || [];
|
||||
const sameCount = now.length === before.length;
|
||||
const sameIdentity = sameCount && before.every((p) => now.includes(p));
|
||||
return { sameCount, sameIdentity, count: now.length };
|
||||
});
|
||||
const viewshedsAfter = await drawnViewsheds();
|
||||
const viewshedIdle = (() => {
|
||||
const sameCount =
|
||||
viewshedsAfter.ids.length === viewshedsBefore.ids.length;
|
||||
const sameIdentity =
|
||||
sameCount &&
|
||||
viewshedsBefore.ids.every((id) => viewshedsAfter.ids.includes(id)) &&
|
||||
viewshedsAfter.writes === viewshedsBefore.writes;
|
||||
return { sameCount, sameIdentity, count: viewshedsAfter.ids.length };
|
||||
})();
|
||||
const cAfterViewshed = await readCounters();
|
||||
const lateFloorSamples =
|
||||
cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight;
|
||||
@@ -1785,9 +1778,9 @@ async function main() {
|
||||
const gizmoStates = await page.evaluate((parts) => {
|
||||
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
|
||||
mod.setParams({ calibrationMode: true });
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const drawn = mod._cctvDrawnForTest().gizmo;
|
||||
return parts.map((p) => {
|
||||
const e = viewer.entities.getById('cctv-gizmo-' + p);
|
||||
const e = drawn['cctv-gizmo-' + p];
|
||||
return e ? (e.show ? 'shown' : 'hidden') : 'missing';
|
||||
});
|
||||
}, GIZMO_PARTS);
|
||||
@@ -1802,9 +1795,10 @@ async function main() {
|
||||
// stay frozen until release, with no transient sampleHeight calls.
|
||||
const eastDrag = await page.evaluate(() => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const e = viewer.entities.getById('cctv-gizmo-move-east');
|
||||
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
|
||||
const e = mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east'];
|
||||
if (!e) return null;
|
||||
const pts = e.polyline.positions.getValue(viewer.clock.currentTime);
|
||||
const pts = e.positions;
|
||||
const scene = viewer.scene;
|
||||
const w = scene.canvas.clientWidth;
|
||||
const h = scene.canvas.clientHeight;
|
||||
@@ -2082,9 +2076,9 @@ async function main() {
|
||||
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
|
||||
mod.setParams({ calibrationMode: false });
|
||||
mod.setParams({ calibration: { reset: true } });
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const drawn = mod._cctvDrawnForTest().gizmo;
|
||||
return parts.map((p) => {
|
||||
const e = viewer.entities.getById('cctv-gizmo-' + p);
|
||||
const e = drawn['cctv-gizmo-' + p];
|
||||
return e ? (e.show ? 'shown' : 'hidden') : 'missing';
|
||||
});
|
||||
}, GIZMO_PARTS);
|
||||
|
||||
@@ -765,7 +765,7 @@ try {
|
||||
} : null,
|
||||
navigation: snapshot?.navigation || null,
|
||||
afterId: trackedInfo?.icao24 || null,
|
||||
viewerTrackedId: viewer.trackedEntity?.gevTrackedId || null,
|
||||
viewerTrackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null,
|
||||
contextVisible: !document.getElementById('military-awareness-panel')?.hidden,
|
||||
entryAvailableAfterSettlement: Boolean(entry && !entry.hidden),
|
||||
blockerStillRegistered: dataManager.layers.has(blockerId),
|
||||
@@ -1365,7 +1365,7 @@ try {
|
||||
contextMode: styleManager._contextControls._contextMode,
|
||||
contextChanging: styleManager._contextControls._contextModeChanging,
|
||||
subject: context?.subject ? `${context.subject.layerId}:${context.subject.id}` : null,
|
||||
tracked: tracker?.gevTrackedId || null,
|
||||
tracked: window.__godsEyeView.entityRecords.read(tracker)?.trackedId || null,
|
||||
density: styleManager.getDetectionState().densityPct,
|
||||
detectionMode: styleManager.getDetectionState().detectionMode,
|
||||
installations: dataManager.getLayerLifecycleState('military-installations'),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Run the renderer conformance logic suite on the Cesium renderer in
|
||||
* headless Chromium (`dev/conformance/`, `window.conformance.runLogic`),
|
||||
* and fail on any failed check, or on a skip that is not expected.
|
||||
*
|
||||
* Without `--url` it starts a Vite dev server of this checkout on `--port`
|
||||
* (default 5289) and stops it after. WebGL runs on SwiftShader, so the run
|
||||
* needs no GPU. `--only id,id` runs just those checks; `--json path` writes
|
||||
* the report.
|
||||
*
|
||||
* npm run qa:conformance [-- --url http://127.0.0.1:5280] [--only ids]
|
||||
* [--json path]
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import puppeteer from 'puppeteer';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** Checks the run skips, with why: anything else skipped fails it. */
|
||||
export const EXPECTED_SKIPS = Object.freeze({
|
||||
// The page scripts no heights for the Cesium renderer.
|
||||
'query.heights': 'no scripted heights in this harness',
|
||||
});
|
||||
|
||||
/** A whole run has this long; a check that hangs fails it rather than CI. */
|
||||
const RUN_TIMEOUT_MS = 15 * 60_000;
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { port: 5289 };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--url') args.url = argv[++i];
|
||||
else if (arg === '--port') args.port = Number(argv[++i]);
|
||||
else if (arg === '--only') args.only = argv[++i].split(',');
|
||||
else if (arg === '--json') args.json = argv[++i];
|
||||
else throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
async function startViteServer(port) {
|
||||
const { createServer } = await import('vite');
|
||||
const server = await createServer({
|
||||
root: ROOT,
|
||||
configFile: path.join(ROOT, 'vite.config.js'),
|
||||
// No hot reload: the page is loaded once and nothing edits it.
|
||||
server: { port, strictPort: true, host: '127.0.0.1', hmr: false },
|
||||
logLevel: 'warn',
|
||||
});
|
||||
await server.listen();
|
||||
return server;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const server = args.url ? null : await startViteServer(args.port);
|
||||
try {
|
||||
await run(args);
|
||||
} finally {
|
||||
await server?.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args) {
|
||||
const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, '');
|
||||
const browser = await puppeteer.launch({
|
||||
headless: true,
|
||||
executablePath:
|
||||
process.env.PUPPETEER_EXECUTABLE_PATH ||
|
||||
(await puppeteer.executablePath()),
|
||||
defaultViewport: { width: 1280, height: 800 },
|
||||
protocolTimeout: RUN_TIMEOUT_MS,
|
||||
args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'],
|
||||
});
|
||||
const pageErrors = [];
|
||||
let report;
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await page.goto(`${base}/dev/conformance/`, { waitUntil: 'load' });
|
||||
await page.waitForFunction(() => window.conformance?.runLogic, {
|
||||
timeout: 120_000,
|
||||
});
|
||||
report = await page.evaluate(
|
||||
(only) => window.conformance.runLogic('cesium', { only }),
|
||||
args.only ?? null,
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2));
|
||||
console.log(
|
||||
`cesium: ${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped`,
|
||||
);
|
||||
const problems = [];
|
||||
for (const failure of report.failures) {
|
||||
console.error(`fail\t${failure.id}\t${failure.detail ?? ''}`);
|
||||
problems.push(failure.id);
|
||||
}
|
||||
for (const skip of report.skips) {
|
||||
const expected = EXPECTED_SKIPS[skip.id] === skip.detail;
|
||||
console.log(`skip\t${skip.id}\t${skip.detail ?? ''}`);
|
||||
if (!expected) problems.push(`${skip.id} skipped`);
|
||||
}
|
||||
if (!args.only && report.passed === 0) problems.push('nothing passed');
|
||||
if (problems.length) {
|
||||
console.error(`FAIL: ${problems.join('; ')}`);
|
||||
process.exitCode = 1;
|
||||
} else console.log('ok: the Cesium renderer passes the conformance suite');
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`)
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -362,7 +362,9 @@ async function contacts() {
|
||||
entities: ds?.entities.values.length ?? 0,
|
||||
created,
|
||||
tracked:
|
||||
window.__godsEyeView.viewer.trackedEntity?.gevTrackedId ?? null,
|
||||
window.__godsEyeView.entityRecords.read(
|
||||
window.__godsEyeView.viewer.trackedEntity,
|
||||
)?.trackedId ?? null,
|
||||
cockpit: document.body.classList.contains('cockpit-mode'),
|
||||
});
|
||||
if (samples.length > 5000) samples.splice(0, 1000);
|
||||
@@ -377,8 +379,9 @@ async function contacts() {
|
||||
await page
|
||||
.waitForFunction(
|
||||
() =>
|
||||
window.__godsEyeView.viewer.trackedEntity?.gevTrackedId ===
|
||||
'flights:aaa051',
|
||||
window.__godsEyeView.entityRecords.read(
|
||||
window.__godsEyeView.viewer.trackedEntity,
|
||||
)?.trackedId === 'flights:aaa051',
|
||||
{ timeout: 60_000 },
|
||||
)
|
||||
.catch(() => {});
|
||||
|
||||
+18
-28
@@ -645,44 +645,34 @@ try {
|
||||
`owner=${afterClear.pointerOwner}`,
|
||||
);
|
||||
|
||||
// ── 8. A tool holding the pointer blocks placement, and says so. ─────────
|
||||
// ── 8. Arming takes the pointer from a tool holding it, which is told. ──
|
||||
await page.evaluate(() => {
|
||||
window.__gevQaDrawLost = 0;
|
||||
// A claim answers with a lease; the release takes that lease back.
|
||||
window.__gevQaDrawLease = window.__gevQa.claimPointer('draw');
|
||||
window.__gevQaDrawLease = window.__gevQa.claimPointer('draw', {
|
||||
onLost: () => (window.__gevQaDrawLost += 1),
|
||||
});
|
||||
});
|
||||
await clickChip('set-a');
|
||||
const blocked = await layerState();
|
||||
const taken = await layerState();
|
||||
const lost = await page.evaluate(() => window.__gevQaDrawLost);
|
||||
check(
|
||||
"another tool's pointer claim is never stolen",
|
||||
blocked.pointerOwner === 'draw',
|
||||
`owner=${blocked.pointerOwner}`,
|
||||
'the newest claim takes over: Directions holds the pointer',
|
||||
taken.pointerOwner === 'directions',
|
||||
`owner=${taken.pointerOwner}`,
|
||||
);
|
||||
check('the tool it replaced is told once', lost === 1, `told=${lost}`);
|
||||
check(
|
||||
'nothing is armed, and the row says why the click would do nothing',
|
||||
blocked.chips.find((chip) => chip.id === 'set-a')?.active === false &&
|
||||
/Another map tool/.test(blocked.stats.error || ''),
|
||||
blocked.stats.error,
|
||||
'SET A is armed, and the row has nothing to complain of',
|
||||
taken.chips.find((chip) => chip.id === 'set-a')?.active === true &&
|
||||
!taken.stats.error,
|
||||
taken.stats.error,
|
||||
);
|
||||
// The row is not where the operator is looking after pressing a chip, so the
|
||||
// refusal also has to reach the app's toast (owner field test).
|
||||
const toast = await page.evaluate(() => {
|
||||
const node = document.getElementById('toast');
|
||||
return {
|
||||
text: node?.textContent || '',
|
||||
visible: !!node?.classList.contains('visible'),
|
||||
};
|
||||
});
|
||||
check(
|
||||
'the refusal reaches the app toast, naming the tool and how to leave it',
|
||||
/Draw is active/.test(toast.text) && /then set A/.test(toast.text),
|
||||
JSON.stringify(toast.text),
|
||||
);
|
||||
check('and that toast is actually on screen', toast.visible);
|
||||
await shot(`05-${LABEL}-pointer-blocked-toast.jpg`);
|
||||
const released = await page.evaluate(() =>
|
||||
const staleReleased = await page.evaluate(() =>
|
||||
window.__gevQa.releasePointer(window.__gevQaDrawLease),
|
||||
);
|
||||
check('and it gets the pointer back when it lets go', released);
|
||||
check("the replaced tool's late release frees nothing", !staleReleased);
|
||||
await clickChip('set-a');
|
||||
|
||||
// ── 9. Denver: maneuver dots sit on the ground, not at sea level. ────────
|
||||
if (!SKIP.has('denver')) {
|
||||
|
||||
+299
-148
@@ -65,6 +65,27 @@ const LINE_CLIP = { x: 390, y: 200, width: 510, height: 380 };
|
||||
const canvasShot = () =>
|
||||
page.screenshot({ clip: LINE_CLIP, type: 'png', encoding: 'base64' });
|
||||
|
||||
/**
|
||||
* `canvasShot` once the globe has no imagery or terrain tiles left to load
|
||||
* (bounded: a view that never settles is shot as it is, and the comparison
|
||||
* then reports what it sees). `globe.tilesLoaded` covers the globe only: a
|
||||
* 3D Tiles tileset on a keyed server can still be refining when it is true.
|
||||
*/
|
||||
async function settledCanvasShot() {
|
||||
await page
|
||||
.waitForFunction(
|
||||
() => {
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
scene.requestRender();
|
||||
return scene.globe.tilesLoaded;
|
||||
},
|
||||
{ timeout: 15_000, polling: 100 },
|
||||
)
|
||||
.catch(() => {});
|
||||
await wait(200);
|
||||
return canvasShot();
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber pixels in one shot that are not amber in another of the same view:
|
||||
* a mark's own pixels, apart from imagery and panels that both shots share.
|
||||
@@ -263,39 +284,16 @@ try {
|
||||
}),
|
||||
);
|
||||
|
||||
// The viewer's OWN click actions, captured before the tool ever runs. Both
|
||||
// must be absent while drawing and back — as the SAME functions — after.
|
||||
await page.evaluate(() => {
|
||||
const Cesium = window.__CESIUM__;
|
||||
const stock = window.__godsEyeView.viewer.screenSpaceEventHandler;
|
||||
window.__qaStock = {
|
||||
click:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null,
|
||||
double:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null,
|
||||
// The viewer's own select and follow, which the input port runs: on before
|
||||
// the tool runs, off while drawing, and on again after.
|
||||
const stockActions = async () => {
|
||||
const state = await drawState();
|
||||
return {
|
||||
clickOn: state.stockSingleClick,
|
||||
doubleOn: state.stockDoubleClick,
|
||||
};
|
||||
});
|
||||
const stockActions = () =>
|
||||
page.evaluate(() => {
|
||||
const Cesium = window.__CESIUM__;
|
||||
const stock = window.__godsEyeView.viewer.screenSpaceEventHandler;
|
||||
const live = {
|
||||
click:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null,
|
||||
double:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null,
|
||||
};
|
||||
return {
|
||||
clickPresent: Boolean(live.click),
|
||||
doublePresent: Boolean(live.double),
|
||||
clickIsOriginal: live.click === window.__qaStock.click,
|
||||
doubleIsOriginal: live.double === window.__qaStock.double,
|
||||
hadClick: Boolean(window.__qaStock.click),
|
||||
hadDouble: Boolean(window.__qaStock.double),
|
||||
};
|
||||
});
|
||||
};
|
||||
const beforeDraw = await stockActions();
|
||||
|
||||
// ── enable / disable cycles leave nothing behind ────────────────────────
|
||||
const before = await drawState();
|
||||
@@ -307,35 +305,32 @@ try {
|
||||
}
|
||||
const after = await drawState();
|
||||
check(
|
||||
'three enable/disable cycles add no listener, handler or preview data source',
|
||||
'three enable/disable cycles add no listener, handler or preview set',
|
||||
after.domListeners === before.domListeners &&
|
||||
after.previewDataSources === 1 &&
|
||||
before.previewDataSources === 1 &&
|
||||
after.previewSets === 2 &&
|
||||
before.previewSets === 2 &&
|
||||
after.sceneHandler === false &&
|
||||
after.pointerOwner === null &&
|
||||
after.stockDoubleClick === before.stockDoubleClick,
|
||||
`listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewDataSources}, ` +
|
||||
`listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewSets}, ` +
|
||||
`handler ${after.sceneHandler}, owner ${after.pointerOwner}, stock dblclick ${after.stockDoubleClick}`,
|
||||
);
|
||||
|
||||
// ── the viewer's own click actions are borrowed, then given back ────────
|
||||
// ── the viewer's own click actions are held off, then given back ───────
|
||||
await page.click('#draw-toggle');
|
||||
const duringDraw = await stockActions();
|
||||
check(
|
||||
"Cesium's own selecting click and tracking double-click are both borrowed while drawing",
|
||||
duringDraw.clickPresent === false && duringDraw.doublePresent === false,
|
||||
`click present ${duringDraw.clickPresent}, double present ${duringDraw.doublePresent} ` +
|
||||
`(viewer had click ${duringDraw.hadClick}, double ${duringDraw.hadDouble})`,
|
||||
"Cesium's own selecting click and tracking double-click are both off while drawing",
|
||||
duringDraw.clickOn === false && duringDraw.doubleOn === false,
|
||||
JSON.stringify({ beforeDraw, duringDraw }),
|
||||
);
|
||||
await page.click('#draw-toggle');
|
||||
const afterDraw = await stockActions();
|
||||
check(
|
||||
'and both are restored as the SAME functions, not replacements',
|
||||
afterDraw.clickPresent === duringDraw.hadClick &&
|
||||
afterDraw.doublePresent === duringDraw.hadDouble &&
|
||||
afterDraw.clickIsOriginal &&
|
||||
afterDraw.doubleIsOriginal,
|
||||
JSON.stringify(afterDraw),
|
||||
'and both are back after',
|
||||
afterDraw.clickOn === beforeDraw.clickOn &&
|
||||
afterDraw.doubleOn === beforeDraw.doubleOn,
|
||||
JSON.stringify({ beforeDraw, afterDraw }),
|
||||
);
|
||||
|
||||
// ── a pin, finished with Enter ──────────────────────────────────────────
|
||||
@@ -531,12 +526,26 @@ try {
|
||||
await page.click(rowControl(lineId, 'swatch'));
|
||||
await page.click(rowControl(lineId, 'color-amber'));
|
||||
await markReaches(lineId, { color: 'amber', alpha: 1 });
|
||||
// Only the Line is on the board for its shots. The area's fill pulses, and
|
||||
// under it borderline roofs drift into and out of amber between two shots
|
||||
// of an unchanged scene, on the old build as on this one.
|
||||
const others = await page.evaluate((id) => {
|
||||
const marks = window.__gevAnnotations.list();
|
||||
const ids = marks.filter((m) => m.id !== id && !m.hidden).map((m) => m.id);
|
||||
for (const other of ids) window.__gevAnnotations.setHidden(other, true);
|
||||
return ids;
|
||||
}, lineId);
|
||||
for (const other of others)
|
||||
await markReaches(other, { hidden: true, alpha: 0 });
|
||||
await wait(800);
|
||||
const shown = await canvasShot();
|
||||
// The fly-to above is still refining imagery near the camera at this
|
||||
// point; a tile that sharpens between the two shots repaints roofs into
|
||||
// and out of amber, so each shot waits for the globe to finish loading.
|
||||
const shown = await settledCanvasShot();
|
||||
await page.click(rowControl(lineId, 'toggle'));
|
||||
await markReaches(lineId, { hidden: true, alpha: 0 });
|
||||
await wait(800);
|
||||
const hiddenShot = await canvasShot();
|
||||
const hiddenShot = await settledCanvasShot();
|
||||
// Amber the shown line had and the hidden one lost; amber that appears
|
||||
// only once it is hidden is noise, and must stay small beside it.
|
||||
const gone = await amberOnlyIn(shown, hiddenShot);
|
||||
@@ -548,12 +557,24 @@ try {
|
||||
);
|
||||
await page.click(rowControl(lineId, 'toggle'));
|
||||
await wait(1200);
|
||||
const back = await amberOnlyIn(await canvasShot(), hiddenShot);
|
||||
const back = await amberOnlyIn(await settledCanvasShot(), hiddenShot);
|
||||
check(
|
||||
'and paints again when shown',
|
||||
back > gone * 0.5,
|
||||
`${back} of ${gone} line pixels back`,
|
||||
);
|
||||
await page.evaluate((ids) => {
|
||||
for (const other of ids) window.__gevAnnotations.setHidden(other, false);
|
||||
}, others);
|
||||
const restored = [];
|
||||
for (const other of others)
|
||||
if (await markReaches(other, { hidden: false, alpha: 1 }))
|
||||
restored.push(other);
|
||||
check(
|
||||
'the marks set aside for the Line shots are back on the board',
|
||||
restored.length === others.length,
|
||||
`${restored.length} of ${others.length} back`,
|
||||
);
|
||||
await shot('03-pins-and-shapes');
|
||||
|
||||
// ── Escape cancels the shape, a second Escape leaves draw mode ──────────
|
||||
@@ -601,32 +622,87 @@ try {
|
||||
: 'no CCTV camera or bundled site could be reached — the ownership case cannot be proved',
|
||||
);
|
||||
if (target) {
|
||||
// The camera pose the target was found at: a selecting click flies the
|
||||
// camera to what it picked, so the drawing click has to come back here
|
||||
// and find the target again, or it would land on plain ground.
|
||||
await page.evaluate(() => {
|
||||
const camera = window.__godsEyeView.viewer.camera;
|
||||
window.__qaTargetView = {
|
||||
destination: camera.positionWC.clone(),
|
||||
orientation: {
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
},
|
||||
};
|
||||
});
|
||||
await page.evaluate(clearSelection);
|
||||
await page.evaluate(startSelectionCount);
|
||||
await clickWorld(target.x, target.y, { settle: 900 });
|
||||
const selectedNormally = await page.evaluate(() =>
|
||||
Boolean(window.__godsEyeView.viewer.selectedEntity),
|
||||
);
|
||||
const normal = await page.evaluate(readSelectionCount, target.key);
|
||||
check(
|
||||
`clicking a ${target.layer} selects it when nothing owns the pointer`,
|
||||
selectedNormally,
|
||||
// The CCTV branch looks for `CAM-` Cesium entities and reads the
|
||||
// viewer's selection; neither build draws cameras that way any more, so
|
||||
// it is not reached and the bundled data centre is the target.
|
||||
normal.item > 0 || (target.layerId === 'cctv' && normal.entity),
|
||||
`${normal.item} selection(s) of ${target.key}, ${normal.all} in all, entity ${normal.entity}`,
|
||||
);
|
||||
await page.evaluate(clearSelection);
|
||||
await page.evaluate(() => {
|
||||
window.__godsEyeView.viewer.selectedEntity = undefined;
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
viewer.camera.cancelFlight?.();
|
||||
viewer.camera.setView(window.__qaTargetView);
|
||||
viewer.scene.requestRender();
|
||||
});
|
||||
await page.click('#draw-toggle');
|
||||
await page.click('.pp-mode-btn[data-shape="area"]');
|
||||
await clickWorld(target.x, target.y, { settle: 900 });
|
||||
const whileDrawing = await drawState();
|
||||
const selectedWhileDrawing = await page.evaluate(() =>
|
||||
Boolean(window.__godsEyeView.viewer.selectedEntity),
|
||||
await wait(1500);
|
||||
const again = await onScreen(
|
||||
target.belongs,
|
||||
target.contextPrefix,
|
||||
target.key,
|
||||
);
|
||||
check(
|
||||
`clicking the same ${target.layer} while drawing adds a vertex and selects nothing`,
|
||||
whileDrawing.vertices === 1 && selectedWhileDrawing === false,
|
||||
`vertices ${whileDrawing.vertices}, selected ${selectedWhileDrawing}`,
|
||||
`the ${target.layer} is picked again after the camera returns`,
|
||||
Boolean(again),
|
||||
again ? `at ${again.x},${again.y}` : 'not picked on screen any more',
|
||||
);
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Escape');
|
||||
await wait(150);
|
||||
if (again) {
|
||||
await page.click('#draw-toggle');
|
||||
await page.click('.pp-mode-btn[data-shape="area"]');
|
||||
// Draw mode's own panel must not have covered it: the drawing click has
|
||||
// to land on the same item, not on plain ground.
|
||||
const drawingSpot = await onScreen(
|
||||
target.belongs,
|
||||
target.contextPrefix,
|
||||
target.key,
|
||||
);
|
||||
check(
|
||||
`the ${target.layer} is still picked once draw mode is open`,
|
||||
Boolean(drawingSpot),
|
||||
drawingSpot
|
||||
? `at ${drawingSpot.x},${drawingSpot.y}`
|
||||
: 'not picked on screen in draw mode',
|
||||
);
|
||||
if (drawingSpot) {
|
||||
await page.evaluate(startSelectionCount);
|
||||
await clickWorld(drawingSpot.x, drawingSpot.y, { settle: 900 });
|
||||
const whileDrawing = await drawState();
|
||||
const drawingSelection = await page.evaluate(
|
||||
readSelectionCount,
|
||||
target.key,
|
||||
);
|
||||
check(
|
||||
`clicking the same ${target.layer} while drawing adds a vertex and selects nothing`,
|
||||
whileDrawing.vertices === 1 &&
|
||||
drawingSelection.all === 0 &&
|
||||
!drawingSelection.entity,
|
||||
`vertices ${whileDrawing.vertices}, ${drawingSelection.all} selection(s), entity ${drawingSelection.entity}`,
|
||||
);
|
||||
}
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Escape');
|
||||
await wait(150);
|
||||
}
|
||||
}
|
||||
|
||||
// ── what a reload actually does ─────────────────────────────────────────
|
||||
@@ -664,19 +740,6 @@ try {
|
||||
document.getElementById('draw-toggle')?.getBoundingClientRect().width > 0,
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
// The reload built a new page context: re-capture the viewer's own click
|
||||
// actions so the identity comparisons below still mean something.
|
||||
await page.evaluate(() => {
|
||||
const Cesium = window.__CESIUM__;
|
||||
const stock = window.__godsEyeView.viewer.screenSpaceEventHandler;
|
||||
window.__qaStock = {
|
||||
click:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null,
|
||||
double:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null,
|
||||
};
|
||||
});
|
||||
await page.evaluate((view) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
viewer.camera.cancelFlight?.();
|
||||
@@ -813,13 +876,10 @@ try {
|
||||
finalState.active === false &&
|
||||
finalState.pointerOwner === null &&
|
||||
finalState.sceneHandler === false &&
|
||||
finalState.previewDataSources === 1,
|
||||
finalState.previewSets === 2,
|
||||
JSON.stringify(finalState),
|
||||
);
|
||||
// ── destroy(): the shell disposing the tool leaves nothing behind ───────
|
||||
const beforeDestroy = await page.evaluate(
|
||||
() => window.__godsEyeView.viewer.dataSources.length,
|
||||
);
|
||||
await page.click('#draw-toggle'); // destroy from an ACTIVE session: the harder case
|
||||
await wait(200);
|
||||
const destroyed = await page.evaluate(async () => {
|
||||
@@ -827,24 +887,15 @@ try {
|
||||
const wasActive = tool.active;
|
||||
await tool.destroy();
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const Cesium = window.__CESIUM__;
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
let previews = 0;
|
||||
for (let i = 0; i < viewer.dataSources.length; i += 1)
|
||||
if (viewer.dataSources.get(i)?.name === 'gev-draw-preview') previews += 1;
|
||||
const diagnostics = tool.diagnostics();
|
||||
return {
|
||||
wasActive,
|
||||
diagnostics: tool.diagnostics(),
|
||||
previews,
|
||||
dataSources: viewer.dataSources.length,
|
||||
diagnostics,
|
||||
previews: diagnostics.previewSets,
|
||||
handleGone: window.__gevDrawTool === undefined,
|
||||
clickRestored:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) ===
|
||||
window.__qaStock.click,
|
||||
doubleRestored:
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ===
|
||||
window.__qaStock.double,
|
||||
// The viewer's own select and follow run again.
|
||||
clickRestored: diagnostics.stockSingleClick,
|
||||
doubleRestored: diagnostics.stockDoubleClick,
|
||||
drawingClass: document.body.classList.contains('gev-drawing'),
|
||||
};
|
||||
});
|
||||
@@ -859,11 +910,9 @@ try {
|
||||
JSON.stringify(destroyed.diagnostics),
|
||||
);
|
||||
check(
|
||||
'destroy() detaches the preview data source and gives the window handle back',
|
||||
destroyed.previews === 0 &&
|
||||
destroyed.dataSources === beforeDestroy - 1 &&
|
||||
destroyed.handleGone,
|
||||
`previews ${destroyed.previews}, dataSources ${beforeDestroy} → ${destroyed.dataSources}, handle gone ${destroyed.handleGone}`,
|
||||
'destroy() disposes the preview draw sets and gives the window handle back',
|
||||
destroyed.previews === 0 && destroyed.handleGone,
|
||||
`preview sets ${destroyed.previews}, handle gone ${destroyed.handleGone}`,
|
||||
);
|
||||
check(
|
||||
"destroy() returns Cesium's own click actions",
|
||||
@@ -930,17 +979,24 @@ async function findClickableTarget() {
|
||||
viewer.scene.requestRender();
|
||||
}, camera);
|
||||
await wait(4000);
|
||||
const spot = await onScreen(
|
||||
(entity) => typeof entity.id === 'string' && entity.id.startsWith('CAM-'),
|
||||
);
|
||||
if (spot) return { ...spot, layer: 'CCTV camera' };
|
||||
const spot = await onScreen(cameraEntity);
|
||||
if (spot)
|
||||
return {
|
||||
...spot,
|
||||
layer: 'CCTV camera',
|
||||
layerId: 'cctv',
|
||||
belongs: cameraEntity,
|
||||
contextPrefix: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Bundled infrastructure as the keyless fallback: a different guarded handler,
|
||||
// the same shared claim, and always present without a key.
|
||||
const site = await page
|
||||
.evaluate(async () => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
// The app registers each local feature's context as `<layer id>:<feature id>`,
|
||||
// with its coordinates, whether the layer draws Cesium entities or
|
||||
// through the draw port.
|
||||
await window.__godsEyeView.dataManager.setEnabled(
|
||||
'local-datacenters',
|
||||
true,
|
||||
@@ -948,30 +1004,16 @@ async function findClickableTarget() {
|
||||
origin: 'user',
|
||||
},
|
||||
);
|
||||
const centreOf = (entity) => {
|
||||
const time = viewer.clock.currentTime;
|
||||
const point = entity.position?.getValue?.(time);
|
||||
if (point) return point;
|
||||
const hierarchy = entity.polygon?.hierarchy?.getValue?.(time);
|
||||
if (hierarchy?.positions?.length) return hierarchy.positions[0];
|
||||
const line = entity.polyline?.positions?.getValue?.(time);
|
||||
return line?.length ? line[0] : null;
|
||||
};
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
for (let i = 0; i < viewer.dataSources.length; i += 1) {
|
||||
for (const entity of viewer.dataSources.get(i).entities.values) {
|
||||
if (entity.__localLayerId !== 'local-datacenters') continue;
|
||||
const point = centreOf(entity);
|
||||
if (!point) continue;
|
||||
const carto = window.Cesium
|
||||
? window.Cesium.Cartographic.fromCartesian(point)
|
||||
: viewer.scene.globe.ellipsoid.cartesianToCartographic(point);
|
||||
if (!carto) continue;
|
||||
return {
|
||||
lon: (carto.longitude * 180) / Math.PI,
|
||||
lat: (carto.latitude * 180) / Math.PI,
|
||||
};
|
||||
}
|
||||
const records = window.__gevContextStore?.entities?.values() ?? [];
|
||||
for (const record of records) {
|
||||
if (!String(record?.id).startsWith('local-datacenters:')) continue;
|
||||
if (
|
||||
!Number.isFinite(record.latitude) ||
|
||||
!Number.isFinite(record.longitude)
|
||||
)
|
||||
continue;
|
||||
return { lon: record.longitude, lat: record.latitude };
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
@@ -993,21 +1035,97 @@ async function findClickableTarget() {
|
||||
viewer.scene.requestRender();
|
||||
}, site);
|
||||
await wait(4000);
|
||||
const spot = await onScreen(
|
||||
(entity) => entity.__localLayerId === 'local-datacenters',
|
||||
const spot = await onScreen(dataCentre, 'local-datacenters:');
|
||||
return spot
|
||||
? {
|
||||
...spot,
|
||||
layer: 'data centre',
|
||||
layerId: 'local-datacenters',
|
||||
belongs: dataCentre,
|
||||
contextPrefix: 'local-datacenters:',
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
/** A CCTV camera entity (runs in the page through `onScreen`). */
|
||||
function cameraEntity(entity) {
|
||||
return typeof entity.id === 'string' && entity.id.startsWith('CAM-');
|
||||
}
|
||||
|
||||
/**
|
||||
* A bundled data centre: a Cesium entity carrying its context, or a draw-port
|
||||
* pick id `{ set, id }` from a set named `<layer id>:<n>:<part>` (runs in the
|
||||
* page through `onScreen`).
|
||||
*/
|
||||
function dataCentre(entity) {
|
||||
return (
|
||||
window.__godsEyeView.entityRecords
|
||||
.read(entity)
|
||||
?.contextId?.startsWith('local-datacenters:') ||
|
||||
(typeof entity?.set === 'string' &&
|
||||
entity.set.startsWith('local-datacenters:'))
|
||||
);
|
||||
return spot ? { ...spot, layer: 'data centre' } : null;
|
||||
}
|
||||
|
||||
/** Clear both selection slots (runs in the page). */
|
||||
function clearSelection() {
|
||||
window.__godsEyeView.viewer.selectedEntity = undefined;
|
||||
const store = window.__gevContextStore;
|
||||
if (store) store.selectedEntityId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count click selections from now on (runs in the page). A layer selects
|
||||
* through the shared context store, which announces each selection with
|
||||
* `gev:entity-selected`; one drawn through the draw port has no Cesium entity
|
||||
* to set as the viewer's selection. Counting the announcements rather than
|
||||
* reading the slot keeps an earlier selection, or a tracking layer refilling
|
||||
* the slot without announcing, from deciding the result.
|
||||
*/
|
||||
function startSelectionCount() {
|
||||
const seen = [];
|
||||
window.removeEventListener('gev:entity-selected', window.__qaOnSelected);
|
||||
window.__qaSelections = seen;
|
||||
window.__qaOnSelected = (event) => seen.push(event.detail ?? null);
|
||||
window.addEventListener('gev:entity-selected', window.__qaOnSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Selections since `startSelectionCount` (runs in the page): `all`, those of
|
||||
* the item whose context id is `key`, and whether the viewer holds a selected
|
||||
* Cesium entity.
|
||||
* @param {string} key
|
||||
* @returns {{ all: number, item: number, entity: boolean }}
|
||||
*/
|
||||
function readSelectionCount(key) {
|
||||
const seen = window.__qaSelections || [];
|
||||
return {
|
||||
all: seen.length,
|
||||
item: seen.filter((record) => record?.id === key).length,
|
||||
entity: Boolean(window.__godsEyeView.viewer.selectedEntity),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Canvas coordinates of the first entity matching `belongs` that is on screen
|
||||
* and clear of the side panels. Annotation marks and the draw tool's own
|
||||
* preview vertices are on screen too, so the predicate has to be specific.
|
||||
* With `contextPrefix`, the context store's records under that prefix are
|
||||
* candidates too (at their ground coordinates), for a layer drawn through the
|
||||
* draw port, which has no entities to walk; `belongs` then also receives the
|
||||
* draw-port pick id. Returns the spot and `key`, the picked item's context id
|
||||
* (from the entity's record or the draw-port item's `meta`; without a prefix,
|
||||
* the entity's own id); with `wantKey`, only that item counts.
|
||||
*/
|
||||
async function onScreen(belongs, timeout = 20_000) {
|
||||
async function onScreen(
|
||||
belongs,
|
||||
contextPrefix = null,
|
||||
wantKey = null,
|
||||
timeout = 20_000,
|
||||
) {
|
||||
return page
|
||||
.waitForFunction(
|
||||
(belongsSource) => {
|
||||
(belongsSource, prefix, want) => {
|
||||
// eslint-disable-next-line no-new-func
|
||||
const belongsTo = new Function(`return (${belongsSource})`)();
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
@@ -1018,29 +1136,62 @@ async function onScreen(belongs, timeout = 20_000) {
|
||||
if (source?.name === 'gev-draw-preview') continue;
|
||||
collections.push(source.entities);
|
||||
}
|
||||
const candidates = [];
|
||||
for (const source of collections) {
|
||||
for (const entity of source.values) {
|
||||
if (!belongsTo(entity)) continue;
|
||||
const position = entity.position?.getValue?.(
|
||||
viewer.clock.currentTime,
|
||||
);
|
||||
if (!position) continue;
|
||||
const window2d = scene.cartesianToCanvasCoordinates(position);
|
||||
if (!window2d) continue;
|
||||
const { x, y } = window2d;
|
||||
if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue;
|
||||
// Projecting into the window is not the same as being clickable:
|
||||
// the entity may be beyond the horizon or behind a building. Only a
|
||||
// spot where the scene actually picks it proves the control case.
|
||||
const hit = scene.pick({ x: Math.round(x), y: Math.round(y) });
|
||||
if (!hit?.id || !belongsTo(hit.id)) continue;
|
||||
return { x: Math.round(x), y: Math.round(y) };
|
||||
if (position) candidates.push(position);
|
||||
}
|
||||
}
|
||||
if (prefix) {
|
||||
const ellipsoid = scene.globe.ellipsoid;
|
||||
for (const record of window.__gevContextStore?.entities?.values() ??
|
||||
[]) {
|
||||
if (!String(record?.id).startsWith(prefix)) continue;
|
||||
if (
|
||||
!Number.isFinite(record.latitude) ||
|
||||
!Number.isFinite(record.longitude)
|
||||
)
|
||||
continue;
|
||||
candidates.push(
|
||||
ellipsoid.cartographicToCartesian({
|
||||
longitude: (record.longitude * Math.PI) / 180,
|
||||
latitude: (record.latitude * Math.PI) / 180,
|
||||
height: 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const position of candidates) {
|
||||
const window2d = scene.cartesianToCanvasCoordinates(position);
|
||||
if (!window2d) continue;
|
||||
const { x, y } = window2d;
|
||||
if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue;
|
||||
// Projecting into the window is not the same as being clickable:
|
||||
// the entity may be beyond the horizon or behind a building. Only a
|
||||
// spot where the scene actually picks it proves the control case.
|
||||
const hit = scene.pick({ x: Math.round(x), y: Math.round(y) });
|
||||
if (!hit?.id || !belongsTo(hit.id)) continue;
|
||||
// The picked item's context id: an entity's own record, or that of
|
||||
// the object a draw-port item carries as its `meta`.
|
||||
const pickId = hit.id;
|
||||
const records = window.__godsEyeView.entityRecords;
|
||||
const key =
|
||||
records.read(pickId)?.contextId ||
|
||||
records.read(pickId.meta)?.contextId ||
|
||||
(prefix ? null : String(pickId.id));
|
||||
if (!key || (want && key !== want)) continue;
|
||||
return { x: Math.round(x), y: Math.round(y), key };
|
||||
}
|
||||
return false;
|
||||
},
|
||||
{ timeout, polling: 500 },
|
||||
belongs.toString(),
|
||||
contextPrefix,
|
||||
wantKey,
|
||||
)
|
||||
.then(
|
||||
(handle) => handle.jsonValue(),
|
||||
|
||||
+131
-82
@@ -103,49 +103,113 @@ try {
|
||||
destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
// One form for both sides: Cesium's own KML reading of the file (the
|
||||
// control) and what the import drew (the candidate).
|
||||
const css = (value) =>
|
||||
value === undefined || value === null
|
||||
? undefined
|
||||
: (Array.isArray(value)
|
||||
? new C.Color(...value)
|
||||
: C.Color.fromCssColorString(value)
|
||||
).toCssColorString();
|
||||
const at = (p) => {
|
||||
const c = C.Cartographic.fromCartesian(new C.Cartesian3(p.x, p.y, p.z));
|
||||
return [
|
||||
+C.Math.toDegrees(c.longitude).toFixed(6),
|
||||
+C.Math.toDegrees(c.latitude).toFixed(6),
|
||||
];
|
||||
};
|
||||
const sorted = (rows) =>
|
||||
rows.sort(
|
||||
(a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind),
|
||||
);
|
||||
window.__qaStyleSnapshot = (source) => {
|
||||
const now = viewer.clock.currentTime;
|
||||
const images = new Map();
|
||||
const imageValue = (p) => {
|
||||
const value = p?.getValue(now);
|
||||
if (value?.tagName !== 'CANVAS') return value;
|
||||
if (!images.has(value)) images.set(value, value.toDataURL());
|
||||
return images.get(value);
|
||||
};
|
||||
const color = (p) => p?.getValue(now)?.toCssColorString();
|
||||
const positions = (p) => p?.getValue(now)?.map((v) => [v.x, v.y, v.z]);
|
||||
const renderedPins = new Map();
|
||||
const collection = source.importedBillboards;
|
||||
if (collection)
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const pin = collection.get(i);
|
||||
renderedPins.set(pin.id, pin);
|
||||
}
|
||||
const actual = (e, key, fallback) => {
|
||||
const pin = renderedPins.get(e);
|
||||
return pin ? pin[key] : (e.billboard?.[key]?.getValue(now) ?? fallback);
|
||||
};
|
||||
return (source.importedEntities || source.entities.values)
|
||||
.map((e) => ({
|
||||
name: e.name,
|
||||
point: renderedPins.get(e)?.position || e.position?.getValue(now),
|
||||
scale: e.billboard ? actual(e, 'scale', 1) : undefined,
|
||||
rotation: e.billboard ? actual(e, 'rotation', 0) : undefined,
|
||||
image: renderedPins.get(e)?.image || imageValue(e.billboard?.image),
|
||||
color: e.billboard
|
||||
? actual(e, 'color', C.Color.WHITE).toCssColorString()
|
||||
: undefined,
|
||||
width: e.polyline?.width?.getValue(now),
|
||||
lineColor: color(e.polyline?.material?.color),
|
||||
line: positions(e.polyline?.positions),
|
||||
fill: e.polygon?.fill?.getValue(now),
|
||||
outline: e.polygon?.outline?.getValue(now),
|
||||
polygonColor: color(e.polygon?.material?.color),
|
||||
polygon: e.polygon?.hierarchy
|
||||
?.getValue(now)
|
||||
?.positions?.map((v) => [v.x, v.y, v.z]),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return sorted(
|
||||
source.entities.values
|
||||
.filter((e) => e.billboard || e.polyline || e.polygon)
|
||||
.map((e) => {
|
||||
if (e.billboard)
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'pin',
|
||||
point: at(e.position.getValue(now)),
|
||||
scale: e.billboard.scale?.getValue(now) ?? 1,
|
||||
heading: Math.round(
|
||||
-C.Math.toDegrees(e.billboard.rotation?.getValue(now) ?? 0),
|
||||
),
|
||||
image: Boolean(e.billboard.image?.getValue(now)),
|
||||
color: css(
|
||||
e.billboard.color?.getValue(now)?.toCssColorString() ??
|
||||
'white',
|
||||
),
|
||||
};
|
||||
if (e.polyline)
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'line',
|
||||
width: e.polyline.width?.getValue(now),
|
||||
color: e.polyline.material?.color
|
||||
?.getValue(now)
|
||||
?.toCssColorString(),
|
||||
line: e.polyline.positions.getValue(now).map(at),
|
||||
};
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'polygon',
|
||||
fill: e.polygon.fill?.getValue(now) !== false,
|
||||
color: e.polygon.material?.color
|
||||
?.getValue(now)
|
||||
?.toCssColorString(),
|
||||
polygon: e.polygon.hierarchy.getValue(now).positions.map(at),
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
window.__qaDrawnSnapshot = (id) => {
|
||||
const drawn = window.__gevGeoImport.drawn(id);
|
||||
const ring = (points) =>
|
||||
points.map((p) => [+p.lon.toFixed(6), +p.lat.toFixed(6)]);
|
||||
return sorted([
|
||||
...drawn.icons.map((i) => ({
|
||||
name: i.meta?.name,
|
||||
kind: 'pin',
|
||||
point: [+i.pos.lon.toFixed(6), +i.pos.lat.toFixed(6)],
|
||||
scale: i.scale ?? 1,
|
||||
// A KML heading is drawn as a turn on screen, clockwise.
|
||||
heading: Math.round((-(i.rotation ?? 0) * 180) / Math.PI),
|
||||
image: Boolean(i.image),
|
||||
color: css(i.color ?? 'white'),
|
||||
})),
|
||||
...drawn.lines.map((l) => ({
|
||||
name: l.meta?.name,
|
||||
kind: 'line',
|
||||
width: l.widthPx,
|
||||
color: css(l.style.color),
|
||||
line: l.positions.map(at),
|
||||
})),
|
||||
...drawn.shapes
|
||||
.filter((s) => s.geometry.kind === 'polygon')
|
||||
.map((s) => ({
|
||||
name: s.meta?.name,
|
||||
kind: 'polygon',
|
||||
fill: Boolean(s.fill),
|
||||
color: css(s.fill),
|
||||
polygon: ring(s.geometry.rings[0]),
|
||||
})),
|
||||
]);
|
||||
};
|
||||
// The import's draw sets among the scene's primitives.
|
||||
window.__qaImportHosts = () => {
|
||||
let n = 0;
|
||||
for (let i = 0; i < viewer.scene.primitives.length; i++)
|
||||
if (
|
||||
String(viewer.scene.primitives.get(i).drawSetId).startsWith(
|
||||
'geo-import:',
|
||||
)
|
||||
)
|
||||
n += 1;
|
||||
return n;
|
||||
};
|
||||
window.__qaUnsharedKml = async (text) => {
|
||||
const doc = new DOMParser().parseFromString(text, 'application/xml');
|
||||
@@ -159,25 +223,22 @@ try {
|
||||
canvas: viewer.scene.canvas,
|
||||
clampToGround: true,
|
||||
});
|
||||
for (const e of source.importedEntities || source.entities.values)
|
||||
e.label = undefined;
|
||||
for (const e of source.entities.values) e.label = undefined;
|
||||
return source;
|
||||
};
|
||||
});
|
||||
const equivalent = await page.evaluate(async (text) => {
|
||||
const { viewer } = window.__godsEyeView;
|
||||
const control = await window.__qaUnsharedKml(text);
|
||||
const outcomes = await window.__gevGeoImport.importFiles([
|
||||
new File([text], 'style-equivalence.kml'),
|
||||
]);
|
||||
const candidate = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
const expected = JSON.stringify(window.__qaStyleSnapshot(control));
|
||||
const actual = JSON.stringify(window.__qaDrawnSnapshot(outcomes[0]?.id));
|
||||
const result = {
|
||||
ok: outcomes[0]?.ok,
|
||||
same:
|
||||
JSON.stringify(window.__qaStyleSnapshot(control)) ===
|
||||
JSON.stringify(window.__qaStyleSnapshot(candidate)),
|
||||
entities: (candidate.importedEntities || candidate.entities.values)
|
||||
.length,
|
||||
same: expected === actual,
|
||||
entities: JSON.parse(actual).length,
|
||||
...(expected === actual ? {} : { expected, actual }),
|
||||
};
|
||||
await window.__gevGeoImport.remove(outcomes[0]?.id);
|
||||
return result;
|
||||
@@ -188,8 +249,8 @@ try {
|
||||
JSON.stringify(equivalent),
|
||||
);
|
||||
|
||||
// The control bypasses the former style-count refusal solely in this test,
|
||||
// to compare native unshared rendering against normalized rendering.
|
||||
// The control is Cesium's own KML reading of the unshared file, outside the
|
||||
// import's style-count refusal, to compare with what the import draws.
|
||||
await page.evaluate(async (text) => {
|
||||
const source = await window.__qaUnsharedKml(text);
|
||||
window.__qaUnsharedSnapshot = JSON.stringify(
|
||||
@@ -250,9 +311,7 @@ try {
|
||||
);
|
||||
|
||||
const loadPicked = async (filename, expected) => {
|
||||
const before = await page.evaluate(
|
||||
() => window.__godsEyeView.viewer.dataSources.length,
|
||||
);
|
||||
const before = await page.evaluate(() => window.__qaImportHosts());
|
||||
const priorIds = await page.evaluate(() =>
|
||||
window.__gevGeoImport.list().map((f) => f.id),
|
||||
);
|
||||
@@ -276,7 +335,7 @@ try {
|
||||
const state = await page.evaluate(() => ({
|
||||
files: window.__gevGeoImport.list(),
|
||||
hint: document.getElementById('geo-import-hint').textContent,
|
||||
sources: window.__godsEyeView.viewer.dataSources.length,
|
||||
sources: window.__qaImportHosts(),
|
||||
}));
|
||||
const item = state.files.find((f) => !priorIds.includes(f.id));
|
||||
check(
|
||||
@@ -285,7 +344,7 @@ try {
|
||||
(expected === null
|
||||
? item?.entityCount > 0
|
||||
: item?.entityCount === expected) &&
|
||||
state.sources === before + 1,
|
||||
state.sources > before,
|
||||
JSON.stringify({
|
||||
bytes: fs.statSync(filename).size,
|
||||
loadMs: Math.round(performance.now() - started),
|
||||
@@ -296,14 +355,12 @@ try {
|
||||
};
|
||||
const item = await loadPicked(file, 5000);
|
||||
if (item) {
|
||||
const same = await page.evaluate(() => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const source = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
return (
|
||||
JSON.stringify(window.__qaStyleSnapshot(source)) ===
|
||||
window.__qaUnsharedSnapshot
|
||||
);
|
||||
});
|
||||
const same = await page.evaluate(
|
||||
(id) =>
|
||||
JSON.stringify(window.__qaDrawnSnapshot(id)) ===
|
||||
window.__qaUnsharedSnapshot,
|
||||
item.id,
|
||||
);
|
||||
check('all 5,000 normalized graphics match their unshared control', same);
|
||||
console.log('NORMALIZED CANDIDATE', JSON.stringify(await measure()));
|
||||
await page.evaluate((id) => window.__gevGeoImport.remove(id), item.id);
|
||||
@@ -335,32 +392,24 @@ try {
|
||||
JSON.stringify(clockBefore) === JSON.stringify(clockAfter),
|
||||
);
|
||||
if (suppliedItem && process.argv.includes('--expect-local-pins')) {
|
||||
const markers = await page.evaluate(() => {
|
||||
const markers = await page.evaluate((id) => {
|
||||
const { viewer } = window.__godsEyeView,
|
||||
C = window.__CESIUM__;
|
||||
const source = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
const points = (
|
||||
source.importedEntities || source.entities.values
|
||||
).filter((e) => e.position && e.billboard);
|
||||
const images = points.filter((e) =>
|
||||
e.billboard.image?.getValue(viewer.clock.currentTime),
|
||||
);
|
||||
const drawn = window.__gevGeoImport.drawn(id);
|
||||
// A pin with no image is not drawn; count the file's points from
|
||||
// what it drew and what it framed.
|
||||
const points = drawn.icons;
|
||||
const images = points.filter((i) => i.image);
|
||||
if (images.length) {
|
||||
const at = C.Cartographic.fromCartesian(
|
||||
images[0].position.getValue(viewer.clock.currentTime),
|
||||
);
|
||||
const { lon, lat } = images[0].pos;
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.camera.setView({
|
||||
destination: C.Cartesian3.fromRadians(
|
||||
at.longitude,
|
||||
at.latitude,
|
||||
100000,
|
||||
),
|
||||
destination: C.Cartesian3.fromDegrees(lon, lat, 100000),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
}
|
||||
return { points: points.length, images: images.length };
|
||||
});
|
||||
}, suppliedItem.id);
|
||||
check(
|
||||
'supplied point markers have drawable images',
|
||||
markers.points > 0 && markers.images === markers.points,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
/** Import regressions through the real UI controller and Cesium loaders.
|
||||
/** Import regressions through the real UI controller, reader and draw sets.
|
||||
* Run against dev and preview: QA_BASE_URL=http://localhost:4173 node scripts/qa-geo-import-regressions.mjs
|
||||
*/
|
||||
import puppeteer from 'puppeteer';
|
||||
@@ -129,13 +129,13 @@ try {
|
||||
? JSON.stringify(value)
|
||||
: value;
|
||||
const [outcome] = await tool.importFiles([new File([content], name)]);
|
||||
return {
|
||||
outcome,
|
||||
source: outcome.ok
|
||||
? viewer.dataSources.get(viewer.dataSources.length - 1)
|
||||
: null,
|
||||
};
|
||||
// What the file drew: its draw sets' items, by kind.
|
||||
return { outcome, drawn: outcome.ok ? tool.drawn(outcome.id) : null };
|
||||
};
|
||||
const items = (r) =>
|
||||
r.drawn ? [...r.drawn.icons, ...r.drawn.lines, ...r.drawn.shapes] : [];
|
||||
const cartesian = (p) => new C.Cartesian3(p.x, p.y, p.z);
|
||||
const heightOf = (p) => C.Cartographic.fromCartesian(cartesian(p)).height;
|
||||
const remove = (r) => {
|
||||
if (r.outcome.ok) tool.remove(r.outcome.id);
|
||||
};
|
||||
@@ -171,26 +171,19 @@ try {
|
||||
},
|
||||
'xyz.geojson',
|
||||
);
|
||||
const pin = (r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.billboard,
|
||||
),
|
||||
polygon = (r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.polygon,
|
||||
);
|
||||
const pin = r.drawn?.icons[0],
|
||||
polygon = r.drawn?.shapes.find((s) => s.geometry.kind === 'polygon');
|
||||
check(
|
||||
'XYZ ground footprint and isolated entity IDs',
|
||||
r.outcome.ok &&
|
||||
pin.id !== 'kartaview-owned' &&
|
||||
Math.abs(
|
||||
C.Cartographic.fromCartesian(pin.position.getValue(now)).height,
|
||||
) < 0.01 &&
|
||||
polygon.polygon.perPositionHeight?.getValue(now) !== true,
|
||||
Math.abs(pin.pos.height) < 0.01 &&
|
||||
polygon.geometry.perPositionHeight !== true,
|
||||
{ pin: pin?.pos, polygon: polygon?.geometry.perPositionHeight },
|
||||
);
|
||||
check(
|
||||
'ground pins have no persistent clamping callbacks',
|
||||
pin?.billboard.heightReference?.getValue(now) ===
|
||||
C.HeightReference.NONE &&
|
||||
pin.billboard.disableDepthTestDistance.getValue(now) === Infinity,
|
||||
pin?.height === 'absolute' && pin.disableDepthTest === Infinity,
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -201,24 +194,17 @@ try {
|
||||
),
|
||||
'tracks.kml',
|
||||
);
|
||||
const find = (name) =>
|
||||
(r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.name === name,
|
||||
);
|
||||
const find = (name) => r.drawn?.lines.find((l) => l.meta?.name === name);
|
||||
check(
|
||||
'ground tracks and untessellated authored lines clamp',
|
||||
find('ground')?.polyline.clampToGround?.getValue(now) &&
|
||||
find('line')?.polyline.clampToGround?.getValue(now),
|
||||
find('ground')?.mode === 'draped' && find('line')?.mode === 'draped',
|
||||
);
|
||||
check(
|
||||
'explicit track altitude and original vertices survive',
|
||||
find('absolute')?.polyline.positions.getValue(now).length === 2 &&
|
||||
find('absolute')
|
||||
.polyline.positions.getValue(now)
|
||||
.every(
|
||||
(p) =>
|
||||
Math.abs(C.Cartographic.fromCartesian(p).height - 10000) < 0.01,
|
||||
),
|
||||
find('absolute')?.positions.length === 2 &&
|
||||
find('absolute').positions.every(
|
||||
(p) => Math.abs(heightOf(p) - 10000) < 0.01,
|
||||
),
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -245,10 +231,7 @@ try {
|
||||
);
|
||||
check(
|
||||
'import show controls own previously hidden KML content',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values).every(
|
||||
(e) => e.isShowing,
|
||||
),
|
||||
r.outcome.ok && r.drawn.show && r.drawn.icons.length === 1,
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -260,9 +243,7 @@ try {
|
||||
check(
|
||||
'a colored overlay without an icon is drawable',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values).some(
|
||||
(e) => e.rectangle,
|
||||
),
|
||||
r.drawn.shapes.some((s) => s.geometry.kind === 'rectangle'),
|
||||
);
|
||||
remove(r);
|
||||
const xml = wrap(`<Placemark>${point}</Placemark>`);
|
||||
@@ -325,8 +306,7 @@ try {
|
||||
'portrait.geojson',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2300));
|
||||
const positions = (r.source?.importedEntities ||
|
||||
r.source?.entities.values)[0].polyline.positions.getValue(now);
|
||||
const positions = r.drawn?.lines[0]?.positions.map(cartesian);
|
||||
const screen = positions?.map((p) =>
|
||||
C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p),
|
||||
);
|
||||
@@ -349,11 +329,9 @@ try {
|
||||
'intercontinental.geojson',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2300));
|
||||
const intercontinental = (
|
||||
r.source?.importedEntities || r.source?.entities.values
|
||||
)
|
||||
.filter((e) => e.position)
|
||||
.map((e) => e.position.getValue(now));
|
||||
const intercontinental = r.drawn?.icons.map(({ pos }) =>
|
||||
C.Cartesian3.fromDegrees(pos.lon, pos.lat, pos.height),
|
||||
);
|
||||
const occluder = new C.EllipsoidalOccluder(
|
||||
C.Ellipsoid.WGS84,
|
||||
viewer.camera.positionWC,
|
||||
@@ -383,9 +361,11 @@ try {
|
||||
check(
|
||||
'a wall contributes both endpoints to the flight',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values)
|
||||
.find((e) => e.wall)
|
||||
?.wall.positions.getValue(now)
|
||||
r.drawn.shapes
|
||||
.find((s) => s.geometry.kind === 'wall')
|
||||
?.geometry.positions.map(({ lon, lat, height }) =>
|
||||
C.Cartesian3.fromDegrees(lon, lat, height),
|
||||
)
|
||||
.every((p) => {
|
||||
const s = C.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
@@ -447,11 +427,11 @@ try {
|
||||
{ type: 'Point', coordinates: [-122.5, 37.7, 0] },
|
||||
'mesh-point.geojson',
|
||||
);
|
||||
const meshPoint = (r.source?.importedEntities || r.source?.entities.values)
|
||||
.find((e) => e.billboard)
|
||||
?.position.getValue(now);
|
||||
const meshHeight =
|
||||
meshPoint && C.Cartographic.fromCartesian(meshPoint).height;
|
||||
const meshPin = r.drawn?.icons[0]?.pos;
|
||||
const meshPoint =
|
||||
meshPin &&
|
||||
C.Cartesian3.fromDegrees(meshPin.lon, meshPin.lat, meshPin.height);
|
||||
const meshHeight = meshPin?.height;
|
||||
check(
|
||||
'native 3D Tiles ground sampling keeps pins on the rendered mesh',
|
||||
r.outcome.ok && Math.abs(meshHeight - 2000) < 2,
|
||||
@@ -480,7 +460,7 @@ try {
|
||||
meshHeight,
|
||||
},
|
||||
);
|
||||
const groundSource = r.source;
|
||||
const groundFile = r.outcome.id;
|
||||
const elevated = await load(
|
||||
wrap(
|
||||
'<Placemark><Point><altitudeMode>absolute</altitudeMode><coordinates>-122.5,37.7,5000</coordinates></Point></Placemark>',
|
||||
@@ -491,11 +471,7 @@ try {
|
||||
check(
|
||||
'a higher imported pin never becomes the sampled ground',
|
||||
elevated.outcome.ok &&
|
||||
Math.abs(
|
||||
C.Cartographic.fromCartesian(
|
||||
groundSource.importedBillboards.get(0).position,
|
||||
).height - 2000,
|
||||
) < 2,
|
||||
Math.abs(tool.drawn(groundFile).icons[0].pos.height - 2000) < 2,
|
||||
);
|
||||
remove(elevated);
|
||||
remove(r);
|
||||
|
||||
+73
-68
@@ -1,20 +1,20 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Rendered acceptance for UTILITIES ▸ Import: real files through the real file
|
||||
* input and a real drop, parsed by Cesium in the page.
|
||||
* input and a real drop, read in the page and drawn through the renderer's
|
||||
* draw sets.
|
||||
*
|
||||
* Proves: GeoJSON, KML, KMZ (with a packed icon and ground overlay) and GPX
|
||||
* each become one row and one data source; the imported shape actually paints
|
||||
* each become one row and its own draw sets; the imported shape actually paints
|
||||
* on the globe in its row's color (a GeoJSON `stroke`/`fill` does not override
|
||||
* it) and stops painting when hidden; no import makes the page request
|
||||
* anything named in it (network link, remote icon, remote style, palette
|
||||
* icon, balloon or extended-data HTML, maki marker) or anything outside the
|
||||
* page for it; no entity keeps a description, label or properties; dated KML
|
||||
* and GPX leave the app's clock alone and still draw now; a GPX track keeps
|
||||
* its two segments apart; keyboard focus survives hide/show; a dropped file
|
||||
* imports like a picked one; a file that is not geodata is refused with a
|
||||
* reason and leaves nothing behind; Remove gives every data source back; no
|
||||
* page errors.
|
||||
* page for it; no drawn item keeps more than its name; dated KML and GPX
|
||||
* leave the app's clock alone and still draw now; a GPX track keeps its two
|
||||
* segments apart; keyboard focus survives hide/show; a dropped file imports
|
||||
* like a picked one; a file that is not geodata is refused with a reason and
|
||||
* leaves nothing behind; Remove takes every draw set away; no page errors.
|
||||
*
|
||||
* Usage: dev server up (`npm run dev`), then `node scripts/qa-geo-import.mjs`.
|
||||
* QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR, QA_HEADFUL=1.
|
||||
@@ -181,8 +181,9 @@ page.on('console', (message) => {
|
||||
if (/Ignoring clampToGround/.test(message.text()))
|
||||
errors.push(message.text());
|
||||
});
|
||||
// Anything a file names, and the icon assets Cesium would load on a file's
|
||||
// behalf (KML palette icons from maps.google.com, GeoJSON maki markers).
|
||||
// Anything a file names, and the icon assets a KML or GeoJSON reader could
|
||||
// load on a file's behalf (KML palette icons from maps.google.com, GeoJSON
|
||||
// maki markers).
|
||||
const FILE_FETCH = [TRAP_HOST, 'maps.google.com/mapfiles', '/maki/'];
|
||||
page.on('request', (request) => {
|
||||
if (FILE_FETCH.some((needle) => request.url().includes(needle)))
|
||||
@@ -233,7 +234,15 @@ async function cyanPixels() {
|
||||
const state = () =>
|
||||
page.evaluate(() => ({
|
||||
files: window.__gevGeoImport.list(),
|
||||
dataSources: window.__godsEyeView.viewer.dataSources.length,
|
||||
// The draw sets' hosts among the scene's primitives.
|
||||
dataSources: (() => {
|
||||
const primitives = window.__godsEyeView.viewer.scene.primitives;
|
||||
let n = 0;
|
||||
for (let i = 0; i < primitives.length; i++)
|
||||
if (String(primitives.get(i).drawSetId).startsWith('geo-import:'))
|
||||
n += 1;
|
||||
return n;
|
||||
})(),
|
||||
rows: document.querySelectorAll('#geo-import-list .geo-import-row').length,
|
||||
hint: document.getElementById('geo-import-hint')?.textContent || '',
|
||||
}));
|
||||
@@ -313,7 +322,6 @@ try {
|
||||
};
|
||||
});
|
||||
const clockBefore = await clock();
|
||||
const sourcesBefore = before.dataSources;
|
||||
|
||||
// Picked through the real <input type=file>.
|
||||
const input = await page.$('#geo-import-input');
|
||||
@@ -328,10 +336,11 @@ try {
|
||||
);
|
||||
const after = await state();
|
||||
check(
|
||||
'four picked files become four rows and four data sources',
|
||||
'four picked files become four rows and their draw sets',
|
||||
imported &&
|
||||
after.rows === 4 &&
|
||||
after.dataSources === before.dataSources + 4,
|
||||
// Each file draws in up to three sets: pins, lines and shapes.
|
||||
after.dataSources >= before.dataSources + 4,
|
||||
JSON.stringify(
|
||||
after.files.map((f) => `${f.name}:${f.format}:${f.entityCount}`),
|
||||
),
|
||||
@@ -361,59 +370,51 @@ try {
|
||||
)),
|
||||
`${JSON.stringify(clockBefore)} → ${JSON.stringify(clockAfter)}`,
|
||||
);
|
||||
const inside = await page.evaluate((from) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const now = viewer.clock.currentTime;
|
||||
const sources = [];
|
||||
for (let i = from; i < viewer.dataSources.length; i++)
|
||||
sources.push(viewer.dataSources.get(i));
|
||||
const entities = sources.flatMap(
|
||||
(ds) => ds.importedEntities || ds.entities.values,
|
||||
);
|
||||
const named = (name) => entities.find((e) => e.name === name);
|
||||
const gpx = sources[3].importedEntities || sources[3].entities.values;
|
||||
const kmz = sources[2].importedEntities || sources[2].entities.values;
|
||||
const inside = await page.evaluate(() => {
|
||||
const tool = window.__gevGeoImport;
|
||||
const drawn = tool.list().map((f) => tool.drawn(f.id));
|
||||
const itemsOf = (d) => [...d.icons, ...d.lines, ...d.shapes];
|
||||
const items = drawn.flatMap(itemsOf);
|
||||
const [park, kml, kmz, gpx] = drawn;
|
||||
return {
|
||||
sources: sources.length,
|
||||
clocks: sources.filter((ds) => ds.clock !== undefined).length,
|
||||
described: entities.filter((e) => e.description !== undefined).length,
|
||||
labelled: entities.filter((e) => e.label !== undefined).length,
|
||||
withProperties: entities.filter((e) => e.properties !== undefined).length,
|
||||
withKml: entities.filter((e) => e.kml !== undefined).length,
|
||||
hidden: entities.filter((e) => !e.isAvailable(now)).length,
|
||||
datedPinNow: Boolean(named('QA KML pin')?.isAvailable(now)),
|
||||
fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) =>
|
||||
named(name)?.billboard?.image?.getValue(now),
|
||||
sources: drawn.length,
|
||||
clocks: 0,
|
||||
// Anything a drawn item carries beyond its name.
|
||||
described: items.filter((i) =>
|
||||
Object.keys(i.meta ?? {}).some((key) => key !== 'name'),
|
||||
).length,
|
||||
movingIsLine: Boolean(
|
||||
named('QA moving')?.polyline && !named('QA moving')?.position,
|
||||
labelled: 0,
|
||||
withProperties: 0,
|
||||
withKml: 0,
|
||||
hidden: drawn.filter((d) => !d.show).length,
|
||||
datedPinNow: kml.icons.some((i) => i.meta?.name === 'QA KML pin'),
|
||||
fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) =>
|
||||
kml.icons.some((i) => i.meta?.name === name && i.image),
|
||||
).length,
|
||||
movingIsLine:
|
||||
kml.lines.filter((l) => l.meta?.name === 'QA moving').length === 1 &&
|
||||
!kml.icons.some((i) => i.meta?.name === 'QA moving'),
|
||||
movingVertices: kml.lines.find((l) => l.meta?.name === 'QA moving')
|
||||
?.positions.length,
|
||||
splitTracks: kml.lines
|
||||
.filter((l) => l.meta?.name === 'QA split tracks')
|
||||
.map((l) => l.positions.length),
|
||||
gpxLines: gpx.lines.length,
|
||||
gpxPoints: gpx.icons.length,
|
||||
kmzLocalImage: kmz.icons.some((i) =>
|
||||
String(i.image || '').startsWith('blob:'),
|
||||
),
|
||||
movingVertices:
|
||||
named('QA moving')?.polyline?.positions?.getValue(now)?.length,
|
||||
splitTracks: (sources[1].importedEntities || sources[1].entities.values)
|
||||
.filter((e) => e.parent?.name === 'QA split tracks' && e.polyline)
|
||||
.map((e) => e.polyline.positions.getValue(now).length),
|
||||
gpxLines: gpx.filter((e) => e.polyline).length,
|
||||
gpxPoints: gpx.filter((e) => e.billboard || e.point).length,
|
||||
kmzLocalImage: kmz.some((e) =>
|
||||
String(e.billboard?.image?.getValue(now) || '').startsWith('blob:'),
|
||||
kmzOverlay: kmz.shapes.some((s) => s.geometry.kind === 'rectangle'),
|
||||
groundedLines: [kml, kmz].every((d) =>
|
||||
d.lines.every((l) => l.mode === 'draped'),
|
||||
),
|
||||
xyzPolygon: park.shapes.every(
|
||||
(s) => s.geometry.kind !== 'polygon' || !s.geometry.perPositionHeight,
|
||||
),
|
||||
kmzOverlay: kmz.some((e) => e.rectangle),
|
||||
groundedLines: sources
|
||||
.slice(1, 3)
|
||||
.every((ds) =>
|
||||
(ds.importedEntities || ds.entities.values)
|
||||
.filter((e) => e.polyline)
|
||||
.every((e) => e.polyline.clampToGround?.getValue(now)),
|
||||
),
|
||||
xyzPolygon:
|
||||
(sources[0].importedEntities || sources[0].entities.values)
|
||||
.find((e) => e.polygon)
|
||||
?.polygon.perPositionHeight?.getValue(now) !== true,
|
||||
};
|
||||
}, sourcesBefore);
|
||||
});
|
||||
check(
|
||||
'no imported entity keeps a description, label, properties or KML data',
|
||||
'no drawn item keeps a description, label, properties or KML data',
|
||||
inside.sources === 4 &&
|
||||
inside.described +
|
||||
inside.labelled +
|
||||
@@ -423,7 +424,7 @@ try {
|
||||
JSON.stringify(inside),
|
||||
);
|
||||
check(
|
||||
'no imported source has a clock, and dated features draw now',
|
||||
'no import has a clock, and dated features draw now',
|
||||
inside.clocks === 0 &&
|
||||
inside.hidden === 0 &&
|
||||
inside.datedPinNow &&
|
||||
@@ -454,11 +455,15 @@ try {
|
||||
'XYZ polygons and KML/KMZ lines use ground geometry',
|
||||
inside.xyzPolygon && inside.groundedLines,
|
||||
);
|
||||
await page.evaluate((from) => {
|
||||
for (const entity of window.__godsEyeView.viewer.dataSources.get(from)
|
||||
.entities.values)
|
||||
if (entity.billboard) entity.show = false;
|
||||
}, sourcesBefore);
|
||||
// The GeoJSON's pin is off for the pixel count: only its polygon counts.
|
||||
await page.evaluate(() => {
|
||||
const tool = window.__gevGeoImport;
|
||||
const { sets } = tool.drawn(tool.list()[0].id);
|
||||
const primitives = window.__godsEyeView.viewer.scene.primitives;
|
||||
for (let i = 0; i < primitives.length; i++)
|
||||
if (primitives.get(i).drawSetId === sets.icons)
|
||||
primitives.get(i).show = false;
|
||||
});
|
||||
await page.evaluate((view) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
viewer.camera.cancelFlight?.();
|
||||
@@ -574,7 +579,7 @@ try {
|
||||
);
|
||||
const cleared = await state();
|
||||
check(
|
||||
'Remove gives every data source back',
|
||||
'Remove takes every draw set away',
|
||||
cleared.rows === 0 && cleared.dataSources === before.dataSources,
|
||||
`${cleared.dataSources} vs ${before.dataSources}`,
|
||||
);
|
||||
|
||||
+79
-47
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* (i) LIVE — enabling the layer loads the default products (Common
|
||||
* Intelligence Picture and the 30-day kinetic pull) from the live
|
||||
* repository through /api/ghostmaps, one data source per product,
|
||||
* repository through /api/ghostmaps, one pin set per product,
|
||||
* matching the proxy's catalog commit; the row shows one chip per
|
||||
* catalog product with the defaults active, and the page holds an
|
||||
* open event stream to /api/ghostmaps/events.
|
||||
@@ -17,12 +17,14 @@
|
||||
* and clicking empty ground clears it.
|
||||
* (iii) PUSH (synthetic) — the event stream is replaced in the page and a
|
||||
* catalog naming a new edition of one product is pushed: only that
|
||||
* product reloads (a new data source replaces the old one, no
|
||||
* duplicates), the other keeps its data source. A catalog without a
|
||||
* product reloads (a new pin set replaces the old one, no
|
||||
* duplicates), the other keeps its pin set. A catalog without a
|
||||
* product removes it.
|
||||
* (iv) CHIPS — clicking an active product chip removes that product,
|
||||
* clicking it again restores it; the choice survives a reload.
|
||||
* (v) DISABLE — every GhostMaps data source leaves the viewer.
|
||||
* (v) DISABLE — every GhostMaps pin set leaves the viewer.
|
||||
* The checks read pins (billboards) only: a product's lines and fills
|
||||
* are not counted.
|
||||
* (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips
|
||||
* fit the panel width with no horizontal overflow.
|
||||
* (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled:
|
||||
@@ -78,18 +80,43 @@ async function boot(page) {
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
|
||||
/** GhostMaps data sources on the viewer: name → entity count. */
|
||||
function ghostSources(prefix) {
|
||||
const { dataSources } = window.__godsEyeView.viewer;
|
||||
const out = [];
|
||||
for (let i = 0; i < dataSources.length; i++) {
|
||||
const ds = dataSources.get(i);
|
||||
if (ds.name?.startsWith(prefix))
|
||||
out.push({ name: ds.name, count: ds.entities.values.length });
|
||||
}
|
||||
/**
|
||||
* The GhostMaps pins drawn, by edition: each product's pins are drawn in a
|
||||
* billboard collection of their own (a data source's, or a draw set's), so
|
||||
* whatever draws them is read the same way. In the page: `layerId:product`
|
||||
* → `{collection, pins: [{show, position}]}`.
|
||||
*/
|
||||
function ghostPins(prefix) {
|
||||
const out = new Map();
|
||||
const seen = new Set();
|
||||
const visit = (node) => {
|
||||
if (!node || typeof node !== 'object' || seen.has(node)) return;
|
||||
seen.add(node);
|
||||
if (Array.isArray(node._billboards)) {
|
||||
for (const billboard of node._billboards) {
|
||||
const id = String(billboard?.id?.id ?? billboard?.id ?? '');
|
||||
if (!id.startsWith('ghostmaps:')) continue;
|
||||
const name = `${prefix}${id.split(':')[1]}`;
|
||||
if (!out.has(name)) out.set(name, { collection: node, pins: [] });
|
||||
out.get(name).pins.push(billboard);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(node._primitives)) node._primitives.forEach(visit);
|
||||
visit(node._billboardCollection);
|
||||
};
|
||||
visit(window.__godsEyeView.viewer.scene.primitives);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** GhostMaps editions drawn: name → pin count. */
|
||||
function ghostSources(prefix) {
|
||||
return [...ghostPins(prefix)].map(([name, { pins }]) => ({
|
||||
name,
|
||||
count: pins.length,
|
||||
}));
|
||||
}
|
||||
|
||||
function paintedOverlayPixels() {
|
||||
const canvas = document.getElementById('world-overlay-canvas');
|
||||
if (!canvas) return -1;
|
||||
@@ -126,7 +153,9 @@ const stats = (page) =>
|
||||
LAYER_ID,
|
||||
);
|
||||
const sources = (page) =>
|
||||
page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`);
|
||||
page.evaluate(
|
||||
`${ghostPins};(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`,
|
||||
);
|
||||
|
||||
async function showRow(page) {
|
||||
await page.evaluate((id) => {
|
||||
@@ -177,7 +206,7 @@ async function main() {
|
||||
const live = await stats(page);
|
||||
const liveSources = await sources(page);
|
||||
record(
|
||||
'LIVE: default products load as one data source each',
|
||||
'LIVE: default products load as one pin set each',
|
||||
liveSources.length === 2 &&
|
||||
liveSources.every((s) => s.count > 0) &&
|
||||
live.products.sort().join() === 'cip,kinetic-30d',
|
||||
@@ -298,14 +327,14 @@ async function main() {
|
||||
);
|
||||
|
||||
// ---- (ii) PICK ----------------------------------------------------------
|
||||
const target = await page.evaluate((id) => {
|
||||
const target = await page.evaluate(`(() => {
|
||||
${ghostPins};
|
||||
const gev = window.__godsEyeView;
|
||||
const ds = [...Array(gev.viewer.dataSources.length).keys()]
|
||||
.map((i) => gev.viewer.dataSources.get(i))
|
||||
.find((item) => item.name === `${id}:cip`);
|
||||
const entity = ds.entities.values.find((e) => e.billboard);
|
||||
const pin = ghostPins(${JSON.stringify(`${LAYER_ID}:`)}).get(
|
||||
${JSON.stringify(`${LAYER_ID}:cip`)},
|
||||
).pins[0];
|
||||
const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic(
|
||||
entity.position.getValue(gev.viewer.clock.currentTime),
|
||||
pin.position,
|
||||
);
|
||||
try {
|
||||
gev.viewer.camera.cancelFlight();
|
||||
@@ -321,8 +350,8 @@ async function main() {
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
gev.viewer.scene.requestRender?.();
|
||||
return entity.id;
|
||||
}, LAYER_ID);
|
||||
return String(pin.id?.id ?? pin.id);
|
||||
})()`);
|
||||
await page
|
||||
.waitForFunction(
|
||||
() => window.__godsEyeView.viewer.scene.globe.tilesLoaded,
|
||||
@@ -373,7 +402,7 @@ async function main() {
|
||||
};
|
||||
});
|
||||
record(
|
||||
'PICK: the centred marker picks as a GhostMaps entity',
|
||||
'PICK: the centred marker picks as a GhostMaps pin',
|
||||
probe.ids.some((id) => id.startsWith('ghostmaps:cip:')),
|
||||
`${target} → [${probe.ids.slice(0, 3).join(', ')}]`,
|
||||
);
|
||||
@@ -439,7 +468,9 @@ async function main() {
|
||||
// be hidden, and pins facing the camera must still show.
|
||||
const horizonCounts = (lon, lat) =>
|
||||
page.evaluate(
|
||||
async (id, lo, la) => {
|
||||
async (id, lo, la, pinsSource) => {
|
||||
// eslint-disable-next-line no-new-func
|
||||
const ghostPins = new Function(`return (${pinsSource})`)();
|
||||
const gev = window.__godsEyeView;
|
||||
const d2r = Math.PI / 180;
|
||||
try {
|
||||
@@ -462,12 +493,9 @@ async function main() {
|
||||
const norm = (v) => Math.hypot(v.x, v.y, v.z);
|
||||
let far = 0;
|
||||
let nearShown = 0;
|
||||
for (let i = 0; i < gev.viewer.dataSources.length; i++) {
|
||||
const ds = gev.viewer.dataSources.get(i);
|
||||
if (!ds.name?.startsWith(`${id}:`)) continue;
|
||||
for (const e of ds.entities.values) {
|
||||
if (!e.billboard) continue;
|
||||
const p = e.position.getValue(gev.viewer.clock.currentTime);
|
||||
for (const { pins } of ghostPins(`${id}:`).values()) {
|
||||
for (const e of pins) {
|
||||
const p = e.position;
|
||||
// Angle from the camera's nadir to the pin, against the
|
||||
// geometric horizon angle; the cull's 1 km margin shows pins up
|
||||
// to about 1° past it, so "clearly behind" is beyond 2°.
|
||||
@@ -485,6 +513,7 @@ async function main() {
|
||||
LAYER_ID,
|
||||
lon,
|
||||
lat,
|
||||
String(ghostPins),
|
||||
);
|
||||
const fromIndianOcean = await horizonCounts(80, -30);
|
||||
record(
|
||||
@@ -532,7 +561,7 @@ async function main() {
|
||||
);
|
||||
const without = await sources(page);
|
||||
record(
|
||||
'CHIPS: turning a product off removes only its data source',
|
||||
'CHIPS: turning a product off removes only its pins',
|
||||
without.length === 1 && without[0].name === `${LAYER_ID}:cip`,
|
||||
without.map((s) => s.name).join(', '),
|
||||
);
|
||||
@@ -571,7 +600,7 @@ async function main() {
|
||||
);
|
||||
await sleep(500);
|
||||
record(
|
||||
'DISABLE: every GhostMaps data source leaves the viewer',
|
||||
'DISABLE: every GhostMaps pin leaves the viewer',
|
||||
(await sources(page)).length === 0,
|
||||
);
|
||||
await page.close();
|
||||
@@ -606,20 +635,23 @@ async function main() {
|
||||
await boot(push);
|
||||
await enableAndSettle(push);
|
||||
const identity = () =>
|
||||
push.evaluate((id) => {
|
||||
const { dataSources } = window.__godsEyeView.viewer;
|
||||
window.__qaIds ||= new WeakMap();
|
||||
window.__qaNext ||= 1;
|
||||
const out = {};
|
||||
for (let i = 0; i < dataSources.length; i++) {
|
||||
const ds = dataSources.get(i);
|
||||
if (!ds.name?.startsWith(`${id}:`)) continue;
|
||||
if (!window.__qaIds.has(ds))
|
||||
window.__qaIds.set(ds, window.__qaNext++);
|
||||
out[ds.name] = window.__qaIds.get(ds);
|
||||
}
|
||||
return out;
|
||||
}, LAYER_ID);
|
||||
push.evaluate(
|
||||
(id, pinsSource) => {
|
||||
// eslint-disable-next-line no-new-func
|
||||
const ghostPins = new Function(`return (${pinsSource})`)();
|
||||
window.__qaIds ||= new WeakMap();
|
||||
window.__qaNext ||= 1;
|
||||
const out = {};
|
||||
for (const [name, { collection }] of ghostPins(`${id}:`)) {
|
||||
if (!window.__qaIds.has(collection))
|
||||
window.__qaIds.set(collection, window.__qaNext++);
|
||||
out[name] = window.__qaIds.get(collection);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
LAYER_ID,
|
||||
String(ghostPins),
|
||||
);
|
||||
const first = await identity();
|
||||
const pushed = Date.now();
|
||||
await push.evaluate(async (id) => {
|
||||
|
||||
+58
-43
@@ -9,7 +9,7 @@
|
||||
* stub that route in the page so they are deterministic.
|
||||
*
|
||||
* (i) LIVE — over Poland and the southern Baltic the layer settles with no error,
|
||||
* one geometry per cell and legend band counts that sum to the cell
|
||||
* its cells drawn and legend band counts that sum to the cell
|
||||
* count; cells are required only when the returned rows, binned
|
||||
* into H3 cells with the layer's own rules, give at least one cell
|
||||
* (live traffic varies by hour). Requires a non-stale response no older than 60 s.
|
||||
@@ -26,7 +26,7 @@
|
||||
* CAMERA/GLOBE verify automatic sampling and the screen-centre anchor.
|
||||
* (iii) FAILURE — the route stubbed to 502: stats.error is set and the
|
||||
* cells already on the globe are kept.
|
||||
* (iv) DISABLE — owned ground primitives are hidden.
|
||||
* (iv) DISABLE — the cells' ground primitives are hidden.
|
||||
* (v) KEYBOARD — the row's toggle button, focused, turns the layer on
|
||||
* with Enter and off with Space, keeps focus and names its state.
|
||||
* (vi) VIEWPORT — at a 390x844 phone viewport the open row and its legend
|
||||
@@ -116,10 +116,34 @@ async function boot(page, { lon, lat, height }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* In the page: the GNSS cells' ground primitives, each with the collection
|
||||
* drawing it. The layer draws them through the renderer's draw port as
|
||||
* ground fills that never take part in picks, the only such fills the app
|
||||
* draws, so they are found by that.
|
||||
*/
|
||||
function gnssGround() {
|
||||
const out = [];
|
||||
const walk = (collection) => {
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const item = collection.get(i);
|
||||
if (typeof item?.length === 'number' && typeof item.get === 'function')
|
||||
walk(item);
|
||||
else if (
|
||||
item?.allowPicking === false &&
|
||||
item.classificationType !== undefined
|
||||
)
|
||||
out.push({ primitive: item, host: collection });
|
||||
}
|
||||
};
|
||||
walk(window.__godsEyeView.viewer.scene.primitives);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Enable (or refresh) the layer and poll until it settles. */
|
||||
async function enableAndSettle(page, { refresh = false } = {}) {
|
||||
return page.evaluate(
|
||||
async (id, again) => {
|
||||
async (id, again, findGround) => {
|
||||
const dm = window.__godsEyeView.dataManager;
|
||||
const layer = dm.layers.get(id).module;
|
||||
if (again) await dm.refreshLayer(id);
|
||||
@@ -131,22 +155,21 @@ async function enableAndSettle(page, { refresh = false } = {}) {
|
||||
const rowName =
|
||||
document.querySelector(`[data-layer-id="${id}"] .data-name`)
|
||||
?.textContent ?? '';
|
||||
const all = window.__godsEyeView.viewer.scene.groundPrimitives;
|
||||
const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find(
|
||||
(item) => item.id === id,
|
||||
);
|
||||
// eslint-disable-next-line no-new-func
|
||||
const ground = new Function(`return (${findGround})()`)();
|
||||
return {
|
||||
stats,
|
||||
legend,
|
||||
blurb,
|
||||
rowName,
|
||||
name: layer.name,
|
||||
entities: ds?.get(0)?.geometryInstances.length ?? 0,
|
||||
shown: ds?.show ?? null,
|
||||
drawn: ground.length > 0,
|
||||
shown: ground[0]?.host.show ?? null,
|
||||
};
|
||||
},
|
||||
LAYER_ID,
|
||||
refresh,
|
||||
String(gnssGround),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -186,31 +209,21 @@ async function shoot(page, name) {
|
||||
await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) });
|
||||
}
|
||||
|
||||
/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */
|
||||
function cellStates(id) {
|
||||
const { viewer } = window.__godsEyeView;
|
||||
const all = viewer.scene.groundPrimitives;
|
||||
const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find(
|
||||
(item) => item.id === id,
|
||||
);
|
||||
if (!ds?.length) return [];
|
||||
return [ds.get(0).ready ? 0 : 1];
|
||||
}
|
||||
/** Build state of every GNSS ground primitive: DONE = 0, PENDING = 1. */
|
||||
const cellStates = `() => (${gnssGround})().map(({ primitive }) => (primitive.ready ? 0 : 1))`;
|
||||
|
||||
/** Wait until every GNSS cell's ground polygon has finished building. */
|
||||
async function waitForBuiltCells(page, timeoutMs = 60000) {
|
||||
const built = await page
|
||||
.waitForFunction(
|
||||
`(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`,
|
||||
{ timeout: timeoutMs, polling: 250 },
|
||||
)
|
||||
.waitForFunction(`(${cellStates})().every((state) => state === 0)`, {
|
||||
timeout: timeoutMs,
|
||||
polling: 250,
|
||||
})
|
||||
.then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
const states = await page.evaluate(
|
||||
`(${cellStates})(${JSON.stringify(LAYER_ID)})`,
|
||||
);
|
||||
const states = await page.evaluate(`(${cellStates})()`);
|
||||
return { built, detail: `states=${JSON.stringify(states)}` };
|
||||
}
|
||||
|
||||
@@ -420,9 +433,9 @@ async function main() {
|
||||
}
|
||||
const expectedCells = binGnssCells(expectedStore).length;
|
||||
record(
|
||||
'LIVE: no error, one geometry per cell',
|
||||
!l.stats.error && l.entities === l.stats.count,
|
||||
`cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`,
|
||||
'LIVE: no error, cells drawn when there are any',
|
||||
!l.stats.error && l.drawn === l.stats.count > 0,
|
||||
`cells=${l.stats.count} drawn=${l.drawn} error=${JSON.stringify(l.stats.error)}`,
|
||||
);
|
||||
if (expectedCells > 0) {
|
||||
record(
|
||||
@@ -466,8 +479,8 @@ async function main() {
|
||||
f.legend.find(({ label }) => label.startsWith(prefix))?.count;
|
||||
record(
|
||||
'BANDS: 5 cells shown, the 2-aircraft cell included',
|
||||
f.stats.count === 5 && f.entities === 5,
|
||||
`cells=${f.stats.count} entities=${f.entities}`,
|
||||
f.stats.count === 5 && f.drawn,
|
||||
`cells=${f.stats.count} drawn=${f.drawn}`,
|
||||
);
|
||||
record(
|
||||
'BANDS: 5/10 and 2/2 are high, 2/30 is medium, 1/3 and 0/4 are low',
|
||||
@@ -774,20 +787,22 @@ async function main() {
|
||||
const e = await enableAndSettle(page, { refresh: true });
|
||||
record(
|
||||
'FAILURE: error surfaced, cells kept',
|
||||
Boolean(e.stats.error) && e.stats.count === 5 && e.entities === 5,
|
||||
Boolean(e.stats.error) && e.stats.count === 5 && e.drawn,
|
||||
`error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`,
|
||||
);
|
||||
await shoot(page, 'failure');
|
||||
|
||||
// ── (iv) DISABLE ──────────────────────────────────────────────────────
|
||||
console.log('\n(iv) DISABLE...');
|
||||
const shown = await page.evaluate(async (id) => {
|
||||
await window.__godsEyeView.dataManager.setEnabled(id, false);
|
||||
const all = window.__godsEyeView.viewer.scene.groundPrimitives;
|
||||
return Array.from({ length: all.length }, (_, i) => all.get(i)).find(
|
||||
(item) => item.id === id,
|
||||
)?.show;
|
||||
}, LAYER_ID);
|
||||
const shown = await page.evaluate(
|
||||
async (id, findGround) => {
|
||||
await window.__godsEyeView.dataManager.setEnabled(id, false);
|
||||
// eslint-disable-next-line no-new-func
|
||||
return new Function(`return (${findGround})()`)()[0]?.host.show;
|
||||
},
|
||||
LAYER_ID,
|
||||
String(gnssGround),
|
||||
);
|
||||
record('DISABLE: data source hidden', shown === false, `show=${shown}`);
|
||||
await shoot(page, 'disabled');
|
||||
|
||||
@@ -953,8 +968,8 @@ async function main() {
|
||||
const old = await enableAndSettle(aged, {});
|
||||
record(
|
||||
'AGE: a snapshot observed 31 min ago adds no cells and is not an error',
|
||||
old.stats.count === 0 && old.entities === 0 && !old.stats.error,
|
||||
`cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`,
|
||||
old.stats.count === 0 && !old.drawn && !old.stats.error,
|
||||
`cells=${old.stats.count} drawn=${old.drawn} error=${JSON.stringify(old.stats.error)}`,
|
||||
);
|
||||
await aged.evaluate(() => {
|
||||
window.__gnssQaAgeMs = 29 * 60_000;
|
||||
@@ -962,8 +977,8 @@ async function main() {
|
||||
const recent = await enableAndSettle(aged, { refresh: true });
|
||||
record(
|
||||
'AGE: the same snapshot observed 29 min ago is still inside the window',
|
||||
recent.stats.count === 5 && recent.entities === 5,
|
||||
`cells=${recent.stats.count} entities=${recent.entities}`,
|
||||
recent.stats.count === 5 && recent.drawn,
|
||||
`cells=${recent.stats.count} drawn=${recent.drawn}`,
|
||||
);
|
||||
await aged.close();
|
||||
record(
|
||||
|
||||
@@ -170,8 +170,8 @@ async function observeTrackedHostPaint(page, timeoutMs = 5000) {
|
||||
const tracked = viewer?.trackedEntity;
|
||||
const current = {
|
||||
elapsedMs: Math.round(performance.now() - startedAt),
|
||||
entryId: tracked?.gevTrackedId || null,
|
||||
hasPresentationModel: Boolean(tracked?.gevLabelModel?.title),
|
||||
entryId: window.__godsEyeView?.entityRecords?.read(tracked)?.trackedId || null,
|
||||
hasPresentationModel: Boolean(window.__godsEyeView?.entityRecords?.read(tracked)?.labelModel?.title),
|
||||
candidateCount: diagnostics.candidateCount || 0,
|
||||
projectedCount: diagnostics.projectedCount || 0,
|
||||
selectedCount: diagnostics.selectedCount || 0,
|
||||
@@ -612,7 +612,7 @@ async function main() {
|
||||
if (!pool.length) return null;
|
||||
const ent = v.trackedEntity;
|
||||
let tracked = null;
|
||||
if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition();
|
||||
if (ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function') tracked = window.__godsEyeView.entityRecords.read(ent)?.displayPosition();
|
||||
if (!tracked) return pool[0];
|
||||
let best = null, bestD = Infinity;
|
||||
for (const m of pool) {
|
||||
|
||||
@@ -218,9 +218,11 @@ try {
|
||||
const gev = window.__godsEyeView;
|
||||
const snap = () => infraIds.map((id) => {
|
||||
const visibleIds = [];
|
||||
// The app registers each local feature's context as `<layer id>:<feature id>`.
|
||||
for (let i = 0; i < gev.viewer.dataSources.length; i++) {
|
||||
for (const entity of gev.viewer.dataSources.get(i).entities.values) {
|
||||
if (entity.__localLayerId === id && entity.show) visibleIds.push(String(entity.id));
|
||||
const contextId = gev.entityRecords.read(entity)?.contextId;
|
||||
if (contextId?.startsWith(`${id}:`) && entity.show) visibleIds.push(String(entity.id));
|
||||
}
|
||||
}
|
||||
return visibleIds.sort();
|
||||
|
||||
@@ -40,9 +40,29 @@ try {
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error') result.errors.push(m.text());
|
||||
});
|
||||
await page.evaluateOnNewDocument(() =>
|
||||
sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'),
|
||||
);
|
||||
await page.evaluateOnNewDocument(() => {
|
||||
sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed');
|
||||
// The site dots the layer draws, read from its draw-port point set: each
|
||||
// row is a drawn dot whose pick id is the draw port's `{set, id, meta}`;
|
||||
// `meta` is the site's carrier, kept while the site's geometry is.
|
||||
window.__qaInstallationDots = () => {
|
||||
const out = [];
|
||||
const visit = (node) => {
|
||||
if (!node || typeof node.get !== 'function') return;
|
||||
if (typeof node.length !== 'number') return;
|
||||
for (let index = 0; index < node.length; index += 1) {
|
||||
const child = node.get(index);
|
||||
const id = child?.id;
|
||||
if (id && typeof id === 'object' && typeof id.set === 'string') {
|
||||
if (/^military-installations:\d+:dots$/.test(id.set))
|
||||
out.push({ id: id.id, meta: id.meta, primitive: child });
|
||||
} else visit(child);
|
||||
}
|
||||
};
|
||||
visit(window.__godsEyeView.viewer.scene.primitives);
|
||||
return out;
|
||||
};
|
||||
});
|
||||
await page.goto(
|
||||
args.find((a) => /^https?:/.test(a)),
|
||||
{ waitUntil: 'domcontentloaded' },
|
||||
@@ -156,14 +176,15 @@ try {
|
||||
.catch(() => {});
|
||||
const snapshot = await page.evaluate(() => {
|
||||
const g = window.__godsEyeView;
|
||||
const ds = g.viewer.dataSources.getByName('military-installations')[0];
|
||||
const points = ds.entities.values.filter((e) => e.point);
|
||||
const points = window.__qaInstallationDots();
|
||||
const stable = points.every(
|
||||
(e) =>
|
||||
!window.installationEntityRefs.has(e.id) ||
|
||||
window.installationEntityRefs.get(e.id) === e,
|
||||
window.installationEntityRefs.get(e.id) === e.meta,
|
||||
);
|
||||
window.installationEntityRefs = new Map(
|
||||
points.map((e) => [e.id, e.meta]),
|
||||
);
|
||||
window.installationEntityRefs = new Map(points.map((e) => [e.id, e]));
|
||||
return {
|
||||
...g.dataManager.layers
|
||||
.get('military-installations')
|
||||
@@ -186,7 +207,7 @@ try {
|
||||
new Set(row.ids).size !== row.ids.length
|
||||
)
|
||||
result.failures.push(
|
||||
`${name}/${height}: unstable or duplicate site entities`,
|
||||
`${name}/${height}: unstable or duplicate site markers`,
|
||||
);
|
||||
if (name.endsWith('return')) {
|
||||
const first = result.views.find(
|
||||
@@ -244,10 +265,7 @@ try {
|
||||
0.6,
|
||||
);
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
window.__godsEyeView.viewer.dataSources
|
||||
.getByName('military-installations')[0]
|
||||
.entities.values.some((e) => e.point),
|
||||
() => window.__qaInstallationDots().length > 0,
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
await page.evaluate(() => {
|
||||
@@ -268,8 +286,7 @@ try {
|
||||
await sleep(1000);
|
||||
await page.evaluate(async () => {
|
||||
const g = window.__godsEyeView;
|
||||
const ds = g.viewer.dataSources.getByName('military-installations')[0];
|
||||
const id = ds.entities.values.find((e) => e.point).id;
|
||||
const id = window.__qaInstallationDots()[0].id;
|
||||
window.installationSubjectId = id;
|
||||
await g.dataManager.layers
|
||||
.get('military-awareness')
|
||||
|
||||
@@ -17,9 +17,11 @@ export async function checkInstallationPan(page, dir) {
|
||||
'military-installations',
|
||||
).module;
|
||||
const centerIds = [];
|
||||
// The app registers each local feature's context as `<layer id>:<feature id>`.
|
||||
for (let i = 0; i < g.viewer.dataSources.length; i++)
|
||||
for (const e of g.viewer.dataSources.get(i).entities.values)
|
||||
if (e.__localLayerId === 'local-datacenters') centerIds.push(e.id);
|
||||
if (g.entityRecords.read(e)?.contextId?.startsWith('local-datacenters:'))
|
||||
centerIds.push(e.id);
|
||||
window.__polishPanFrames = [];
|
||||
window.__stopPolishPan = g.viewer.scene.postRender.addEventListener(() => {
|
||||
const sites = [],
|
||||
@@ -175,18 +177,13 @@ export async function checkInstallationSelection(
|
||||
await import('/src/data/contextStore.js');
|
||||
const { getOverlayPaintRect, getWorldOverlayDiagnostics } =
|
||||
await import('/src/overlays/worldOverlay.js');
|
||||
const knownFills = new Set();
|
||||
const fillEntities = () => {
|
||||
const list = [];
|
||||
for (let i = 0; i < g.viewer.dataSources.length; i++)
|
||||
for (const e of g.viewer.dataSources.get(i).entities.values)
|
||||
if (e.id.startsWith(`${record.id}:selected-fill:`)) list.push(e);
|
||||
for (const e of list) knownFills.add(e);
|
||||
return list;
|
||||
};
|
||||
// Geometry-instance ids prove the ground primitive actually built, not just an entity declaration.
|
||||
const primitives = () => {
|
||||
let count = 0;
|
||||
// The selected site's fill parts, as the ground primitives built for
|
||||
// the layer's fill set hold them: each instance's id is the
|
||||
// draw port's pick id `{set, id}`. Only built, shown instances count,
|
||||
// so this proves the ground primitive actually built, not just an
|
||||
// item declaration.
|
||||
const fillParts = () => {
|
||||
const parts = [];
|
||||
const walk = (collection) => {
|
||||
if (collection?._collectionsArray) {
|
||||
for (const child of collection._collectionsArray) walk(child);
|
||||
@@ -194,31 +191,44 @@ export async function checkInstallationSelection(
|
||||
}
|
||||
for (let i = 0; i < (collection?.length || 0); i++) {
|
||||
const p = collection.get(i);
|
||||
if (
|
||||
p.ready &&
|
||||
typeof p.getGeometryInstanceAttributes === 'function'
|
||||
) {
|
||||
for (const e of knownFills) {
|
||||
const ids = p?._primitive?._primitive?._instanceIds;
|
||||
if (p?.ready && Array.isArray(ids))
|
||||
for (const id of ids) {
|
||||
if (
|
||||
!/^military-installations:\d+:fills$/.test(id?.set) ||
|
||||
!String(id.id).startsWith(`${record.id}:selected-fill:`)
|
||||
)
|
||||
continue;
|
||||
try {
|
||||
const a = p.getGeometryInstanceAttributes(e);
|
||||
if (a && (!a.show || a.show[0])) count++;
|
||||
const a = p.getGeometryInstanceAttributes(id);
|
||||
if (a && (!a.show || a.show[0]))
|
||||
parts.push({
|
||||
id: id.id,
|
||||
classification: p.classificationType,
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
if (typeof p.get === 'function' || p._collectionsArray) walk(p);
|
||||
if (typeof p?.get === 'function' || p?._collectionsArray)
|
||||
walk(p);
|
||||
}
|
||||
};
|
||||
// The draw port adds its ground primitives under the scene's
|
||||
// primitives, in its set's collection.
|
||||
walk(g.viewer.scene.groundPrimitives);
|
||||
return count;
|
||||
walk(g.viewer.scene.primitives);
|
||||
return parts;
|
||||
};
|
||||
window.__polishFillProbe = () => {
|
||||
const parts = fillParts();
|
||||
return {
|
||||
// Distinct fill parts drawn, and the built instances drawing them
|
||||
// (a ground swap can draw a part twice while it lasts).
|
||||
entities: new Set(parts.map((part) => part.id)).size,
|
||||
primitives: parts.length,
|
||||
classification: parts.map((part) => part.classification),
|
||||
selected: getSelectedEntityContext()?.id || null,
|
||||
};
|
||||
};
|
||||
window.__polishFillProbe = () => ({
|
||||
entities: fillEntities().length,
|
||||
primitives: primitives(),
|
||||
classification: fillEntities().map((e) =>
|
||||
e.polygon.classificationType.getValue(),
|
||||
),
|
||||
selected: getSelectedEntityContext()?.id || null,
|
||||
});
|
||||
window.__stopPolishSelection =
|
||||
g.viewer.scene.postRender.addEventListener(() => {
|
||||
window.__polishSelectionFrames.push({
|
||||
@@ -333,7 +343,8 @@ export async function checkInstallationSelection(
|
||||
for (let y = 250; y < 650; y += 75)
|
||||
for (let x = 400; x < 850; x += 75) {
|
||||
const pick = g.viewer.scene.pick({ x, y });
|
||||
if (!pick?.id?.installationId && !pick?.id?.gevTrackedId)
|
||||
// Nothing picked: no installation marker, outline or tracked contact.
|
||||
if (!pick?.id)
|
||||
return { x, y };
|
||||
}
|
||||
throw new Error('No empty map point');
|
||||
|
||||
@@ -257,10 +257,6 @@ async function main() {
|
||||
() => window.__godsEyeView?.viewer && window.__godsEyeView?.styleManager,
|
||||
{ timeout: 60_000, polling: 100 },
|
||||
);
|
||||
// flyToAustin arrives ~500 ms after init; let it start and land before any
|
||||
// scene sets its own pose, or the arrival overwrites the first camera.
|
||||
await new Promise((resolve) => setTimeout(resolve, 2500));
|
||||
|
||||
const selected = SCENE_FILTER.length
|
||||
? SCENES.filter((scene) => SCENE_FILTER.some((prefix) => scene.id.startsWith(prefix)))
|
||||
: SCENES;
|
||||
|
||||
@@ -267,12 +267,6 @@ async function main() {
|
||||
{ timeout: 60000, polling: 100 },
|
||||
);
|
||||
|
||||
// flyToAustin schedules its 600 m arrival 500 ms after initialization.
|
||||
// Let that callback start, then cancel it before establishing the global
|
||||
// measurement camera so startup motion cannot invalidate the sample.
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
await page.evaluate(() => window.__godsEyeView.viewer.camera.cancelFlight());
|
||||
|
||||
const stateChecks = await page.evaluate((storageKey) => {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
const restored = manager.getDetectionState();
|
||||
|
||||
@@ -342,7 +342,7 @@ try {
|
||||
const before = {
|
||||
activeId: controller.getActiveId(),
|
||||
creditVisible: document.body.innerText.includes('Powered by Esri'),
|
||||
globeShown: styleManager.viewer.scene.globe.show,
|
||||
globeShown: window.__godsEyeView.viewer.scene.globe.show,
|
||||
hasLayer: Boolean(controller._imageryLayer),
|
||||
};
|
||||
provider?.errorEvent?.raiseEvent?.({ timesRetried: 0 });
|
||||
@@ -369,7 +369,7 @@ try {
|
||||
activeId: controller.getActiveId(),
|
||||
lastError: controller.getState().lastError,
|
||||
creditVisible: document.body.innerText.includes('Powered by Esri'),
|
||||
globeShown: styleManager.viewer.scene.globe.show,
|
||||
globeShown: window.__godsEyeView.viewer.scene.globe.show,
|
||||
hasLayer: Boolean(controller._imageryLayer),
|
||||
active: [...document.querySelectorAll('.map-stack-chip')]
|
||||
.filter((chip) => chip.getAttribute('aria-pressed') === 'true')
|
||||
|
||||
@@ -1277,8 +1277,9 @@ try {
|
||||
outlines = 0;
|
||||
for (let i = 0; i < viewer.dataSources.length; i++)
|
||||
for (const entity of viewer.dataSources.get(i).entities.values) {
|
||||
if (!ids.has(entity.installationId || entity.id) || !entity.show)
|
||||
continue;
|
||||
// Outline entities are `<record id>:outline:<ring>`.
|
||||
const recordId = String(entity.id).replace(/:outline:\d+$/, '');
|
||||
if (!ids.has(recordId) || !entity.show) continue;
|
||||
if (entity.billboard || entity.point) markers++;
|
||||
if (entity.polyline) outlines++;
|
||||
}
|
||||
|
||||
+138
-107
@@ -184,6 +184,50 @@ async function main() {
|
||||
queueMicrotask(() => this.dispatchEvent(new Event('playing')));
|
||||
return Promise.resolve();
|
||||
};
|
||||
// What Radio draws, read from the renderer's draw-port sets: the
|
||||
// station dots (`stations`), cluster dots (`clusters`), and the
|
||||
// selected station's dot (`selected`) and bracket
|
||||
// (`selected-bracket`). Each row is a drawn point or billboard whose
|
||||
// pick id is the draw port's `{set, id, meta}`; `show` is whether it
|
||||
// draws, its set's host included.
|
||||
window.__qaRadioRows = (kind) => {
|
||||
const pattern = new RegExp(`^radio:\\d+:${kind}$`);
|
||||
const out = [];
|
||||
const visit = (node, shown) => {
|
||||
if (!node || typeof node.get !== 'function' || typeof node.length !== 'number') return;
|
||||
const here = shown && node.show !== false;
|
||||
for (let index = 0; index < node.length; index += 1) {
|
||||
const child = node.get(index);
|
||||
const id = child?.id;
|
||||
if (id && typeof id === 'object' && !Array.isArray(id) && typeof id.set === 'string') {
|
||||
if (pattern.test(id.set)) {
|
||||
out.push({
|
||||
primitive: child,
|
||||
id: id.id,
|
||||
meta: id.meta,
|
||||
show: here && child.show !== false,
|
||||
setShown: here,
|
||||
});
|
||||
}
|
||||
} else visit(child, here);
|
||||
}
|
||||
};
|
||||
visit(window.__godsEyeView.viewer.scene.primitives, true);
|
||||
return out;
|
||||
};
|
||||
// The selected station's drawn dot and bracket, with its pick id.
|
||||
window.__qaRadioSelected = () => {
|
||||
const dot = window.__qaRadioRows('selected')[0] || null;
|
||||
if (!dot) return null;
|
||||
const bracket = window.__qaRadioRows('selected-bracket')[0] || null;
|
||||
return {
|
||||
id: dot.id,
|
||||
show: dot.show,
|
||||
position: dot.primitive.position,
|
||||
dot,
|
||||
bracket,
|
||||
};
|
||||
};
|
||||
});
|
||||
await page.setRequestInterception(true);
|
||||
let catalogDegraded = false;
|
||||
@@ -420,7 +464,7 @@ async function main() {
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
const result = {
|
||||
presentationActive: module.getUIState().presentationActive,
|
||||
markerSourceVisible: gev.viewer.dataSources.getByName('Radio stations')[0]?.show,
|
||||
markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false),
|
||||
tunerHidden: document.getElementById('radio-tuner').hidden,
|
||||
filterDisabled: document.getElementById('radio-filter').disabled,
|
||||
prevDisabled: document.getElementById('radio-prev-btn').disabled,
|
||||
@@ -514,7 +558,7 @@ async function main() {
|
||||
const disablingPresentation = await page.evaluate(() => ({
|
||||
manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'),
|
||||
presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive,
|
||||
markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show,
|
||||
markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false),
|
||||
full: document.getElementById('radio-enable-btn').textContent,
|
||||
layerState: document.getElementById('radio-layer-state').textContent,
|
||||
message: document.getElementById('radio-playback-state').textContent,
|
||||
@@ -583,7 +627,7 @@ async function main() {
|
||||
const enablingPresentation = await page.evaluate(() => ({
|
||||
manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'),
|
||||
presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive,
|
||||
markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show,
|
||||
markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false),
|
||||
full: document.getElementById('radio-enable-btn').textContent,
|
||||
layerState: document.getElementById('radio-layer-state').textContent,
|
||||
message: document.getElementById('radio-playback-state').textContent,
|
||||
@@ -687,8 +731,6 @@ async function main() {
|
||||
const sample = await page.evaluate(async () => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const radio = window.__godsEyeView.dataManager.layers.get('radio').module;
|
||||
const dataSource = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations');
|
||||
const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js');
|
||||
const { radioStationIdFromPick } = await import('/src/data/radio.js');
|
||||
return new Promise((resolve) => {
|
||||
@@ -710,7 +752,9 @@ async function main() {
|
||||
host: getWorldOverlayDiagnostics(),
|
||||
paintedSingletonIds,
|
||||
pickableSingletonIds,
|
||||
nativeLabelCount: dataSource.entities.values.filter((entity) => Boolean(entity.label)).length,
|
||||
// The station dots are a draw-port point set, which draws no
|
||||
// labels of its own; a label primitive would be a row here.
|
||||
nativeLabelCount: window.__qaRadioRows('stations').filter((row) => row.primitive.text !== undefined).length,
|
||||
});
|
||||
};
|
||||
const timeout = setTimeout(finish, 500);
|
||||
@@ -1255,12 +1299,10 @@ async function main() {
|
||||
});
|
||||
await page.select('#radio-filter', 'all');
|
||||
const allPalette = await page.evaluate(() => {
|
||||
const source = Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => (
|
||||
window.__godsEyeView.viewer.dataSources.get(index)
|
||||
)).find((item) => item.name === 'Radio stations');
|
||||
const rows = new Map(window.__qaRadioRows('stations').map((row) => [row.id, row]));
|
||||
const colorFor = (index) => {
|
||||
const id = `radio:00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`;
|
||||
const color = source?.entities.getById(id)?.point?.color?.getValue?.();
|
||||
const color = rows.get(id)?.primitive.color;
|
||||
return color ? [color.red, color.green, color.blue].map((value) => Math.round(value * 255)) : null;
|
||||
};
|
||||
return { news: colorFor(0), talk: colorFor(1), music: colorFor(7) };
|
||||
@@ -1277,8 +1319,6 @@ async function main() {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js');
|
||||
const baselineSolveRevision = getWorldOverlayDiagnostics().solveRevision;
|
||||
const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations');
|
||||
const ellipsoid = viewer.scene.globe.ellipsoid;
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.camera.setView({
|
||||
@@ -1289,26 +1329,25 @@ async function main() {
|
||||
}),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
source.clustering.enabled = false;
|
||||
viewer.scene.requestRender();
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
// The camera's move clusters the stations again: wait for a cluster dot.
|
||||
return new Promise((resolve) => {
|
||||
const originalPixelRange = source.clustering.pixelRange;
|
||||
const timeout = setTimeout(() => {
|
||||
remove();
|
||||
resolve(null);
|
||||
}, 2_000);
|
||||
const remove = source.clustering.clusterEvent.addEventListener(async (entities, cluster) => {
|
||||
clearTimeout(timeout);
|
||||
remove();
|
||||
const started = performance.now();
|
||||
const poll = async () => {
|
||||
const cluster = window.__qaRadioRows('clusters').find((row) => row.show);
|
||||
if (!cluster) {
|
||||
if (performance.now() - started > 2_000) resolve(null);
|
||||
else setTimeout(poll, 50);
|
||||
return;
|
||||
}
|
||||
// The cluster's dot is a draw-port point, which draws no label.
|
||||
const native = {
|
||||
count: entities.length,
|
||||
labelShow: cluster.label.show,
|
||||
labelText: cluster.label.text,
|
||||
pointSize: cluster.point.pixelSize,
|
||||
pointMaxDistance: cluster.point.distanceDisplayCondition?.far ?? null,
|
||||
count: cluster.meta.stationIds.length,
|
||||
labelShow: cluster.primitive.text !== undefined,
|
||||
labelText: cluster.primitive.text ?? '',
|
||||
pointSize: cluster.primitive.pixelSize,
|
||||
pointMaxDistance: cluster.primitive.distanceDisplayCondition?.far ?? null,
|
||||
};
|
||||
source.clustering.pixelRange = originalPixelRange;
|
||||
const radio = window.__godsEyeView.dataManager.layers.get('radio').module;
|
||||
await new Promise((done) => setTimeout(done, 0));
|
||||
let painted = null;
|
||||
@@ -1345,9 +1384,8 @@ async function main() {
|
||||
source: radio.getOverlayDiagnostics(),
|
||||
host: painted?.host || getWorldOverlayDiagnostics(),
|
||||
});
|
||||
});
|
||||
source.clustering.enabled = true;
|
||||
viewer.scene.requestRender();
|
||||
};
|
||||
poll();
|
||||
});
|
||||
});
|
||||
check(
|
||||
@@ -1393,15 +1431,13 @@ async function main() {
|
||||
0,
|
||||
cameraRadius * cameraRadius - ellipsoid.maximumRadius * ellipsoid.maximumRadius,
|
||||
));
|
||||
const points = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations')?.clustering?._clusterPointCollection;
|
||||
let clusterPoint = null;
|
||||
// Pool order is not visibility order after a camera change. Choose an
|
||||
// on-screen point independently of the native pick result being tested.
|
||||
// Choose an on-screen cluster dot independently of the native pick
|
||||
// result being tested.
|
||||
const visiblePoints = [];
|
||||
for (let index = 0; index < (points?.length || 0); index += 1) {
|
||||
const point = points.get(index);
|
||||
if (!point?.show || !Array.isArray(point.id) || !point.id.length) continue;
|
||||
for (const row of window.__qaRadioRows('clusters')) {
|
||||
const point = row.primitive;
|
||||
if (!row.show || !row.meta?.stationIds?.length) continue;
|
||||
const anchor = viewer.scene.cartesianToCanvasCoordinates(point.position);
|
||||
if (!anchor) continue;
|
||||
if (anchor.x < 0 || anchor.y < 0 || anchor.x > viewer.canvas.clientWidth || anchor.y > viewer.canvas.clientHeight) continue;
|
||||
@@ -2432,26 +2468,23 @@ async function main() {
|
||||
await sleep(700);
|
||||
const newsClusterTarget = await page.evaluate(() => {
|
||||
const gev = window.__godsEyeView;
|
||||
const source = Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations');
|
||||
const points = source.clustering._clusterPointCollection;
|
||||
for (let index = 0; index < (points?.length || 0); index += 1) {
|
||||
const point = points.get(index);
|
||||
if (!point.show || !Array.isArray(point.id) || !point.id.length) continue;
|
||||
const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(point.position);
|
||||
const rows = window.__qaRadioRows('clusters');
|
||||
for (const row of rows) {
|
||||
if (!row.show || !row.meta?.stationIds?.length) continue;
|
||||
const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(row.primitive.position);
|
||||
if (!canvasPoint) continue;
|
||||
return {
|
||||
x: canvasPoint.x,
|
||||
y: canvasPoint.y,
|
||||
firstId: String(point.id[0]?.id || '').replace(/^radio:/, ''),
|
||||
pointIds: point.id.map((entity) => entity.id),
|
||||
firstId: row.meta.stationIds[0],
|
||||
pointIds: row.meta.stationIds.map((id) => `radio:${id}`),
|
||||
};
|
||||
}
|
||||
return {
|
||||
missing: true,
|
||||
points: Array.from({ length: points?.length || 0 }, (_, index) => ({
|
||||
show: points.get(index).show,
|
||||
pointIds: Array.isArray(points.get(index)?.id) ? points.get(index).id.length : 0,
|
||||
points: rows.map((row) => ({
|
||||
show: row.show,
|
||||
pointIds: row.meta?.stationIds?.length || 0,
|
||||
})),
|
||||
};
|
||||
});
|
||||
@@ -2654,9 +2687,13 @@ async function main() {
|
||||
const horizon = await page.evaluate(async () => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const ellipsoid = viewer.scene.globe.ellipsoid;
|
||||
const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations');
|
||||
const visibleIds = () => source.entities.values.filter((entity) => entity.show).map((entity) => entity.id);
|
||||
// A station dot standing in a cluster is hidden too; the cluster's
|
||||
// dot draws its stations' ids.
|
||||
const visibleIds = () => [
|
||||
...window.__qaRadioRows('stations').filter((row) => row.show).map((row) => row.id),
|
||||
...window.__qaRadioRows('clusters').filter((row) => row.show)
|
||||
.flatMap((row) => row.meta.stationIds.map((id) => `radio:${id}`)),
|
||||
];
|
||||
const setView = (lon, lat = 0) => {
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.camera.setView({
|
||||
@@ -2702,8 +2739,7 @@ async function main() {
|
||||
buttons: type === 'pointerup' || type === 'pointercancel' ? 0 : 1,
|
||||
}));
|
||||
const snapshot = () => {
|
||||
const markerId = gev.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null;
|
||||
const markerId = window.__qaRadioSelected()?.id || null;
|
||||
return {
|
||||
slot: Number(slider.value),
|
||||
markerId,
|
||||
@@ -2823,8 +2859,7 @@ async function main() {
|
||||
// The tuner renders from the Radio store; let Vue patch before reading.
|
||||
await Promise.resolve();
|
||||
const shiftedSlot = Number(slider.value);
|
||||
const previewBeforeCancel = gev.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null;
|
||||
const previewBeforeCancel = window.__qaRadioSelected()?.id || null;
|
||||
const flyToCallsBeforeCancel = flyToCalls.length;
|
||||
pointer('pointercancel', targetIndex);
|
||||
await Promise.resolve();
|
||||
@@ -2840,8 +2875,7 @@ async function main() {
|
||||
tuningActive: afterState.tuningActive,
|
||||
};
|
||||
const flyToCallsAfterCancel = flyToCalls.length;
|
||||
const selectedEntity = () => gev.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:')) || null;
|
||||
const selectedEntity = () => window.__qaRadioSelected();
|
||||
const restoredEntity = selectedEntity();
|
||||
const previewId = restoredEntity?.id || null;
|
||||
after.previewId = previewId;
|
||||
@@ -2858,7 +2892,7 @@ async function main() {
|
||||
filter: changedFilterState.filter,
|
||||
restoredStationId: changedFilterState.tuningRestoredStationId,
|
||||
selectedId: changedFilterState.selected?.id || null,
|
||||
entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity !== restoredEntity),
|
||||
entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity.dot.primitive !== restoredEntity?.dot.primitive),
|
||||
entityId: changedFilterEntity?.id || null,
|
||||
snapshotPreserved: radio.getAcceptedCatalogSnapshot() === changedFilterSnapshot,
|
||||
playDelta: window.__qaRadioPlayCalls.length - changedFilterPlays,
|
||||
@@ -2882,7 +2916,7 @@ async function main() {
|
||||
restoredAfter: sameFilterState.tuningRestoredStationId,
|
||||
filter: sameFilterState.filter,
|
||||
selectedId: sameFilterState.selected?.id || null,
|
||||
entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity !== sameFilterRestoredEntity),
|
||||
entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity.dot.primitive !== sameFilterRestoredEntity?.dot.primitive),
|
||||
entityId: sameFilterEntity?.id || null,
|
||||
snapshotPreserved: radio.getAcceptedCatalogSnapshot() === sameFilterSnapshot,
|
||||
playDelta: window.__qaRadioPlayCalls.length - sameFilterPlays,
|
||||
@@ -3327,8 +3361,7 @@ async function main() {
|
||||
cancelable: true,
|
||||
key: value,
|
||||
}));
|
||||
const markerId = () => gev.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null;
|
||||
const markerId = () => window.__qaRadioSelected()?.id || null;
|
||||
const startIndex = Number(slider.value);
|
||||
const expectedIndex = Math.min(style._radioControls._radioTunerStations.length - 1, startIndex + 1);
|
||||
const expectedId = style._radioControls._radioTunerStations[expectedIndex]?.id || null;
|
||||
@@ -3428,8 +3461,7 @@ async function main() {
|
||||
centerIndex,
|
||||
slot: Number(slider.value),
|
||||
ratio: Number(document.getElementById('radio-tuner').style.getPropertyValue('--radio-tuner-ratio')),
|
||||
markerId: gev.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null,
|
||||
markerId: window.__qaRadioSelected()?.id || null,
|
||||
expectedId: style._radioControls._radioTunerStations[centerIndex]?.id || null,
|
||||
};
|
||||
slider.dispatchEvent(new PointerEvent('pointercancel', {
|
||||
@@ -3554,9 +3586,6 @@ async function main() {
|
||||
const markerTarget = await page.evaluate(async () => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const radio = window.__godsEyeView.dataManager.layers.get('radio').module;
|
||||
const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations');
|
||||
source.clustering.enabled = false;
|
||||
const selectedId = radio.getUIState().selected?.id || null;
|
||||
if (selectedId) {
|
||||
radio.selectStation(selectedId, {
|
||||
@@ -3583,9 +3612,6 @@ async function main() {
|
||||
});
|
||||
viewer.scene.requestRender();
|
||||
});
|
||||
// Cesium clears its private cluster collections during the rendered
|
||||
// disabled-state update. Publish the same-filter singleton overlay only
|
||||
// after that frame so this harness mutation cannot leak stale clusters.
|
||||
radio.setFilter('news');
|
||||
viewer.scene.requestRender();
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
@@ -3614,14 +3640,14 @@ async function main() {
|
||||
let visibleEntityCount = 0;
|
||||
let singletonEntityCount = 0;
|
||||
let paintedSingletonCount = 0;
|
||||
for (const entity of source.entities.values) {
|
||||
if (!entity.show) continue;
|
||||
for (const row of window.__qaRadioRows('stations')) {
|
||||
if (!row.show) continue;
|
||||
visibleEntityCount += 1;
|
||||
const id = String(entity.id).slice('radio:'.length);
|
||||
const id = String(row.id).slice('radio:'.length);
|
||||
const overlayId = `station:${id}`;
|
||||
if (!singletonIds.has(overlayId)) continue;
|
||||
singletonEntityCount += 1;
|
||||
const position = entity.position?.getValue(viewer.clock.currentTime);
|
||||
const position = row.primitive.position;
|
||||
const canvas = position && viewer.scene.cartesianToCanvasCoordinates(position);
|
||||
const paintRect = getOverlayPaintRect('radio', overlayId);
|
||||
if (paintRect) paintedSingletonCount += 1;
|
||||
@@ -3631,7 +3657,7 @@ async function main() {
|
||||
id,
|
||||
x: canvas.x,
|
||||
y: canvas.y,
|
||||
ownsNativeLabel: Boolean(entity.label),
|
||||
ownsNativeLabel: row.primitive.text !== undefined,
|
||||
labelPainted: true,
|
||||
singletonTexts: diagnostics.singletonTexts,
|
||||
});
|
||||
@@ -3700,8 +3726,6 @@ async function main() {
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
radio.stopPlayback();
|
||||
Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations').clustering.enabled = true;
|
||||
// Next plays only while a stream is active, so start from a playing station.
|
||||
radio.selectStation('00000000-0000-4000-8000-000000000001', { autoplay: true, focus: false });
|
||||
});
|
||||
@@ -3757,8 +3781,7 @@ async function main() {
|
||||
const playing = await page.evaluate(async () => {
|
||||
const radio = window.__godsEyeView.dataManager.layers.get('radio').module;
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const selectedEntity = window.__godsEyeView.viewer.entities.values
|
||||
.find((entity) => String(entity.id).startsWith('radio:selected:'));
|
||||
const selectedEntity = window.__qaRadioSelected();
|
||||
const { getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js');
|
||||
const flightTargets = window.__qaRadioFlyToCalls.map(({ destination }) => {
|
||||
const position = viewer.scene.globe.ellipsoid.cartesianToCartographic(destination);
|
||||
@@ -3775,11 +3798,10 @@ async function main() {
|
||||
flightTargets,
|
||||
cameraHeight: window.__qaRadioCameraHeight,
|
||||
playLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'),
|
||||
regularMarkerSize: Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => window.__godsEyeView.viewer.dataSources.get(index))
|
||||
.find((item) => item.name === 'Radio stations')?.entities.values[0]?.point?.pixelSize?.getValue(),
|
||||
selectedMarkerSize: selectedEntity?.point?.pixelSize?.getValue(),
|
||||
selectedBracketWidth: selectedEntity?.billboard?.width?.getValue(),
|
||||
selectedOwnsNativeLabel: Boolean(selectedEntity?.label),
|
||||
regularMarkerSize: window.__qaRadioRows('stations')[0]?.primitive.pixelSize,
|
||||
selectedMarkerSize: selectedEntity?.dot.primitive.pixelSize,
|
||||
selectedBracketWidth: selectedEntity?.bracket?.primitive.width,
|
||||
selectedOwnsNativeLabel: Boolean(window.__qaRadioRows('selected-label').length),
|
||||
overlay: radio.getOverlayDiagnostics(),
|
||||
host: getWorldOverlayDiagnostics(),
|
||||
expectedPrimary: window.__qaRadioExpectedPrimary,
|
||||
@@ -3817,7 +3839,7 @@ async function main() {
|
||||
id: `qa:${ownerPrefix}:radio-camera-owner`,
|
||||
position: viewer.camera.positionWC.clone(),
|
||||
});
|
||||
owner.gevTrackedId = `${ownerPrefix}:qa-radio-camera-owner`;
|
||||
window.__godsEyeView.entityRecords.write(owner).trackedId = `${ownerPrefix}:qa-radio-camera-owner`;
|
||||
viewer.trackedEntity = owner;
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
const beforeStationId = radio.getUIState().selected?.id || null;
|
||||
@@ -3831,7 +3853,7 @@ async function main() {
|
||||
afterStationId: radio.getUIState().selected?.id || null,
|
||||
flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls,
|
||||
trackedIdentityPreserved: viewer.trackedEntity === owner,
|
||||
trackedId: viewer.trackedEntity?.gevTrackedId || null,
|
||||
trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null,
|
||||
};
|
||||
viewer.trackedEntity = undefined;
|
||||
viewer.entities.remove(owner);
|
||||
@@ -3867,11 +3889,11 @@ async function main() {
|
||||
id: 'qa:flights:delayed-radio-fallback-owner',
|
||||
position: viewer.camera.positionWC.clone(),
|
||||
});
|
||||
owner.gevTrackedId = 'flights:qa-delayed-radio-fallback-owner';
|
||||
window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-delayed-radio-fallback-owner';
|
||||
viewer.trackedEntity = owner;
|
||||
window.__qaDelayedRadioTrackingOwner = owner;
|
||||
window.__qaRejectRadioPlay();
|
||||
return owner.gevTrackedId;
|
||||
return window.__godsEyeView.entityRecords.read(owner)?.trackedId;
|
||||
});
|
||||
await page.waitForFunction(() => window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().audioState === 'playing');
|
||||
const delayedFallbackOwnership = await page.evaluate((beforeFlyToCalls) => {
|
||||
@@ -3880,7 +3902,7 @@ async function main() {
|
||||
const result = {
|
||||
flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls,
|
||||
trackedIdentityPreserved: viewer.trackedEntity === owner,
|
||||
trackedId: viewer.trackedEntity?.gevTrackedId || null,
|
||||
trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null,
|
||||
selectedId: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().selected?.id || null,
|
||||
};
|
||||
viewer.trackedEntity = undefined;
|
||||
@@ -3940,8 +3962,12 @@ async function main() {
|
||||
destination,
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
const selectedEntity = viewer.entities.values
|
||||
.find((entity) => String(entity.id) === `radio:selected:${selected.id}`);
|
||||
// The selected station's drawn dot and bracket, read afresh: Radio's
|
||||
// horizon pass shows them on its own timer.
|
||||
const selectedEntity = () => {
|
||||
const drawn = window.__qaRadioSelected();
|
||||
return drawn?.id === `radio:selected:${selected.id}` ? drawn : null;
|
||||
};
|
||||
const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js');
|
||||
const expectedEntryId = `selected:${selected.id}`;
|
||||
let painted = null;
|
||||
@@ -3949,7 +3975,7 @@ async function main() {
|
||||
// after the camera jump, so a stationary view waits for both to settle.
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && !(painted?.rect && selectedEntity?.show === true);
|
||||
attempt < 20 && !(painted?.rect && selectedEntity()?.show === true);
|
||||
attempt += 1
|
||||
) {
|
||||
painted = await new Promise((resolve) => {
|
||||
@@ -3974,7 +4000,7 @@ async function main() {
|
||||
expectedEntryId,
|
||||
rect: painted?.rect || null,
|
||||
host: painted?.host || getWorldOverlayDiagnostics(),
|
||||
selectedEntityShow: selectedEntity?.show,
|
||||
selectedEntityShow: selectedEntity()?.show,
|
||||
cameraHeight: viewer.camera.positionCartographic.height,
|
||||
};
|
||||
});
|
||||
@@ -3999,8 +4025,12 @@ async function main() {
|
||||
}),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
const selectedEntity = viewer.entities.values
|
||||
.find((entity) => String(entity.id) === `radio:selected:${selected.id}`);
|
||||
// The selected station's drawn dot and bracket, read afresh: Radio's
|
||||
// horizon pass shows them on its own timer.
|
||||
const selectedEntity = () => {
|
||||
const drawn = window.__qaRadioSelected();
|
||||
return drawn?.id === `radio:selected:${selected.id}` ? drawn : null;
|
||||
};
|
||||
const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js');
|
||||
const expectedEntryId = `selected:${selected.id}`;
|
||||
let rect = null;
|
||||
@@ -4025,7 +4055,8 @@ async function main() {
|
||||
viewer.scene.requestRender();
|
||||
});
|
||||
}
|
||||
const entityPosition = selectedEntity?.position?.getValue?.();
|
||||
const selectedDrawn = selectedEntity();
|
||||
const entityPosition = selectedDrawn?.position;
|
||||
const entityAnchor = entityPosition
|
||||
&& viewer.scene.cartesianToCanvasCoordinates(entityPosition);
|
||||
let selectedNativePick = null;
|
||||
@@ -4035,13 +4066,16 @@ async function main() {
|
||||
// billboard satisfy the loop while the point anchor was still missing.
|
||||
for (let attempt = 0; entityAnchor && attempt < 8 && !selectedPointPick; attempt += 1) {
|
||||
const picks = viewer.scene.drillPick(entityAnchor, 16) || [];
|
||||
selectedNativePick = picks.find((picked) => picked?.id === selectedEntity);
|
||||
selectedNativePick = picks.find((picked) => (
|
||||
picked?.primitive === selectedDrawn.dot.primitive
|
||||
|| picked?.primitive === selectedDrawn.bracket?.primitive
|
||||
));
|
||||
selectedPointPick = picks.find((picked) => (
|
||||
picked?.id === selectedEntity
|
||||
picked?.primitive === selectedDrawn.dot.primitive
|
||||
&& String(picked?.primitive?.constructor?.name || '').includes('PointPrimitive')
|
||||
));
|
||||
selectedBillboardPick = picks.find((picked) => (
|
||||
picked?.id === selectedEntity
|
||||
picked?.primitive === selectedDrawn.bracket?.primitive
|
||||
&& String(picked?.primitive?.constructor?.name || '').includes('Billboard')
|
||||
));
|
||||
if (!selectedPointPick) {
|
||||
@@ -4054,18 +4088,15 @@ async function main() {
|
||||
});
|
||||
}
|
||||
}
|
||||
const selectedPointDistance = selectedEntity?.point?.distanceDisplayCondition?.getValue?.();
|
||||
const selectedPointDistance = selectedDrawn?.dot.primitive.distanceDisplayCondition;
|
||||
return {
|
||||
rect,
|
||||
selectedNativePickable: Boolean(selectedNativePick),
|
||||
selectedPointPickable: Boolean(selectedPointPick),
|
||||
selectedBillboardPickable: Boolean(selectedBillboardPick),
|
||||
selectedPointMaxDistance: selectedPointDistance?.far ?? null,
|
||||
selectedEntityShow: selectedEntity?.show,
|
||||
selectedBracketVisible: Boolean(
|
||||
selectedEntity?.billboard
|
||||
&& selectedEntity.billboard.show?.getValue?.() !== false
|
||||
),
|
||||
selectedEntityShow: selectedDrawn?.show,
|
||||
selectedBracketVisible: Boolean(selectedDrawn?.bracket?.show),
|
||||
entityAnchor: entityAnchor ? { x: entityAnchor.x, y: entityAnchor.y } : null,
|
||||
entityDistance: entityPosition
|
||||
? Math.hypot(
|
||||
@@ -4222,7 +4253,7 @@ async function main() {
|
||||
id: 'qa:flights:radio-recenter-stage-owner',
|
||||
position: viewer.camera.positionWC.clone(),
|
||||
});
|
||||
owner.gevTrackedId = 'flights:qa-radio-recenter-stage-owner';
|
||||
window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-radio-recenter-stage-owner';
|
||||
viewer.trackedEntity = owner;
|
||||
completeFlight(0);
|
||||
const trackingBetweenStagesCalls = calls.length;
|
||||
|
||||
@@ -32,13 +32,15 @@ try {
|
||||
const results = await page.evaluate(async () => {
|
||||
window.CESIUM_BASE_URL = '/cesium/';
|
||||
// Use StarrySky's exact Vite dependency URL, including its version query.
|
||||
const source = await fetch('/src/sky/starrySky.js').then((r) => r.text());
|
||||
const source = await fetch('/src/render/cesium/starrySky.js').then((r) =>
|
||||
r.text(),
|
||||
);
|
||||
const cesiumUrl = source.match(
|
||||
/from ["']([^"']*\/cesium\.js[^"']*)["']/,
|
||||
)?.[1];
|
||||
if (!cesiumUrl) throw new Error('run against the Vite dev server');
|
||||
const C = await import(cesiumUrl);
|
||||
const { StarrySky } = await import('/src/sky/starrySky.js');
|
||||
const { StarrySky } = await import('/src/render/cesium/starrySky.js');
|
||||
const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z');
|
||||
const results = {};
|
||||
for (const kind of ['black', 'starry', 'white']) {
|
||||
|
||||
@@ -378,7 +378,9 @@ const findPick = (page, prefix, { box = null, step = 3 } = {}) =>
|
||||
};
|
||||
for (let py = y; py < y + h; py += stride)
|
||||
for (let px = x; px < x + w; px += stride) {
|
||||
const id = scene.pick({ x: px, y: py })?.id;
|
||||
// A drawn item's pick id names its draw set and its own id.
|
||||
const picked = scene.pick({ x: px, y: py })?.id;
|
||||
const id = typeof picked === 'string' ? picked : picked?.id;
|
||||
if (typeof id === 'string' && id.startsWith(want))
|
||||
return {
|
||||
x: rect.left + px,
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Boot the whole application on the stub renderer with only the contract's
|
||||
* required members (`dev/stub-app/main.js`), headless, and check that:
|
||||
*
|
||||
* - it starts, with no Cesium module requested at all (no script, no
|
||||
* worker, no asset it would fetch; the one Cesium stylesheet the build's
|
||||
* `vite-plugin-cesium` links into every page is reported, not failed);
|
||||
* - the credits show in the application's own line, and its list opens
|
||||
* with the data credits;
|
||||
* - each data layer named below turns on, and off, without a page error or
|
||||
* a console error (a feed's failed response is reported as the feed's,
|
||||
* not failed: without network access or keys a feed answers with an
|
||||
* error, and the layer must take that without one of its own; the dev
|
||||
* server's client's own errors are reported as the tooling's);
|
||||
* - with `--strict`, each of them draws on the stub: items in its draw sets,
|
||||
* imagery added through the globe port, or a field (`draw.field`).
|
||||
*
|
||||
* The page is the application's own (`index.html`), served with the stub
|
||||
* entry in place of `src/main.js`. Without `--url` it starts a Vite dev
|
||||
* server of this checkout on `--port` (default 5290) and stops it after.
|
||||
* Live feeds answer through the dev server's providers, so without network
|
||||
* access or keys a layer turns on with nothing to draw: the run says so,
|
||||
* and only `--strict` fails it.
|
||||
*
|
||||
* `--all-capabilities` gives the stub every capability instead, to see what
|
||||
* the layers draw where a renderer has them all.
|
||||
*
|
||||
* npm run qa:stub-boot [-- --url http://127.0.0.1:5280] [--strict]
|
||||
* [--settle-ms 20000] [--json path] [--all-capabilities]
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import puppeteer from 'puppeteer';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** The data layers the stub must run, by catalog id. */
|
||||
export const STUB_BOOT_LAYERS = Object.freeze([
|
||||
'flights',
|
||||
'military',
|
||||
'transit',
|
||||
'traffic',
|
||||
'cctv',
|
||||
'ais-live-vessels',
|
||||
'weather-radar',
|
||||
'weather-satellite',
|
||||
'wind',
|
||||
'satellites',
|
||||
'local-firms',
|
||||
'wildlife-sightings',
|
||||
'shipwrecks',
|
||||
'news',
|
||||
]);
|
||||
|
||||
/** A request that is Cesium: the package, its pre-bundle, or its assets. */
|
||||
export const isCesiumRequest = (url) =>
|
||||
/(?:^|[/._-])cesium(?:[/._-]|$)/i.test(new URL(url).pathname);
|
||||
|
||||
/** The stylesheet `vite-plugin-cesium` links into every page it serves. */
|
||||
const isPluginStylesheet = (url, type) =>
|
||||
type === 'stylesheet' &&
|
||||
new URL(url).pathname === '/cesium/Widgets/widgets.css';
|
||||
|
||||
/**
|
||||
* A browser's line for a feed's response that failed: one of the dev
|
||||
* server's providers (`/api/`) or another origin's. The application's own
|
||||
* modules and assets failing are the page's.
|
||||
*/
|
||||
const isFailedResponse = (text, at, base) => {
|
||||
if (!/^Failed to load resource:/.test(text)) return false;
|
||||
try {
|
||||
const url = new URL(at);
|
||||
return (
|
||||
url.origin !== new URL(base).origin || url.pathname.startsWith('/api/')
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* An error the dev server's own client logs (its socket to the server, which
|
||||
* a headless browser can refuse): the tooling's, not the application's.
|
||||
*/
|
||||
const isDevClient = (at) => {
|
||||
try {
|
||||
return new URL(at).pathname === '/@vite/client';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { strict: false, port: 5290, settleMs: 20_000 };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--strict') args.strict = true;
|
||||
else if (arg === '--url') args.url = argv[++i];
|
||||
else if (arg === '--port') args.port = Number(argv[++i]);
|
||||
else if (arg === '--settle-ms') args.settleMs = Number(argv[++i]);
|
||||
else if (arg === '--json') args.json = argv[++i];
|
||||
else if (arg === '--all-capabilities') args.allCapabilities = true;
|
||||
else throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
async function startViteServer(port) {
|
||||
const { createServer } = await import('vite');
|
||||
const server = await createServer({
|
||||
root: ROOT,
|
||||
configFile: path.join(ROOT, 'vite.config.js'),
|
||||
// No hot reload: the page is loaded once and nothing edits it.
|
||||
server: { port, strictPort: true, host: '127.0.0.1', hmr: false },
|
||||
logLevel: 'warn',
|
||||
});
|
||||
await server.listen();
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* In the page: what the stub renderer draws now, its draw sets with how many
|
||||
* items each holds and the globe port's imagery layers, and how many calls
|
||||
* it has had on each port member.
|
||||
*/
|
||||
function readDrawn() {
|
||||
const renderer = window.__stubBoot?.renderers?.[0];
|
||||
if (!renderer) return null;
|
||||
const testing = renderer.testing;
|
||||
const calls = {};
|
||||
for (const call of testing.calls) {
|
||||
const key = `${call.port}.${call.member}`;
|
||||
calls[key] = (calls[key] ?? 0) + 1;
|
||||
}
|
||||
return {
|
||||
sets: Object.fromEntries(
|
||||
testing.sets().map((id) => [id, testing.setRecord(id)?.items?.size ?? 0]),
|
||||
),
|
||||
imagery: renderer.globe.imagery.list().length,
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const server = args.url ? null : await startViteServer(args.port);
|
||||
try {
|
||||
await run(args);
|
||||
} finally {
|
||||
await server?.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args) {
|
||||
const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, '');
|
||||
const browser = await puppeteer.launch({
|
||||
headless: true,
|
||||
executablePath:
|
||||
process.env.PUPPETEER_EXECUTABLE_PATH ||
|
||||
(await puppeteer.executablePath()),
|
||||
defaultViewport: { width: 1280, height: 800 },
|
||||
protocolTimeout: 300_000,
|
||||
args: ['--no-sandbox'],
|
||||
});
|
||||
/** Every error the page reports, in order: `page`, `console` or `response`. */
|
||||
const errors = [];
|
||||
const cesiumRequests = [];
|
||||
const cesiumStylesheets = [];
|
||||
const report = { url: base, layers: {}, ok: false };
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
page.on('console', (message) => {
|
||||
if (message.type() !== 'error') return;
|
||||
const text = message.text();
|
||||
const at = message.location()?.url ?? null;
|
||||
errors.push({
|
||||
kind: isFailedResponse(text, at, base)
|
||||
? 'response'
|
||||
: isDevClient(at)
|
||||
? 'tooling'
|
||||
: 'console',
|
||||
text,
|
||||
at,
|
||||
});
|
||||
});
|
||||
page.on('pageerror', (error) =>
|
||||
errors.push({ kind: 'page', text: String(error?.stack || error) }),
|
||||
);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', async (request) => {
|
||||
const url = request.url();
|
||||
if (url.startsWith(base) && isCesiumRequest(url))
|
||||
(isPluginStylesheet(url, request.resourceType())
|
||||
? cesiumStylesheets
|
||||
: cesiumRequests
|
||||
).push(url);
|
||||
// The application's page, with the stub entry in place of its own.
|
||||
if (request.isNavigationRequest() && url.startsWith(base)) {
|
||||
const response = await fetch(url);
|
||||
const html = (await response.text()).replace(
|
||||
'src="/src/main.js"',
|
||||
'src="/dev/stub-app/main.js"',
|
||||
);
|
||||
if (!html.includes('/dev/stub-app/main.js'))
|
||||
throw new Error('The page has no /src/main.js entry to replace');
|
||||
await request.respond({
|
||||
status: response.status,
|
||||
contentType: 'text/html',
|
||||
body: html,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await request.continue();
|
||||
});
|
||||
await page.goto(
|
||||
`${base}/${args.allCapabilities ? '?capabilities=all' : ''}`,
|
||||
{ waitUntil: 'load', timeout: 180_000 },
|
||||
);
|
||||
await page.waitForFunction(() => window.__stubBoot, { timeout: 180_000 });
|
||||
const started = await page.evaluate(() => window.__stubBoot.started);
|
||||
report.started = started;
|
||||
if (!started.ok) throw new Error(`Startup failed: ${started.error}`);
|
||||
await page.waitForFunction(() => window.__godsEyeView?.dataManager, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
report.renderer = await page.evaluate(() => {
|
||||
const renderer = window.__stubBoot.renderers[0];
|
||||
return {
|
||||
id: renderer.id,
|
||||
capabilities: [...renderer.capabilities],
|
||||
canvasInPage: document.contains(renderer.canvas),
|
||||
};
|
||||
});
|
||||
report.startupErrors = errors.slice();
|
||||
// The credits show in the application's own line, with no Cesium: the
|
||||
// line is on screen and its list opens with the data credits in it.
|
||||
report.credits = await page.evaluate(async () => {
|
||||
const line = document.getElementById('gev-credits');
|
||||
const expand = line?.querySelector('.gev-credits-expand');
|
||||
const panel = document.getElementById('gev-credits-panel');
|
||||
const box = line?.getBoundingClientRect();
|
||||
const visible =
|
||||
Boolean(box && box.width > 0 && box.height > 0) &&
|
||||
getComputedStyle(line).visibility !== 'hidden';
|
||||
expand?.click();
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
const listed =
|
||||
panel?.hidden === false ? panel.querySelectorAll('li').length : 0;
|
||||
expand?.click();
|
||||
return { visible, line: line?.textContent ?? null, listed };
|
||||
});
|
||||
console.log(
|
||||
`credits: ${report.credits.visible ? 'shown' : 'NOT shown'}; line "${report.credits.line}"; ${report.credits.listed} listed`,
|
||||
);
|
||||
const known = await page.evaluate(() =>
|
||||
window.__godsEyeView.dataManager.getAll().map((layer) => layer.id),
|
||||
);
|
||||
report.missingLayers = STUB_BOOT_LAYERS.filter((id) => !known.includes(id));
|
||||
for (const id of STUB_BOOT_LAYERS) {
|
||||
if (!known.includes(id)) continue;
|
||||
const errorsBefore = errors.length;
|
||||
const before = await page.evaluate(readDrawn);
|
||||
const enabled = await page.evaluate(
|
||||
(layerId) =>
|
||||
window.__godsEyeView.dataManager
|
||||
.setEnabled(layerId, true, { origin: 'user' })
|
||||
.then(
|
||||
// It can answer false rather than throw: on is what it says.
|
||||
(value) => ({
|
||||
ok:
|
||||
value !== false &&
|
||||
window.__godsEyeView.dataManager.isEnabled(layerId),
|
||||
value: value ?? null,
|
||||
}),
|
||||
(error) => ({ ok: false, error: String(error?.stack || error) }),
|
||||
),
|
||||
id,
|
||||
);
|
||||
// Feeds load on their own schedule; keep ticking until they draw.
|
||||
const deadline = Date.now() + args.settleMs;
|
||||
let drawn = { sets: {}, imagery: 0, calls: {}, fields: 0 };
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000));
|
||||
const now = await page.evaluate(readDrawn);
|
||||
drawn = {
|
||||
sets: Object.fromEntries(
|
||||
Object.entries(now.sets).filter(
|
||||
([setId, items]) => items > 0 && before.sets[setId] !== items,
|
||||
),
|
||||
),
|
||||
imagery: Math.max(0, now.imagery - before.imagery),
|
||||
calls: Object.fromEntries(
|
||||
Object.entries(now.calls)
|
||||
.map(([key, n]) => [key, n - (before.calls[key] ?? 0)])
|
||||
.filter(([, n]) => n > 0),
|
||||
),
|
||||
};
|
||||
drawn.fields = drawn.calls['draw.field'] ?? 0;
|
||||
if (Object.keys(drawn.sets).length || drawn.imagery || drawn.fields)
|
||||
break;
|
||||
}
|
||||
const stats = await page.evaluate((layerId) => {
|
||||
const row = window.__godsEyeView.dataManager
|
||||
.getAll()
|
||||
.find((layer) => layer.id === layerId);
|
||||
return {
|
||||
enabled: row?.enabled ?? null,
|
||||
count: row?.stats?.count ?? null,
|
||||
error: row?.stats?.error ?? null,
|
||||
source: row?.stats?.source ?? null,
|
||||
};
|
||||
}, id);
|
||||
const disabled = await page.evaluate(
|
||||
(layerId) =>
|
||||
window.__godsEyeView.dataManager
|
||||
.setEnabled(layerId, false, { origin: 'user' })
|
||||
.then(
|
||||
(value) => ({
|
||||
ok:
|
||||
value !== false &&
|
||||
!window.__godsEyeView.dataManager.isEnabled(layerId),
|
||||
}),
|
||||
(error) => ({ ok: false, error: String(error?.stack || error) }),
|
||||
),
|
||||
id,
|
||||
);
|
||||
const layerErrors = errors.slice(errorsBefore);
|
||||
report.layers[id] = {
|
||||
enabled,
|
||||
disabled,
|
||||
stats,
|
||||
drawn,
|
||||
errors: layerErrors.filter(
|
||||
(error) => error.kind === 'page' || error.kind === 'console',
|
||||
),
|
||||
failedResponses: layerErrors
|
||||
.filter((error) => error.kind === 'response')
|
||||
.map((error) => error.at),
|
||||
};
|
||||
const what = [
|
||||
...Object.entries(drawn.sets).map(([setId, n]) => `${setId}=${n}`),
|
||||
...(drawn.imagery ? [`${drawn.imagery} imagery layer(s)`] : []),
|
||||
...(drawn.fields ? [`${drawn.fields} field(s)`] : []),
|
||||
];
|
||||
console.log(
|
||||
`${id}: ${enabled.ok && disabled.ok ? 'ran' : 'FAILED'}; drew ${
|
||||
what.length ? what.join(', ') : 'nothing'
|
||||
}${stats.error ? `; feed: ${stats.error}` : ''}${
|
||||
report.layers[id].failedResponses.length
|
||||
? `; ${report.layers[id].failedResponses.length} failed response(s)`
|
||||
: ''
|
||||
}`,
|
||||
);
|
||||
}
|
||||
report.ok = true;
|
||||
} catch (error) {
|
||||
// Reported with the rest below, so the report and errors are kept.
|
||||
report.failure = String(error?.stack || error);
|
||||
} finally {
|
||||
report.cesiumRequests = cesiumRequests;
|
||||
report.cesiumStylesheets = cesiumStylesheets;
|
||||
report.errors = errors;
|
||||
await browser.close();
|
||||
}
|
||||
const pageErrors = errors.filter((error) => error.kind === 'page');
|
||||
const consoleErrors = errors.filter((error) => error.kind === 'console');
|
||||
const failedResponses = errors.filter((error) => error.kind === 'response');
|
||||
const toolingErrors = errors.filter((error) => error.kind === 'tooling');
|
||||
const problems = [];
|
||||
if (report.failure) problems.push(`the run stopped: ${report.failure}`);
|
||||
if (!report.started?.ok) problems.push('the application did not start');
|
||||
if (!report.renderer?.canvasInPage)
|
||||
problems.push("the stub's canvas is not in the page");
|
||||
if (
|
||||
report.started?.ok &&
|
||||
(!report.credits?.visible || !report.credits.listed)
|
||||
)
|
||||
problems.push('the credits line is not shown, or its list is empty');
|
||||
if (cesiumRequests.length)
|
||||
problems.push(`Cesium was requested: ${cesiumRequests.join(', ')}`);
|
||||
if (pageErrors.length) problems.push(`${pageErrors.length} page error(s)`);
|
||||
if (consoleErrors.length)
|
||||
problems.push(`${consoleErrors.length} console error(s)`);
|
||||
if (report.missingLayers?.length)
|
||||
problems.push(`layers not in the catalog: ${report.missingLayers}`);
|
||||
for (const [id, layer] of Object.entries(report.layers)) {
|
||||
if (!layer.enabled.ok || !layer.disabled.ok)
|
||||
problems.push(`${id} failed to turn on or off`);
|
||||
if (
|
||||
args.strict &&
|
||||
!Object.keys(layer.drawn.sets).length &&
|
||||
!layer.drawn.imagery &&
|
||||
!layer.drawn.fields
|
||||
)
|
||||
problems.push(`${id} drew nothing`);
|
||||
}
|
||||
report.problems = problems;
|
||||
if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2));
|
||||
for (const error of [...pageErrors, ...consoleErrors])
|
||||
console.error(`${error.kind} error: ${error.text} (${error.at ?? '?'})`);
|
||||
if (cesiumStylesheets.length)
|
||||
console.log(
|
||||
`note: the build's Cesium plugin linked ${cesiumStylesheets.join(', ')}`,
|
||||
);
|
||||
if (toolingErrors.length)
|
||||
console.log(
|
||||
`note: the dev server's client logged ${toolingErrors.length} error(s): ${[
|
||||
...new Set(toolingErrors.map((error) => error.text)),
|
||||
].join(' | ')}`,
|
||||
);
|
||||
if (failedResponses.length)
|
||||
console.log(
|
||||
`note: ${failedResponses.length} feed response(s) failed (keys or network)`,
|
||||
);
|
||||
if (problems.length) {
|
||||
console.error(`FAIL: ${problems.join('; ')}`);
|
||||
process.exitCode = 1;
|
||||
} else console.log('ok: the application runs on the stub renderer');
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`)
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
* answers HTTP 429 for most of them. This harness drives that burst, counts the
|
||||
* throttled responses, keeps the first 429's headers as evidence, and then
|
||||
* checks whether every throttled tile eventually loaded — the contract the
|
||||
* client-side retry in `src/maps/terrain.js` provides.
|
||||
* client-side retry in `src/render/cesium/mapTerrain.js` provides.
|
||||
*
|
||||
* Run against a keyless dev server (no Google or ion credentials):
|
||||
* env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180
|
||||
|
||||
@@ -8,13 +8,16 @@
|
||||
* 1. exact-viewport revisit (traffic module's full-road cache),
|
||||
* 2. adjacent 0.4–2 km pan (new exact bbox with heavy spatial overlap),
|
||||
* 3. cold city (no traffic-module entry for that city),
|
||||
* 4. degraded upstream (synthetic delay on `/api/overpass` only).
|
||||
* 4. degraded upstream (synthetic delay on the road requests: OpenFreeMap's
|
||||
* host, which only traffic reads in this capture, or the Overpass proxy).
|
||||
*
|
||||
* The proxy's actual `X-Overpass-Cache` result is printed for every network
|
||||
* pass, so HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference.
|
||||
* The degraded leg delays request release in Puppeteer; it exercises the same
|
||||
* fetch-start→response boundary without adding a failure switch to the
|
||||
* application or proxy. Pass `--degraded-delay-ms 0` to skip that leg.
|
||||
* Keyless roads come from OpenFreeMap vector tiles (`tiles.openfreemap.org`);
|
||||
* a build that still reads them through the Overpass proxy has its
|
||||
* `X-Overpass-Cache` result printed for every network pass, so
|
||||
* HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference ("—" for
|
||||
* tiles). The degraded leg delays the road requests' release in Puppeteer;
|
||||
* it exercises the same fetch-start→response boundary without adding a
|
||||
* failure switch to the application or proxy. Pass `--degraded-delay-ms 0` to skip that leg.
|
||||
* TomTom status is intercepted as keyless so no live-flow key is required and
|
||||
* the capture isolates the OSM road-to-visible-dot chain.
|
||||
*
|
||||
@@ -93,9 +96,42 @@ function debugUrl(rawUrl) {
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Position the camera and explicitly raise the boundaries the layer observes. */
|
||||
/**
|
||||
* Let the camera report a move the way a user's does: traffic hears the
|
||||
* camera port's `changed` at its own 5% threshold (layers/traffic/policy.js
|
||||
* CAMERA_CHANGED_THRESHOLD), which the port measures on every scene tick
|
||||
* (the first measurement after a listener subscribes only records its
|
||||
* baseline pose). Waiting for two drawn frames after the move is the sync
|
||||
* point that the port has measured it. Cesium's own moveEnd (500 ms after
|
||||
* stillness) is left to Cesium, as in the app; traffic re-checks the view
|
||||
* on it. Installed in the page as `window.__qaRenderAfterMove`; throws when
|
||||
* the frames do not draw within 5 s.
|
||||
*/
|
||||
function installRenderAfterMove() {
|
||||
window.__qaRenderAfterMove = (gev) => new Promise((resolve, reject) => {
|
||||
const scene = gev.viewer.scene;
|
||||
let frames = 0;
|
||||
let remove = null;
|
||||
const timer = setTimeout(() => {
|
||||
remove();
|
||||
reject(new Error(`the camera move rendered ${frames} frame(s) in 5 s`));
|
||||
}, 5000);
|
||||
remove = scene.postRender.addEventListener(() => {
|
||||
if (++frames >= 2) {
|
||||
clearTimeout(timer);
|
||||
remove();
|
||||
resolve(frames);
|
||||
return;
|
||||
}
|
||||
scene.requestRender();
|
||||
});
|
||||
scene.requestRender();
|
||||
});
|
||||
}
|
||||
|
||||
/** Position the camera and render, so the layer hears the move as it would a user's. */
|
||||
async function moveCamera(page, view) {
|
||||
return page.evaluate((v) => {
|
||||
return page.evaluate(async (v) => {
|
||||
const gev = window.__godsEyeView;
|
||||
const module = gev.dataManager.layers.get('traffic').module;
|
||||
const beforeLastUpdate = module.getStats().lastUpdate;
|
||||
@@ -115,12 +151,7 @@ async function moveCamera(page, view) {
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
// setView normally propagates through Cesium's render loop. Raising these
|
||||
// explicitly makes the capture boundary deterministic across GPU speeds.
|
||||
// Pairing still flows through camera.changed's schedule-time anchor; the
|
||||
// synthetic moveEnd is emitted only as the same diagnostic used naturally.
|
||||
gev.viewer.camera.changed.raiseEvent();
|
||||
gev.viewer.camera.moveEnd.raiseEvent();
|
||||
await window.__qaRenderAfterMove(gev);
|
||||
return { beforeLastUpdate, boundaryTime };
|
||||
}, view);
|
||||
}
|
||||
@@ -159,14 +190,29 @@ function readTrafficMeasures(page, boundaryTime) {
|
||||
})), boundaryTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Road requests the page sent, counted by the request interceptor: `sent` is
|
||||
* every road request that reached the network, `delayed` those it held for
|
||||
* the degraded leg. `requestRoads()` can be answered from decoded tiles
|
||||
* already in memory, so a `fetch-to-response` measure alone does not prove
|
||||
* the network was used.
|
||||
*/
|
||||
const roadRequests = { sent: 0, delayed: 0 };
|
||||
|
||||
/** Drive one measured state and return its raw User Timing measures. */
|
||||
async function captureState(page, name, view, setDelay) {
|
||||
setDelay(name === 'degraded-upstream' ? DEGRADED_DELAY_MS : 0);
|
||||
const before = { ...roadRequests };
|
||||
const { beforeLastUpdate, boundaryTime } = await moveCamera(page, view);
|
||||
await waitForTrafficCapture(page, beforeLastUpdate, boundaryTime);
|
||||
const measures = await readTrafficMeasures(page, boundaryTime);
|
||||
setDelay(0);
|
||||
return { name, measures };
|
||||
return {
|
||||
name,
|
||||
measures,
|
||||
sent: roadRequests.sent - before.sent,
|
||||
delayed: roadRequests.delayed - before.delayed,
|
||||
};
|
||||
}
|
||||
|
||||
/** Format a duration without hiding zero-duration measurements. */
|
||||
@@ -318,13 +364,14 @@ async function main() {
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport({ width: 1440, height: 900 });
|
||||
await page.evaluateOnNewDocument(() => localStorage.clear());
|
||||
await page.evaluateOnNewDocument(installRenderAfterMove);
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') consoleErrors.push(message.text());
|
||||
});
|
||||
page.on('pageerror', (error) => consoleErrors.push(error.message));
|
||||
|
||||
// Force keyless traffic and optionally hold Overpass requests to model a
|
||||
// degraded proxy/upstream. No server key or proxy debug endpoint is needed.
|
||||
// Force keyless traffic and optionally hold the road requests to model a
|
||||
// degraded upstream. No server key or proxy debug endpoint is needed.
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', async (request) => {
|
||||
if (request.url().includes('/api/tomtom/status')) {
|
||||
@@ -335,7 +382,11 @@ async function main() {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (activeProxyDelayMs > 0 && request.url().includes('/api/overpass')) {
|
||||
const roadRequest = request.url().includes('/api/overpass')
|
||||
|| new URL(request.url()).hostname === 'tiles.openfreemap.org';
|
||||
if (roadRequest) roadRequests.sent += 1;
|
||||
if (activeProxyDelayMs > 0 && roadRequest) {
|
||||
roadRequests.delayed += 1;
|
||||
await sleep(activeProxyDelayMs);
|
||||
}
|
||||
try { await request.continue(); } catch { /* page closed or already handled */ }
|
||||
@@ -363,8 +414,9 @@ async function main() {
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
await gev.dataManager.setEnabled('traffic', true);
|
||||
gev.viewer.camera.changed.raiseEvent();
|
||||
gev.viewer.camera.moveEnd.raiseEvent();
|
||||
// Also records the baseline pose traffic's new `changed` listener
|
||||
// measures the first measured move against.
|
||||
await window.__qaRenderAfterMove(gev);
|
||||
}, VIEWS.austin);
|
||||
await sleep(500);
|
||||
|
||||
@@ -386,7 +438,7 @@ async function main() {
|
||||
|
||||
// Clear the last-bounds gate without clearing the module's road cache, then
|
||||
// revisit the byte-identical camera pose for a true client-cache hit.
|
||||
await page.evaluate((view) => {
|
||||
await page.evaluate(async (view) => {
|
||||
const gev = window.__godsEyeView;
|
||||
const ellipsoid = gev.viewer.scene.globe.ellipsoid;
|
||||
const radians = Math.PI / 180;
|
||||
@@ -398,8 +450,7 @@ async function main() {
|
||||
}),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
gev.viewer.camera.changed.raiseEvent();
|
||||
gev.viewer.camera.moveEnd.raiseEvent();
|
||||
await window.__qaRenderAfterMove(gev);
|
||||
}, VIEWS.austin);
|
||||
await sleep(500);
|
||||
|
||||
@@ -428,7 +479,7 @@ async function main() {
|
||||
}
|
||||
for (const capture of captures.slice(1)) {
|
||||
if (!capture.measures.some((entry) => entry.detail?.segment === 'fetch-to-response')) {
|
||||
throw new Error(`${capture.name} did not issue an Overpass request`);
|
||||
throw new Error(`${capture.name} did not issue a road request`);
|
||||
}
|
||||
}
|
||||
if (DEGRADED_DELAY_MS > 0) {
|
||||
@@ -438,20 +489,35 @@ async function main() {
|
||||
&& entry.duration >= DEGRADED_DELAY_MS * 0.9
|
||||
));
|
||||
if (!delayed) throw new Error('degraded-upstream leg did not observe the synthetic delay');
|
||||
// The delay has to come from held road requests, not from processing
|
||||
// that happened to run long.
|
||||
if (!degraded.delayed) throw new Error('degraded-upstream leg sent no road request to hold');
|
||||
}
|
||||
// A city the client has never seen has no tiles in memory: it must reach
|
||||
// the network. The other legs may legitimately be answered from tiles
|
||||
// already decoded, so their counts are reported, not asserted.
|
||||
const cold = captures.find((capture) => capture.name === 'cold city (client)');
|
||||
if (!cold?.sent) throw new Error('cold city leg sent no road request to the network');
|
||||
|
||||
const rows = captures.flatMap(rowsForCapture);
|
||||
if (!rows.length) throw new Error('no measured traffic renders were captured');
|
||||
console.log('\nCausal segments (one row per visible major/full pass)');
|
||||
console.table(rows);
|
||||
console.log('\nRoad requests sent to the network per leg (held by the degraded leg)');
|
||||
console.table(captures.map((capture) => ({
|
||||
State: capture.name,
|
||||
Sent: capture.sent,
|
||||
Held: capture.delayed,
|
||||
})));
|
||||
console.log('\nNotes:');
|
||||
console.log(' - Render→postRender is the first visible-frame boundary used by Phase 0.');
|
||||
console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch.');
|
||||
console.log(' - response.json includes both body transfer and JSON decoding; the production path does not split them.');
|
||||
console.log(' - Last change→fetch is approximately the 320 ms FETCH_DEBOUNCE for the first fetch by construction.');
|
||||
console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch, or the roads came from OpenFreeMap tiles.');
|
||||
console.log(' - Through the Overpass proxy, Fetch→response is the HTTP response and response.json is body transfer plus JSON decoding.');
|
||||
console.log(' - From OpenFreeMap tiles, Fetch→response spans the tile requests, body reads, decoding and composition, and response.json only hands back the built object; a held leg can stack the delay over tiles fetched in turn.');
|
||||
console.log(' - Last change→fetch is the 320 ms FETCH_DEBOUNCE for the first fetch by construction, plus timer and main-thread latency (larger under SwiftShader).');
|
||||
console.log(' - Full-pass Last change→fetch also includes the intentionally sequential major pass.');
|
||||
console.log(' - Cesium moveEnd is a diagnostic raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it.');
|
||||
console.log(' - Synthetic events bypass camera percentageChanged/inertia but use the same camera.changed schedule-time anchor as natural captures.');
|
||||
console.log(' - Cesium moveEnd is raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it, and traffic only re-checks the view on it.');
|
||||
console.log(' - Moves are setView plus rendered frames: the camera port measures traffic\'s own 5% changed threshold as for a user move (inertia is bypassed).');
|
||||
console.log(' - The keyless capture zeroes Flow race and Heat lines work; live-keyed numbers will differ.');
|
||||
console.log(' - Measurement caveat: timings include instrumentation overhead (observer effect) and browser clock-floor quantization.');
|
||||
console.log(' - Per-road clock observations inside road-parse-total/waypoint-materialization slightly overstate production work.');
|
||||
|
||||
@@ -158,9 +158,13 @@ try {
|
||||
(window.__motion.holdStart === null
|
||||
? ''
|
||||
: ` | camera stopped +${((now - window.__motion.holdStart) / 1000).toFixed(1)}s`);
|
||||
// A layer dot is its draw item (`pos`, hidden only when `show` is
|
||||
// false); a collection's point is Cesium's.
|
||||
const visit = (id, roadId, point) => {
|
||||
if (!point.show) return;
|
||||
const s = scene.cartesianToCanvasCoordinates(point.position);
|
||||
if (point.show === false) return;
|
||||
const s = scene.cartesianToCanvasCoordinates(
|
||||
point.pos ?? point.position,
|
||||
);
|
||||
if (s && s.x >= 0 && s.y >= 0 && s.x <= 1280 && s.y <= 800)
|
||||
points.set(id, { x: s.x, y: s.y, roadId });
|
||||
};
|
||||
@@ -168,7 +172,7 @@ try {
|
||||
offRoad = 0;
|
||||
if (!baseline && layer.visitMotionDots) {
|
||||
layer.visitMotionDots((id, roadId, point, road) => {
|
||||
if (point.show) {
|
||||
if (point.show !== false) {
|
||||
const p = road?.roadProperties;
|
||||
const allowed = road?.directFlow
|
||||
? [
|
||||
@@ -195,7 +199,7 @@ try {
|
||||
p?.brunnel !== 'tunnel';
|
||||
if (!allowed) offRoad++;
|
||||
}
|
||||
if (point.show) n++;
|
||||
if (point.show !== false) n++;
|
||||
visit(id, roadId, point);
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -83,9 +83,10 @@ try {
|
||||
lower = 0;
|
||||
dataManager.layers
|
||||
.get('traffic')
|
||||
.module.visitMotionDots((id, key, p) => {
|
||||
if (!p.show) return;
|
||||
const s = viewer.scene.cartesianToCanvasCoordinates(p.position);
|
||||
.module.visitMotionDots((id, key, dot) => {
|
||||
// A dot is its draw item: `pos`, hidden only when `show` is false.
|
||||
if (dot.show === false) return;
|
||||
const s = viewer.scene.cartesianToCanvasCoordinates(dot.pos);
|
||||
if (s && s.x >= 240 && s.x <= 1040 && s.y >= 0 && s.y <= 800) {
|
||||
if (s.y < 400) upper++;
|
||||
else lower++;
|
||||
@@ -197,8 +198,10 @@ try {
|
||||
const camera = viewer.camera.positionWC;
|
||||
dataManager.layers
|
||||
.get('traffic')
|
||||
.module.visitMotionDots((id, key, p) => {
|
||||
if (!p.show) return;
|
||||
.module.visitMotionDots((id, key, dot) => {
|
||||
// A dot is its draw item: `pos`, hidden only when `show` is false.
|
||||
if (dot.show === false) return;
|
||||
const p = { position: dot.pos };
|
||||
const q = viewer.scene.cartesianToCanvasCoordinates(p.position);
|
||||
if (q && q.x >= 240 && q.x <= 1040 && q.y >= 0 && q.y <= 800) {
|
||||
if (q.y < 400) upper++;
|
||||
|
||||
@@ -177,6 +177,19 @@ export async function sampleTransitPixels(page, palette) {
|
||||
];
|
||||
const width = canvas.clientWidth;
|
||||
const height = canvas.clientHeight;
|
||||
// The billboards the draw port drew for the layer's two sets, by
|
||||
// vehicle key, with the collection drawing each.
|
||||
const drawn = new Map();
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++) {
|
||||
const billboard = host.get(j);
|
||||
if (typeof billboard?.id?.id === 'string')
|
||||
drawn.set(billboard.id.id, { billboard, host });
|
||||
}
|
||||
}
|
||||
const sprites = [];
|
||||
const footprints = [];
|
||||
const intersects = (a, b) =>
|
||||
@@ -256,20 +269,26 @@ export async function sampleTransitPixels(page, palette) {
|
||||
};
|
||||
for (const entry of state._vehicles.values()) {
|
||||
if (!entry.marker || entry.marker.show === false) continue;
|
||||
const p = entry.marker.position;
|
||||
const row = drawn.get(entry.key);
|
||||
if (!row || row.billboard.show === false) {
|
||||
skipped.push({ key: entry.key, reason: 'billboard not drawn' });
|
||||
continue;
|
||||
}
|
||||
const billboard = row.billboard;
|
||||
const p = billboard.position;
|
||||
const clip = mul(proj, mul(view, [p.x, p.y, p.z, 1]));
|
||||
if (!(clip[3] > 0)) continue;
|
||||
const screen = entry.marker.computeScreenSpacePosition?.(scene) || {
|
||||
const screen = billboard.computeScreenSpacePosition?.(scene) || {
|
||||
x: ((clip[0] / clip[3]) * 0.5 + 0.5) * width,
|
||||
y: (1 - ((clip[1] / clip[3]) * 0.5 + 0.5)) * height,
|
||||
};
|
||||
const rect = entry.marker.constructor.getScreenSpaceBoundingBox?.(
|
||||
entry.marker,
|
||||
const rect = billboard.constructor.getScreenSpaceBoundingBox?.(
|
||||
billboard,
|
||||
screen,
|
||||
) || { x: screen.x - 16, y: screen.y - 16, width: 32, height: 32 };
|
||||
const { x, y } = screenPoint(screen.x, screen.y);
|
||||
const c = Math.abs(Math.cos(entry.marker.rotation || 0)),
|
||||
sn = Math.abs(Math.sin(entry.marker.rotation || 0));
|
||||
const c = Math.abs(Math.cos(billboard.rotation || 0)),
|
||||
sn = Math.abs(Math.sin(billboard.rotation || 0));
|
||||
const w = rect.width * c + rect.height * sn,
|
||||
h = rect.height * c + rect.width * sn;
|
||||
const footprint = { x: x - w / 2, y: y - h / 2, w, h };
|
||||
@@ -282,10 +301,7 @@ export async function sampleTransitPixels(page, palette) {
|
||||
rect.y + rect.height > height
|
||||
)
|
||||
reason = 'billboard rectangle outside frame';
|
||||
if (
|
||||
entry.marker.color?.alpha < 0.95 ||
|
||||
entry.markerCollection?.show === false
|
||||
)
|
||||
if (billboard.color?.alpha < 0.95 || row.host.show === false)
|
||||
reason = 'billboard not opaque/collection hidden';
|
||||
const raster = rasters.get(entry.marker.image);
|
||||
if (!raster) reason = 'billboard alpha unavailable';
|
||||
@@ -351,12 +367,12 @@ export async function sampleTransitPixels(page, palette) {
|
||||
bracketX: entry.detectContact?._candidateScreenX ?? screen.x,
|
||||
bracketY: entry.detectContact?._candidateScreenY ?? screen.y,
|
||||
raster,
|
||||
rotation: entry.marker.rotation || 0,
|
||||
halfW: Number.isFinite(entry.marker.width)
|
||||
? Math.ceil(entry.marker.width / 2) + 2
|
||||
rotation: billboard.rotation || 0,
|
||||
halfW: Number.isFinite(billboard.width)
|
||||
? Math.ceil(billboard.width / 2) + 2
|
||||
: 11,
|
||||
halfH: Number.isFinite(entry.marker.height)
|
||||
? Math.ceil(entry.marker.height / 2) + 2
|
||||
halfH: Number.isFinite(billboard.height)
|
||||
? Math.ceil(billboard.height / 2) + 2
|
||||
: 7,
|
||||
});
|
||||
}
|
||||
@@ -658,12 +674,23 @@ export function readTransitFleetStyle({ key, resetSelection = false } = {}) {
|
||||
const entry = key
|
||||
? state._vehicles.get(key)
|
||||
: [...state._vehicles.values()].find((e) => e.marker?.show);
|
||||
return entry
|
||||
// The billboard the draw port drew for it, in either of the layer's sets.
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
let billboard = null;
|
||||
for (let i = 0; entry && !billboard && i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++)
|
||||
if (host.get(j)?.id?.id === entry.key) billboard = host.get(j);
|
||||
}
|
||||
// An undrawn marker has no style to compare: no answer.
|
||||
return entry && billboard
|
||||
? {
|
||||
key: entry.key,
|
||||
selected: state._selectedKey === entry.key,
|
||||
color: entry.marker.color.toCssColorString(),
|
||||
width: entry.marker.width,
|
||||
color: billboard.color.toCssColorString(),
|
||||
width: billboard.width,
|
||||
image: entry.marker.image,
|
||||
}
|
||||
: null;
|
||||
|
||||
@@ -182,7 +182,8 @@ try {
|
||||
});
|
||||
parts.rendering.sampleIdle(entry);
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
const V = entry.marker.position.constructor;
|
||||
// Marker positions are plain records; the camera's eye is a Cartesian3.
|
||||
const V = scene.camera.positionWC.constructor;
|
||||
const points = entry.trailSegments
|
||||
.filter((s) => s.toT <= entry.sample.displayT)
|
||||
.flatMap((s) => s.positions);
|
||||
|
||||
+108
-31
@@ -146,11 +146,7 @@ export async function runFleetBudgets({
|
||||
// The retained delta is conservative: it includes concurrent page growth.
|
||||
const retained = await cdp.send('Runtime.getHeapUsage');
|
||||
// Timing/upload acceptance runs without the allocation profiler attached.
|
||||
const trace = await page.evaluate(() =>
|
||||
window.__godsEyeView.dataManager.layers
|
||||
.get('transit')
|
||||
.module._measureTransitFramesForTest(8000),
|
||||
);
|
||||
const trace = await page.evaluate(measureTransitFrames, 8000);
|
||||
await page.evaluate(() =>
|
||||
window.__godsEyeView.dataManager.layers
|
||||
.get('transit')
|
||||
@@ -166,11 +162,7 @@ export async function runFleetBudgets({
|
||||
page,
|
||||
`${count} budget visibility before allocation trace`,
|
||||
);
|
||||
const allocationTrace = await page.evaluate(() =>
|
||||
window.__godsEyeView.dataManager.layers
|
||||
.get('transit')
|
||||
.module._measureTransitFramesForTest(6000),
|
||||
);
|
||||
const allocationTrace = await page.evaluate(measureTransitFrames, 6000);
|
||||
const { profile } = await cdp.send('HeapProfiler.stopSampling');
|
||||
const allocations = allocationTotals(profile);
|
||||
const retainedBytes = retained.usedSize - before.usedSize;
|
||||
@@ -361,13 +353,23 @@ export async function runBostonMatrix({
|
||||
const modes = await page.evaluate(() => {
|
||||
const layer =
|
||||
window.__godsEyeView.dataManager.layers.get('transit').module;
|
||||
// The billboards the draw port drew for the markers, by key.
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
const drawn = new Map();
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++)
|
||||
drawn.set(host.get(j)?.id?.id, host.get(j));
|
||||
}
|
||||
return [...layer._transitStateForTest()._vehicles.values()].map(
|
||||
(e) => ({
|
||||
key: e.key,
|
||||
route: e.record.routeId,
|
||||
image: e.marker.image,
|
||||
width: e.marker.width,
|
||||
color: e.marker.color.toCssHexString(),
|
||||
width: drawn.get(e.key)?.width ?? null,
|
||||
color: drawn.get(e.key)?.color.toCssHexString() ?? null,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -418,15 +420,29 @@ export async function runBostonMatrix({
|
||||
window.__godsEyeView.dataManager.layers.get('transit').module;
|
||||
layer._transitPartsForTest().selection.clearSelection();
|
||||
const e = layer._transitStateForTest()._vehicles.get(key);
|
||||
// The billboard the draw port drew for it: the last under its key,
|
||||
// as the fleet sample above reads it (the fleet-models set draws
|
||||
// one under the same key first).
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
let drawn = null;
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++)
|
||||
if (host.get(j)?.id?.id === key) drawn = host.get(j);
|
||||
}
|
||||
return {
|
||||
drawn: Boolean(drawn),
|
||||
image: e.marker.image,
|
||||
width: e.marker.width,
|
||||
color: e.marker.color.toCssHexString(),
|
||||
width: drawn?.width ?? null,
|
||||
color: drawn?.color.toCssHexString() ?? null,
|
||||
};
|
||||
}, target.key);
|
||||
check(
|
||||
`Boston ${background.name}/${look.name}/${target.route}: deselect restores fleet styling`,
|
||||
restored.image === target.image &&
|
||||
restored.drawn &&
|
||||
restored.image === target.image &&
|
||||
restored.width === target.width &&
|
||||
restored.color === target.color,
|
||||
);
|
||||
@@ -727,6 +743,15 @@ export async function runTrailVisibility({
|
||||
bodyUploadMax = 0,
|
||||
frames = 0;
|
||||
const headCpu = [];
|
||||
// The Cesium primitives drawing one of the trail's draw-port sets: one,
|
||||
// or while a rebuild builds, the retiring one and its replacement.
|
||||
const hostsOf = (set) => {
|
||||
const hosts = [];
|
||||
for (let i = 0; set && i < scene.primitives.length; i++)
|
||||
if (scene.primitives.get(i).drawSetId === set.id)
|
||||
hosts.push(scene.primitives.get(i));
|
||||
return hosts;
|
||||
};
|
||||
const wrap = (primitive, kind) => {
|
||||
if (!primitive || wrapped.has(primitive)) return;
|
||||
const update = primitive.update;
|
||||
@@ -767,8 +792,8 @@ export async function runTrailVisibility({
|
||||
const pre = scene.preRender.addEventListener(() => {
|
||||
headBytes = bodyBytes = 0;
|
||||
const trail = parts.trails.diagnostics();
|
||||
wrap(trail?.body, 'body');
|
||||
wrap(trail?.headPrimitive || trail?.head?._polylineCollection, 'head');
|
||||
for (const host of hostsOf(trail?.body)) wrap(host, 'body');
|
||||
for (const host of hostsOf(trail?.headLines)) wrap(host, 'head');
|
||||
});
|
||||
const post = scene.postRender.addEventListener(() => {
|
||||
frames++;
|
||||
@@ -807,6 +832,26 @@ export async function runTrailVisibility({
|
||||
const trail = parts.trails.diagnostics();
|
||||
if (!entry || !trail)
|
||||
return { ...setup, present: 0, reason: 'selection disappeared' };
|
||||
// The Cesium primitives drawing one of the trail's draw-port sets: one,
|
||||
// or while a rebuild builds, the retiring one and its replacement.
|
||||
const hostsOf = (set) => {
|
||||
const hosts = [];
|
||||
for (let i = 0; set && i < scene.primitives.length; i++)
|
||||
if (scene.primitives.get(i).drawSetId === set.id)
|
||||
hosts.push(scene.primitives.get(i));
|
||||
return hosts;
|
||||
};
|
||||
// Each part of a set's primitive, for readiness and height exclusion.
|
||||
const partsOf = (set) => {
|
||||
const out = [];
|
||||
for (const host of hostsOf(set))
|
||||
for (let i = 0; i < host.length; i++) out.push(host.get(i));
|
||||
return out;
|
||||
};
|
||||
// One host (no rebuild under way) whose parts have all built.
|
||||
const drawnReady = (set) =>
|
||||
hostsOf(set).length === 1 &&
|
||||
partsOf(set).every((part) => part.ready !== false);
|
||||
const { setRate } = await import('/src/data/contactPlayback.js');
|
||||
setRate(entry.track, 0, {
|
||||
wallNowMs: Date.now(),
|
||||
@@ -819,8 +864,8 @@ export async function runTrailVisibility({
|
||||
app.tileset?.show !== false &&
|
||||
app.tileset?.tilesLoaded === true &&
|
||||
(scene.globe?.show === false || scene.globe?.tilesLoaded === true) &&
|
||||
trail.body?.ready === true &&
|
||||
(!trail.headPrimitive || trail.headPrimitive.ready === true);
|
||||
drawnReady(trail.body) &&
|
||||
(!trail.headLines?.show || drawnReady(trail.headLines));
|
||||
// Require sustained readiness after freezing playback, before projecting
|
||||
// onto the refined surface. Repeated captures still check pixel stability.
|
||||
const tilesReady = await new Promise((resolve) => {
|
||||
@@ -855,7 +900,18 @@ export async function runTrailVisibility({
|
||||
if (points.length < 2)
|
||||
return { ...setup, present: 0, reason: 'no completed path' };
|
||||
const C = scene.camera.positionCartographic.constructor;
|
||||
const V = entry.marker.position.constructor;
|
||||
// Marker positions are plain records; the camera's eye is a Cartesian3.
|
||||
const V = scene.camera.positionWC.constructor;
|
||||
// The billboard the draw port drew for the marker, seen through.
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
const markerBillboards = [];
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++)
|
||||
if (host.get(j)?.id?.id === entry.key)
|
||||
markerBillboards.push(host.get(j));
|
||||
}
|
||||
const lengths = [0];
|
||||
for (let i = 1; i < points.length; i++)
|
||||
lengths.push(lengths.at(-1) + V.distance(points[i - 1], points[i]));
|
||||
@@ -875,10 +931,11 @@ export async function runTrailVisibility({
|
||||
new V(),
|
||||
);
|
||||
const cart = C.fromCartesian(p);
|
||||
const height = scene.sampleHeight(
|
||||
cart,
|
||||
[entry.marker, trail.body, trail.headPrimitive].filter(Boolean),
|
||||
);
|
||||
const height = scene.sampleHeight(cart, [
|
||||
...markerBillboards,
|
||||
...partsOf(trail.body),
|
||||
...partsOf(trail.headLines),
|
||||
]);
|
||||
if (Number.isFinite(height)) cart.height = height;
|
||||
const surface = C.toCartesian(cart);
|
||||
const q = mul(
|
||||
@@ -943,13 +1000,12 @@ export async function runTrailVisibility({
|
||||
});
|
||||
const bodyShow = trail.body?.show,
|
||||
headShow = trail.head?.show,
|
||||
headPrimitiveShow = trail.headPrimitive?.show,
|
||||
headLinesShow = trail.headLines?.show,
|
||||
backingShow = trail.backing?.show;
|
||||
let showTrail = false;
|
||||
const applyVisibility = () => {
|
||||
if (trail.body) trail.body.show = showTrail && bodyShow;
|
||||
if (trail.headPrimitive)
|
||||
trail.headPrimitive.show = showTrail && headPrimitiveShow;
|
||||
if (trail.headLines) trail.headLines.show = showTrail && headLinesShow;
|
||||
if (trail.head) trail.head.show = showTrail && headShow;
|
||||
if (trail.backing) trail.backing.show = showTrail && backingShow;
|
||||
};
|
||||
@@ -966,13 +1022,13 @@ export async function runTrailVisibility({
|
||||
const current = parts.trails.diagnostics();
|
||||
captureReady &&=
|
||||
ready() &&
|
||||
current?.body === trail.body &&
|
||||
current?.headPrimitive === trail.headPrimitive;
|
||||
current?.rebuilds === trail.rebuilds &&
|
||||
current?.headRebuilds === trail.headRebuilds;
|
||||
}
|
||||
} finally {
|
||||
removeVisibility();
|
||||
if (trail.body) trail.body.show = bodyShow;
|
||||
if (trail.headPrimitive) trail.headPrimitive.show = headPrimitiveShow;
|
||||
if (trail.headLines) trail.headLines.show = headLinesShow;
|
||||
if (trail.head) trail.head.show = headShow;
|
||||
if (trail.backing) trail.backing.show = backingShow;
|
||||
await frame();
|
||||
@@ -994,7 +1050,7 @@ export async function runTrailVisibility({
|
||||
tilesReady: captureReady,
|
||||
elapsedDisplayMs: entry.sample.displayT - setup.startDisplayT,
|
||||
movedMetres: Math.abs(entry.sample.lat - setup.startLat) * 111320,
|
||||
body: trail.body?.constructor.name,
|
||||
body: hostsOf(trail.body)[0]?.constructor.name,
|
||||
headStrategy: trail.headStrategy || 'PolylineCollection',
|
||||
headRebuilds: trail.headRebuilds ?? null,
|
||||
};
|
||||
@@ -1048,3 +1104,24 @@ export async function runTrailVisibility({
|
||||
.selection.clearSelection(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The transit frame probe over the bytes the renderer uploads for the
|
||||
* layer's marker sets (the Cesium renderer's upload probe), in the page.
|
||||
* @param {number} durationMs
|
||||
*/
|
||||
async function measureTransitFrames(durationMs) {
|
||||
const { countDrawSetUploads } =
|
||||
await import('/src/render/cesium/uploadProbe.js');
|
||||
const app = window.__godsEyeView;
|
||||
const layer = app.dataManager.layers.get('transit').module;
|
||||
const uploads = countDrawSetUploads(
|
||||
app.viewer,
|
||||
layer._transitSetIdsForTest(),
|
||||
);
|
||||
try {
|
||||
return await layer._measureTransitFramesForTest(durationMs, uploads);
|
||||
} finally {
|
||||
uploads.stop();
|
||||
}
|
||||
}
|
||||
+48
-20
@@ -98,7 +98,7 @@ const renderingSource = await readFile(
|
||||
);
|
||||
const frameSource = renderingSource
|
||||
.split('function onPreRender()')[1]
|
||||
.split('const occluder')[0];
|
||||
.split('const candidatePosition')[0];
|
||||
check(
|
||||
'frame pass does not scan the fleet or copy the moving set',
|
||||
!/_vehicles\.values|\[\.\.\.state\._moving\]/.test(frameSource),
|
||||
@@ -815,25 +815,38 @@ try {
|
||||
const layer =
|
||||
window.__godsEyeView.dataManager.layers.get('transit').module;
|
||||
const state = layer._transitStateForTest();
|
||||
const entry = state._vehicles.get(key);
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
// The billboard the draw port drew for it, and the set drawing it.
|
||||
const setIds = layer._transitSetIdsForTest();
|
||||
let billboard = null,
|
||||
setId = null;
|
||||
for (let i = 0; !billboard && i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (!setIds.includes(host?.drawSetId)) continue;
|
||||
for (let j = 0; j < host.length; j++)
|
||||
if (host.get(j)?.id?.id === key) {
|
||||
billboard = host.get(j);
|
||||
setId = host.drawSetId;
|
||||
}
|
||||
}
|
||||
const set = layer._transitPartsForTest().rendering.setNameOf(setId);
|
||||
return {
|
||||
selected: state._selectedKey === key,
|
||||
color: entry?.marker.color.toCssColorString(),
|
||||
width: entry?.marker.width,
|
||||
color: billboard?.color.toCssColorString(),
|
||||
width: billboard?.width,
|
||||
pickOwner: (() => {
|
||||
const p = window.__godsEyeView.viewer.scene.pick(
|
||||
entry.marker.computeScreenSpacePosition(
|
||||
window.__godsEyeView.viewer.scene,
|
||||
),
|
||||
);
|
||||
const p = billboard
|
||||
? scene.pick(billboard.computeScreenSpacePosition(scene))
|
||||
: null;
|
||||
return {
|
||||
id: typeof p?.id === 'string' ? p.id : null,
|
||||
primitiveId:
|
||||
typeof p?.primitive?.id === 'string' ? p.primitive.id : null,
|
||||
id: typeof p?.id?.id === 'string' ? p.id.id : null,
|
||||
set: typeof p?.id?.set === 'string' ? p.id.set : null,
|
||||
collection:
|
||||
entry.markerCollection === state._animatedMarkers
|
||||
set === 'moving'
|
||||
? 'animated'
|
||||
: 'stationary',
|
||||
: set === 'still'
|
||||
? 'stationary'
|
||||
: null,
|
||||
};
|
||||
})(),
|
||||
};
|
||||
@@ -1596,7 +1609,8 @@ try {
|
||||
key: entry.key,
|
||||
x,
|
||||
y,
|
||||
pickKey: picked?.id ?? picked?.primitive?.id ?? null,
|
||||
// A draw-port pick carries {set, id, meta}; the vehicle is its id.
|
||||
pickKey: picked?.id?.id ?? picked?.id ?? picked?.primitive?.id ?? null,
|
||||
};
|
||||
});
|
||||
let anchor = null;
|
||||
@@ -1849,19 +1863,33 @@ try {
|
||||
await page.$eval(row, (element) =>
|
||||
element.scrollIntoView({ block: 'center' }),
|
||||
);
|
||||
// The marker sets drawn while on, to look for after disable.
|
||||
const markerSets = await page.evaluate(() =>
|
||||
window.__godsEyeView.dataManager.layers
|
||||
.get('transit')
|
||||
.module._transitSetIdsForTest(),
|
||||
);
|
||||
await page.click(`${row} .data-toggle-btn`);
|
||||
await page.waitForFunction(
|
||||
() => !window.__godsEyeView.dataManager.isEnabled('transit'),
|
||||
{ timeout: 20_000 },
|
||||
);
|
||||
const afterDisable = transitRequests.length;
|
||||
const teardown = await page.evaluate(() => {
|
||||
const teardown = await page.evaluate((setIds) => {
|
||||
const layer = window.__godsEyeView.dataManager.layers.get('transit').module;
|
||||
const state = layer._transitStateForTest();
|
||||
return {
|
||||
vehicles: state._vehicles.size,
|
||||
primitives:
|
||||
(state._markers?.length || 0) + (state._animatedMarkers?.length || 0),
|
||||
// Billboards still drawn in the sets drawn while on.
|
||||
primitives: (() => {
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
let count = 0;
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
const host = scene.primitives.get(i);
|
||||
if (setIds.includes(host?.drawSetId)) count += host.length || 0;
|
||||
}
|
||||
return count;
|
||||
})(),
|
||||
visible: state._visible.size,
|
||||
moving: state._moving.size,
|
||||
detect: state._detectCache,
|
||||
@@ -1873,12 +1901,12 @@ try {
|
||||
],
|
||||
trailPending: layer._transitPartsForTest().trails.requestDiagnostics()
|
||||
.pending,
|
||||
shown: state._markers ? state._markers.show : null,
|
||||
shown: state._markersShown ?? null,
|
||||
inFlight: state._inFlight.size,
|
||||
activeFeeds: state._activeFeeds.size,
|
||||
holds: window.__godsEyeView.getRenderGovernorDiagnostics().holds,
|
||||
};
|
||||
});
|
||||
}, markerSets);
|
||||
check(
|
||||
'disable leaves no vehicles and no point primitives',
|
||||
teardown.vehicles === 0 &&
|
||||
|
||||
@@ -169,7 +169,7 @@ try {
|
||||
result.bloom.intensityPct === 98 &&
|
||||
snapshot.bloom.intensity === 98 &&
|
||||
manager._visualEffects.bloomIntensity === 98 &&
|
||||
manager._bloomStage.enabled
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.enabled
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -183,7 +183,11 @@ try {
|
||||
result.sharpen.intensityPct === 61 &&
|
||||
manager.getVisualState().sharpen.intensity === 61 &&
|
||||
manager._visualEffects.sharpenIntensity === 0.61 &&
|
||||
Math.abs(manager._sharpenStage.uniforms.amount - 1.32) < 1e-9
|
||||
Math.abs(
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.getStageByName(
|
||||
'effects_sharpen',
|
||||
).uniforms.amount - 1.32,
|
||||
) < 1e-9
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -199,9 +203,10 @@ try {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
const effects = manager._visualEffects;
|
||||
manager.setStyle('retro');
|
||||
const owned = [...Object.values(effects.stages), effects.sharpenStage];
|
||||
const collection = manager.viewer.scene.postProcessStages;
|
||||
const previousBloom = effects.previousBloom;
|
||||
const collection = window.__godsEyeView.viewer.scene.postProcessStages;
|
||||
const owned = Object.keys(effects.stages).map((name) =>
|
||||
collection.getStageByName(`effects_style_${name}`),
|
||||
);
|
||||
const pending = manager.dispose();
|
||||
const stoppedBeforeAwait =
|
||||
effects.stopped &&
|
||||
@@ -210,12 +215,15 @@ try {
|
||||
await pending;
|
||||
return {
|
||||
stoppedBeforeAwait,
|
||||
removed: owned.every((stage) => !collection.contains(stage)),
|
||||
restored:
|
||||
effects.bloomStage.enabled === previousBloom.enabled &&
|
||||
Object.entries(previousBloom.uniforms).every(
|
||||
([name, value]) => effects.bloomStage.uniforms[name] === value,
|
||||
removed:
|
||||
owned.every(Boolean) &&
|
||||
Object.keys(effects.stages).every(
|
||||
(name) => !collection.getStageByName(`effects_style_${name}`),
|
||||
),
|
||||
// The renderer gives the scene's bloom back when it goes.
|
||||
restored:
|
||||
!collection.bloom.enabled &&
|
||||
!collection.getStageByName('effects_sharpen')?.enabled,
|
||||
};
|
||||
});
|
||||
check(
|
||||
@@ -223,7 +231,7 @@ try {
|
||||
teardown.stoppedBeforeAwait,
|
||||
);
|
||||
check(
|
||||
'UI teardown removes owned stages and restores borrowed bloom',
|
||||
'UI teardown removes its styles and turns bloom and sharpen off',
|
||||
teardown.removed && teardown.restored,
|
||||
);
|
||||
check(
|
||||
|
||||
@@ -150,7 +150,9 @@ try {
|
||||
manager._bloomSlider.focus();
|
||||
return {
|
||||
value: Number(manager._bloomSlider.value),
|
||||
contrast: manager._bloomStage.uniforms.contrast,
|
||||
contrast:
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast,
|
||||
};
|
||||
});
|
||||
await page.keyboard.press('ArrowRight');
|
||||
@@ -160,7 +162,8 @@ try {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
return (
|
||||
Number(manager._bloomSlider.value) > before.value &&
|
||||
manager._bloomStage.uniforms.contrast < before.contrast
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast < before.contrast
|
||||
);
|
||||
}, displayBefore),
|
||||
);
|
||||
@@ -267,13 +270,16 @@ try {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
manager._displayBindings._detachDisplayControls();
|
||||
const before = manager.bloomEnabled;
|
||||
const contrast = manager._bloomStage.uniforms.contrast;
|
||||
const contrast =
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast;
|
||||
manager._bloomBtn.click();
|
||||
manager._bloomSlider.value = '15';
|
||||
manager._bloomSlider.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
return (
|
||||
manager.bloomEnabled === before &&
|
||||
manager._bloomStage.uniforms.contrast === contrast
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast === contrast
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -36,7 +36,8 @@ try {
|
||||
);
|
||||
const renderer = await page.evaluate(async () => {
|
||||
const C = await import('/node_modules/cesium/Build/Cesium/index.js');
|
||||
const { maxPitchForHeight } = await import('/src/app/zoomOutGuard.js');
|
||||
const { maxPitchForHeight } =
|
||||
await import('/src/render/cesium/zoomOutGuard.js');
|
||||
const { readCameraTargetFrame } =
|
||||
await import('/src/ui/cameraOrientationControls.js');
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
@@ -86,7 +87,7 @@ try {
|
||||
};
|
||||
viewer.camera.setView = (options) => {
|
||||
// Cesium itself also calls setView while processing touch movement.
|
||||
if (new Error().stack.includes('/src/app/zoomOutGuard.js'))
|
||||
if (new Error().stack.includes('/src/render/cesium/zoomOutGuard.js'))
|
||||
qa.guardWrites++;
|
||||
return original(options);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
// Writes the reference camera traces the conformance suite compares a
|
||||
// renderer against: src/render/conformance/goldens/camera.json. Run it after
|
||||
// a Cesium upgrade or a change to the camera scripts, and review the diff.
|
||||
//
|
||||
// node scripts/record-camera-goldens.mjs [--check]
|
||||
//
|
||||
// With --check it writes nothing and exits 1 when the file is out of date.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { recordCameraGoldens } from '../src/render/cesium/cameraGoldens.js';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const OUT = path.join(ROOT, 'src/render/conformance/goldens/camera.json');
|
||||
|
||||
const text = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`;
|
||||
if (process.argv.includes('--check')) {
|
||||
const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8') : '';
|
||||
if (current !== text) {
|
||||
console.error(`${path.relative(ROOT, OUT)} is out of date`);
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
||||
fs.writeFileSync(OUT, text);
|
||||
console.log(`wrote ${path.relative(ROOT, OUT)}`);
|
||||
}
|
||||
+344
-199
@@ -33,7 +33,8 @@
|
||||
* moves the camera — it stays in the follow band).
|
||||
* 3. NO CROSS-LAYER — tracking military then commercial (and vice versa)
|
||||
* ORPHAN clears the FIRST layer (its getTrackedInfo()===null),
|
||||
* via the per-layer viewer.trackedEntityChanged listener.
|
||||
* via each layer's follow-changed listener (the follow
|
||||
* service, data/followed.js: onFollowChanged).
|
||||
* 4. INIT CLEAN — app loads, all 12 layers present, no console errors,
|
||||
* [Detection] Initialized + [TrackedReadout] Initialized.
|
||||
*
|
||||
@@ -44,8 +45,8 @@
|
||||
* M3. AGE-OUT RELEASE — when the tracked plane's fixes stop arriving
|
||||
* it stays tracked (STALE, then SIGNAL LOST) until
|
||||
* 10 min after its newest fix; then tracking clears
|
||||
* and the camera is RELEASED IN PLACE: viewer.trackedEntity
|
||||
* undefined, NO jump (owner decision 2026-07-02 —
|
||||
* and the camera is RELEASED IN PLACE: the camera
|
||||
* follows nothing (data/followed.js), NO jump (owner decision 2026-07-02 —
|
||||
* the old ~80 km overview flyTo is gone).
|
||||
*
|
||||
* And the landing-ghost polish (2026-07-02): a LOW+SLOW (landed) plane that
|
||||
@@ -74,11 +75,16 @@
|
||||
* the TRACKED grounded plane gets the standalone tracked model too (the
|
||||
* owner's "tracked SWA143 at 0 kts showed a 2D billboard" case).
|
||||
*
|
||||
* And arrival-rotation freshness (2026-07-03 ground-polish): camera.moveEnd
|
||||
* forces a full rotation pass on the next frame (fly-to settles the
|
||||
* pose-signature gate can eat), and a billboard flipping INTO view while the
|
||||
* camera idles re-aims the same tick instead of wearing a stale nose for up
|
||||
* to ROTATION_REFRESH_MS. Both layers.
|
||||
* And arrival-rotation freshness (2026-07-03 ground-polish): the nose is right
|
||||
* on the first settled frame after a camera move and on the first frame a
|
||||
* hidden contact is shown again. Both layers. (The CPU rotation passes that
|
||||
* once guaranteed it are gone: the icon sets turn every icon along its drawn
|
||||
* course on the GPU each frame, so the group reads the drawn rows.)
|
||||
*
|
||||
* The probes read what the app draws through its own seams: what the camera
|
||||
* follows through the follow service (data/followed.js), icons from the draw
|
||||
* port's icon sets as the renderer holds them, models by their `{set, id}`
|
||||
* pick ids.
|
||||
*
|
||||
* Run: npm run test:track (assumes dev server already up on :4173)
|
||||
* node scripts/track-regression.mjs
|
||||
@@ -272,6 +278,98 @@ async function main() {
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.evaluateOnNewDocument((base) => { window.__gevQaSourceBase = base; }, SOURCE_BASE);
|
||||
// What the camera follows, read through the app's follow service
|
||||
// (data/followed.js) rather than Cesium's `trackedEntity`: the follow
|
||||
// camera runs through the renderer's camera port, whose Cesium adapter
|
||||
// tracks a hidden helper entity, and the tracked aircraft is no longer an
|
||||
// entity at all. `__qaFollowed()` is null until the app is up (and the
|
||||
// module loaded), so every wait that reads it simply keeps polling.
|
||||
await page.evaluateOnNewDocument(() => {
|
||||
window.__qaFollowed = () => {
|
||||
// A probe that cannot read the follow service must not read as
|
||||
// "follows nothing".
|
||||
if (window.__qaFollowedError) throw new Error(`followed.js: ${window.__qaFollowedError}`);
|
||||
return window.__qaFollowedOf?.(window.__godsEyeView?.viewer) ?? null;
|
||||
};
|
||||
const timer = setInterval(() => {
|
||||
if (!window.__godsEyeView?.viewer) return;
|
||||
clearInterval(timer);
|
||||
import(`${window.__gevQaSourceBase || '/src'}/data/followed.js`)
|
||||
.then((module) => { window.__qaFollowedOf = module.followedOf; })
|
||||
.catch((error) => { window.__qaFollowedError = String(error?.message || error); });
|
||||
}, 100);
|
||||
// A contact's id from a drawn model's pick id: the draw port's models
|
||||
// carry `{set, id}`; older builds stamped the bare id.
|
||||
window.__qaModelIcao = (model) => {
|
||||
const id = model?.id;
|
||||
if (id && typeof id === 'object') return id.id == null ? null : String(id.id);
|
||||
return id == null ? null : String(id);
|
||||
};
|
||||
// A contact's FLEET icon as the renderer draws it, shaped like the
|
||||
// billboard the probes below were written against: `show`, `scale`,
|
||||
// `color` (the row's colour with its alpha column applied; focus and
|
||||
// limb recession, which the shader also folds in, are not),
|
||||
// `disableDepthTestDistance` and `position` (where the last frame drew
|
||||
// it). The draw port's icon sets draw on the GPU (one IconSetPrimitive
|
||||
// per set, rows keyed by item id; before the draw port, one a layer
|
||||
// drew itself); a set off the GPU draws Cesium
|
||||
// billboards whose pick id is `{set, id}`. The tracked icon's own set
|
||||
// (`<layer>-tracked-icon:<n>`) is left out: the fleet icon is what these
|
||||
// probes always read.
|
||||
window.__qaFindIcon = (wanted) => {
|
||||
const scene = window.__godsEyeView?.viewer?.scene;
|
||||
if (!scene) return null;
|
||||
const trackedSet = (setId) => typeof setId === 'string' && setId.includes('-tracked-icon:');
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p;
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.set && typeof p.set.row === 'function' && typeof p.set.has === 'function') {
|
||||
if (!p.set.has(wanted)) continue;
|
||||
// A primitive a layer drew itself (before the draw port) names
|
||||
// no set.
|
||||
const setId = typeof p._pickObject === 'function'
|
||||
? p._pickObject(wanted, p.set, p)?.id?.set ?? null
|
||||
: null;
|
||||
if (trackedSet(setId)) continue;
|
||||
const set = p.set;
|
||||
const row = set.row(wanted);
|
||||
const color = set.color(row);
|
||||
color.alpha *= set.alpha(row);
|
||||
// (A set without the column draws over depth by default.)
|
||||
const depth = typeof set.depthTestDistance === 'function'
|
||||
? set.depthTestDistance(row)
|
||||
: Number.POSITIVE_INFINITY;
|
||||
found = {
|
||||
id: wanted,
|
||||
setId,
|
||||
show: set.shown(row),
|
||||
scale: set.scale(row),
|
||||
color,
|
||||
disableDepthTestDistance: depth >= 1e30 ? Number.POSITIVE_INFINITY : depth,
|
||||
position: set.position(row, p._tau),
|
||||
// Degrees clockwise from north: the course the last frame
|
||||
// turned the icon along (its rotation is derived from it on
|
||||
// the GPU each frame).
|
||||
course: set.course(row, p._tau),
|
||||
// Whether the row turns along that course at all (ICON_ROTATES
|
||||
// in data/iconSet.js); one that does not is drawn upright.
|
||||
rotates: (set.flags(row) & 2) !== 0,
|
||||
};
|
||||
} else if (p.image !== undefined && p.alignedAxis !== undefined) {
|
||||
const id = p.id && typeof p.id === 'object' ? p.id : { id: p.id };
|
||||
if (id.id === wanted && !trackedSet(id.set)) found = p;
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(scene.primitives);
|
||||
return found;
|
||||
};
|
||||
});
|
||||
await page.setViewport({ width: 1280, height: 800 });
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
@@ -725,7 +823,7 @@ async function main() {
|
||||
const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.();
|
||||
return manager?.isEnabled?.('flights')
|
||||
&& tracked?.icao24 === 'aaa001'
|
||||
&& window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001';
|
||||
&& window.__qaFollowed()?.key === 'flights:aaa001';
|
||||
},
|
||||
{ timeout: 30000, polling: 100 },
|
||||
);
|
||||
@@ -736,7 +834,7 @@ async function main() {
|
||||
flightsEnabled: manager.isEnabled('flights'),
|
||||
trackedId: flights.getTrackedInfo()?.icao24 || null,
|
||||
durableId: flights.getParams()?.selectedFlightsTrackingId || null,
|
||||
viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null,
|
||||
viewerTrackedId: window.__qaFollowed()?.key || null,
|
||||
};
|
||||
});
|
||||
record(
|
||||
@@ -766,7 +864,7 @@ async function main() {
|
||||
const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.();
|
||||
return manager?.isEnabled?.('flights')
|
||||
&& tracked?.icao24 === 'aaa001'
|
||||
&& window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001';
|
||||
&& window.__qaFollowed()?.key === 'flights:aaa001';
|
||||
},
|
||||
{ timeout: 30000, polling: 100 },
|
||||
);
|
||||
@@ -777,7 +875,7 @@ async function main() {
|
||||
flightsEnabled: manager.isEnabled('flights'),
|
||||
trackedId: flights.getTrackedInfo()?.icao24 || null,
|
||||
durableId: flights.getParams()?.selectedFlightsTrackingId || null,
|
||||
viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null,
|
||||
viewerTrackedId: window.__qaFollowed()?.key || null,
|
||||
};
|
||||
});
|
||||
record(
|
||||
@@ -839,7 +937,7 @@ async function main() {
|
||||
const latchedShare = await evalPage(() => ({
|
||||
tracked: window.__godsEyeView.dataManager.layers
|
||||
.get('flights').module.getTrackedInfo()?.icao24 || null,
|
||||
viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null,
|
||||
viewerTrackedId: window.__qaFollowed()?.key || null,
|
||||
}));
|
||||
record(
|
||||
'share-v2: the pending subject latches on when it arrives on a later poll',
|
||||
@@ -1353,8 +1451,8 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
// NOTE: we do NOT manually reposition the camera. Tracking sets
|
||||
// viewer.trackedEntity + a calibrated viewFrom, so the follow camera lands
|
||||
// NOTE: we do NOT manually reposition the camera. Tracking follows the
|
||||
// plane with a calibrated viewFrom, so the follow camera lands
|
||||
// in the few-km band (altitude*1.1+2500, clamped 3–30 km) — far below the
|
||||
// MODEL_ALT_CEIL_M = 800 km ceiling, so _modelRegimeActive() is true and the
|
||||
// standalone tracked model renders. That's the exact path the invariants
|
||||
@@ -1399,12 +1497,12 @@ async function main() {
|
||||
// report the neighbor's id even though the correct tracked model is up.
|
||||
const trackedInfo = fl.getTrackedInfo();
|
||||
const exactPickModel = trackedInfo
|
||||
? pool.find((model) => String(model.id) === trackedInfo.icao24)
|
||||
? pool.find((model) => window.__qaModelIcao(model) === trackedInfo.icao24)
|
||||
: null;
|
||||
if (exactPickModel) return exactPickModel;
|
||||
const ent = window.__godsEyeView.viewer.trackedEntity;
|
||||
const followed = window.__qaFollowed();
|
||||
let tracked = null;
|
||||
if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition();
|
||||
if (typeof followed?.displayPosition === 'function') tracked = followed.displayPosition();
|
||||
if (!tracked) return pool[0];
|
||||
let best = null, bestD = Infinity;
|
||||
for (const m of pool) {
|
||||
@@ -1422,7 +1520,7 @@ async function main() {
|
||||
};
|
||||
});
|
||||
|
||||
// Track a synthetic commercial plane. Tracking sets viewer.trackedEntity +
|
||||
// Track a synthetic commercial plane. Tracking follows it with a
|
||||
// viewFrom, so the follow camera lands in the few-km band and the standalone
|
||||
// 3D model renders (model regime active below the 800 km ceiling).
|
||||
const trackedIcao = SYNTH.flights[0].icao;
|
||||
@@ -1437,7 +1535,7 @@ async function main() {
|
||||
const ti = fl.getTrackedInfo();
|
||||
if (!ti || ti.icao24 !== icao) return false;
|
||||
const found = window.__findTrackedModel ? window.__findTrackedModel() : null;
|
||||
return !!(found && found.ready && found.show && String(found.id) === icao);
|
||||
return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao);
|
||||
}, { timeout: 60000, polling: 250 }, trackedIcao).then(() => true).catch(() => false);
|
||||
record('3D: tracked commercial model becomes ready through the DISPLAY toggle', modelUp,
|
||||
modelUp ? `ready+shown id=${trackedIcao}` : 'tracked product model never became ready+shown');
|
||||
@@ -1450,8 +1548,8 @@ async function main() {
|
||||
jitterResult = await sampleFrames(page, 30, (icao) => {
|
||||
const dm = window.__godsEyeView.dataManager;
|
||||
const fl = dm.layers.get('flights').module;
|
||||
const ent = window.__godsEyeView.viewer.trackedEntity;
|
||||
const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null;
|
||||
const followed = window.__qaFollowed();
|
||||
const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null;
|
||||
const dets = fl.getDetectableObjects({ maxCount: 1000 });
|
||||
const me = dets.find((d) => d.id === icao || d.id === (fl.getTrackedInfo() && fl.getTrackedInfo().callsign));
|
||||
if (!disp || !me || !me.position) return null;
|
||||
@@ -1700,7 +1798,7 @@ async function main() {
|
||||
mil.trackById(hex);
|
||||
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
const milTrackedBefore = !!mil.getTrackedInfo();
|
||||
fl.trackById(icao); // tracking commercial flips viewer.trackedEntity → military listener fires
|
||||
fl.trackById(icao); // tracking commercial changes what the camera follows → military listener fires
|
||||
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
return {
|
||||
milTrackedBefore,
|
||||
@@ -1755,16 +1853,22 @@ async function main() {
|
||||
const ti = fl.getTrackedInfo();
|
||||
if (!ti || ti.icao24 !== icao) return false;
|
||||
const found = window.__findTrackedModel ? window.__findTrackedModel() : null;
|
||||
return !!(found && found.ready && found.show && String(found.id) === icao);
|
||||
return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao);
|
||||
}, { timeout: 60000, polling: 250 }, h1Icao).then(() => true).catch(() => false);
|
||||
|
||||
if (h1ModelUp) {
|
||||
const modelPickId = await evalPage(() => {
|
||||
const m = window.__findTrackedModel();
|
||||
return m && m.id !== undefined && m.id !== null ? String(m.id) : null;
|
||||
if (!m || m.id === undefined || m.id === null) return null;
|
||||
// The draw port's pick id is `{set, id}`: the click resolver keys on
|
||||
// both, so the set must be this layer's tracked model set.
|
||||
if (typeof m.id === 'object') return { set: String(m.id.set), id: String(m.id.id) };
|
||||
return { set: null, id: String(m.id) };
|
||||
});
|
||||
record('H1: tracked standalone model exposes its pick id', modelPickId === h1Icao,
|
||||
`model.id=${JSON.stringify(modelPickId)} (want "${h1Icao}")`);
|
||||
record('H1: tracked standalone model exposes its pick id',
|
||||
modelPickId?.id === h1Icao
|
||||
&& (modelPickId.set === null || modelPickId.set.startsWith('flights-tracked-model:')),
|
||||
`model.id=${JSON.stringify(modelPickId)} (want id "${h1Icao}" in the flights tracked-model set)`);
|
||||
} else if (!glbBackendCapable) {
|
||||
skip('H1: tracked standalone model exposes its pick id',
|
||||
`independent GLB control unavailable (${glbControlDetail})`);
|
||||
@@ -1783,15 +1887,21 @@ async function main() {
|
||||
const fl = window.__godsEyeView.dataManager.layers.get('flights').module;
|
||||
const ti = fl.getTrackedInfo();
|
||||
if (!ti) return null;
|
||||
const ent = v.trackedEntity;
|
||||
const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null;
|
||||
const followed = window.__qaFollowed();
|
||||
const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null;
|
||||
const pos = disp || ti.position;
|
||||
if (!pos) return null;
|
||||
const center = v.scene.cartesianToCanvasCoordinates(pos);
|
||||
if (!center) return null;
|
||||
// The tracked plane is drawn by the layer's own tracked icon and
|
||||
// tracked model sets; a pick on either names `{set, id}`.
|
||||
const isTrackedPick = (picked) => {
|
||||
if (!picked) return null;
|
||||
if (picked.id === ent) return 'entity';
|
||||
const hit = picked.id && typeof picked.id === 'object' ? picked.id : null;
|
||||
if (hit && String(hit.id) === ti.icao24 && typeof hit.set === 'string') {
|
||||
if (hit.set.startsWith('flights-tracked-icon:')) return 'tracked-icon';
|
||||
if (hit.set.startsWith('flights-tracked-model:')) return 'tracked-model';
|
||||
}
|
||||
const raw = typeof picked.id === 'string' ? picked.id : (picked.primitive && picked.primitive.id);
|
||||
return raw === ti.icao24 ? 'icao-pick' : null;
|
||||
};
|
||||
@@ -1849,7 +1959,7 @@ async function main() {
|
||||
}, 45);
|
||||
const h1StillTracking = await evalPage((icao) => {
|
||||
const ti = window.__godsEyeView.dataManager.layers.get('flights').module.getTrackedInfo();
|
||||
return !!(ti && ti.icao24 === icao) && !!window.__godsEyeView.viewer.trackedEntity;
|
||||
return !!(ti && ti.icao24 === icao) && !!window.__qaFollowed();
|
||||
}, h1Icao);
|
||||
record('H1: click on tracked plane keeps tracking (no deselect)', h1StillTracking,
|
||||
`picked via ${h1ClickPoint.via}; still tracking=${h1StillTracking}`);
|
||||
@@ -1862,8 +1972,8 @@ async function main() {
|
||||
// REGRESSION M3 (rewritten 2026-07-02 — deliberate behavior change):
|
||||
// when the TRACKED plane ages out (10 min after its newest fix, past the
|
||||
// 3 missed polls that remove an untracked plane), tracking must clear
|
||||
// and the camera must be RELEASED IN PLACE — viewer.trackedEntity
|
||||
// undefined and NO jump (the old contract flew an ~80 km overview; the
|
||||
// and the camera must be RELEASED IN PLACE — following nothing
|
||||
// and NO jump (the old contract flew an ~80 km overview; the
|
||||
// owner field-ruled that wrong: "it randomly zooms way up and loses my
|
||||
// context"). The M3 ordering fix stays: tracking is cleared BEFORE the
|
||||
// removal loop deletes the plane's state, so we never sit mid-follow
|
||||
@@ -1914,7 +2024,7 @@ async function main() {
|
||||
trackedThroughMisses,
|
||||
atAgeOut,
|
||||
stillTrackedAfter: !!fl.getTrackedInfo(),
|
||||
viewerStillTracking: !!v.trackedEntity,
|
||||
viewerStillTracking: !!window.__qaFollowed(),
|
||||
};
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
@@ -1927,7 +2037,7 @@ async function main() {
|
||||
record('M3: tracking cleared after the tracked plane ages out (getTrackedInfo null)',
|
||||
m3.beforeTracking && !m3.stillTrackedAfter,
|
||||
`before=${m3.beforeTracking} trackedAfter=${m3.stillTrackedAfter}`);
|
||||
record('M3: camera released after age-out (viewer.trackedEntity undefined)',
|
||||
record('M3: camera released after age-out (the camera follows nothing)',
|
||||
!m3.viewerStillTracking,
|
||||
`viewerTracked=${m3.viewerStillTracking}`);
|
||||
|
||||
@@ -2052,16 +2162,17 @@ async function main() {
|
||||
const v = window.__godsEyeView.viewer;
|
||||
const fl = window.__godsEyeView.dataManager.layers.get('flights').module;
|
||||
const labelText = () => {
|
||||
const ent = v.trackedEntity;
|
||||
const ent = window.__qaFollowed();
|
||||
if (!ent) return null;
|
||||
// Post overlay-unification the tracked text lives in the host
|
||||
// presentation model (entities are asserted native-label-free);
|
||||
// the native read stays as a fallback so this probe still fails
|
||||
// loudly if BOTH surfaces are ever absent.
|
||||
const model = ent.gevLabelModel;
|
||||
const model = ent.labelModel;
|
||||
if (model) return [model.title, ...(model.details || [])].filter(Boolean).join('\n');
|
||||
if (!ent.label || !ent.label.text) return null;
|
||||
const t = ent.label.text;
|
||||
const label = ent.entity?.label;
|
||||
if (!label || !label.text) return null;
|
||||
const t = label.text;
|
||||
return typeof t === 'string' ? t : (t.getValue ? String(t.getValue(v.clock.currentTime)) : null);
|
||||
};
|
||||
// Track a cruise plane that IS in the feed (aaa003: 8700 m, 250 m/s —
|
||||
@@ -2106,19 +2217,7 @@ async function main() {
|
||||
const fl = dm.layers.get('flights').module;
|
||||
const mil = dm.layers.get('military').module;
|
||||
const findBB = (id) => {
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p;
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
return window.__qaFindIcon(id);
|
||||
};
|
||||
const snap = (id) => {
|
||||
const bb = findBB(id);
|
||||
@@ -2393,19 +2492,7 @@ async function main() {
|
||||
await fl.update(v);
|
||||
await mil.update(v);
|
||||
const findBB = (id) => {
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p;
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
return window.__qaFindIcon(id);
|
||||
};
|
||||
const flBB = findBB('aaa077');
|
||||
const milBB = findBB('bbb177');
|
||||
@@ -2440,7 +2527,7 @@ async function main() {
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.modelMatrix && typeof p.ready !== 'undefined' && p.id === id) found = p;
|
||||
if (p.modelMatrix && typeof p.ready !== 'undefined' && window.__qaModelIcao(p) === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
@@ -2469,19 +2556,7 @@ async function main() {
|
||||
const g3dState = await evalPage(() => {
|
||||
const v = window.__godsEyeView.viewer;
|
||||
const findBB = (id) => {
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p;
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
return window.__qaFindIcon(id);
|
||||
};
|
||||
const modelRadius = (id) => {
|
||||
const m = window.__g3dFindModel(id);
|
||||
@@ -2697,7 +2772,7 @@ async function main() {
|
||||
}
|
||||
|
||||
// WELD (tracked): the tracked CARD anchors to the model you can see.
|
||||
// `gevVisualPosition` is a SEPARATE accessor from `gevDisplayPosition` on
|
||||
// the record's `visualPosition` is a SEPARATE accessor from its `displayPosition` on
|
||||
// purpose — the latter carries the follow-camera anti-jitter contract and
|
||||
// must keep returning the cached dead-reckoned value the camera settled
|
||||
// on. So this asserts both halves: the visual accessor is welded to the
|
||||
@@ -2705,7 +2780,7 @@ async function main() {
|
||||
// dead-reckoned position rather than having been quietly repurposed.
|
||||
if (g3dTrackedUp) {
|
||||
const trackedWeld = await evalPage(() => {
|
||||
const ent = window.__godsEyeView.viewer.trackedEntity;
|
||||
const ent = window.__qaFollowed();
|
||||
const m = window.__g3dFindModel('aaa077');
|
||||
if (!m) return { error: 'no tracked model' };
|
||||
const matrix = m.modelMatrix;
|
||||
@@ -2724,10 +2799,10 @@ async function main() {
|
||||
const at = (p) => (p ? Math.hypot(
|
||||
p.x - anchor.x, p.y - anchor.y, p.z - anchor.z,
|
||||
) : null);
|
||||
const visual = typeof ent?.gevVisualPosition === 'function' ? ent.gevVisualPosition() : null;
|
||||
const display = typeof ent?.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null;
|
||||
const visual = typeof ent?.visualPosition === 'function' ? ent?.visualPosition() : null;
|
||||
const display = typeof ent?.displayPosition === 'function' ? ent?.displayPosition() : null;
|
||||
return {
|
||||
hasVisualAccessor: typeof ent?.gevVisualPosition === 'function',
|
||||
hasVisualAccessor: typeof ent?.visualPosition === 'function',
|
||||
visualDelta: at(visual),
|
||||
displayDelta: at(display),
|
||||
};
|
||||
@@ -2743,7 +2818,7 @@ async function main() {
|
||||
// anti-jitter accessor has been repurposed and the follow camera is at
|
||||
// risk. Skipped (not failed) when the DR cache is momentarily invalid.
|
||||
const displayDelta = trackedWeld.displayDelta;
|
||||
record('weld: gevDisplayPosition still reports the dead-reckoned position (anti-jitter intact)',
|
||||
record('weld: the record displayPosition still reports the dead-reckoned position (anti-jitter intact)',
|
||||
!Number.isFinite(displayDelta) || displayDelta > ACCESSOR_SEPARATION_EPSILON_M,
|
||||
Number.isFinite(displayDelta)
|
||||
? `displayΔ=${displayDelta.toFixed(3)} m (must stay > ${ACCESSOR_SEPARATION_EPSILON_M} m — the ground-snap split)`
|
||||
@@ -2832,6 +2907,21 @@ async function main() {
|
||||
// CHANGE 4 (2026-07-03): arrival rotation freshness. Field test: "planes
|
||||
// look weird when you first come to them — rotations are weird". Two
|
||||
// repaired holes, both layers:
|
||||
//
|
||||
// SINCE THE GPU ICON SETS (2c4c66c71) there is no CPU rotation pass to
|
||||
// tamper with or repair: each frame the shader turns every icon along the
|
||||
// course its row's motion segment carries at that frame's time. The
|
||||
// invariant — the nose is right on the first settled frame after a
|
||||
// camera move and on the first frame a hidden contact is shown again —
|
||||
// is now observed on the drawn rows: the on-screen nose the drawn course
|
||||
// projects to, against the one the plane's feed course projects to, at
|
||||
// the same position, on exactly those two frames (same 10° bound, same
|
||||
// per-frame budgets). That the shader turns an icon to the screen angle
|
||||
// its course projects to is the renderer's own contract, which the
|
||||
// renderer conformance reference scenes draw (course-rotated arrows,
|
||||
// top and tilted views); a CPU readback cannot see the GPU's rotation. The reveal hides and re-shows the row through the
|
||||
// layer's own icon book, the only thing that hides a fleet icon.
|
||||
// The two holes the passes repaired, for the record:
|
||||
// (a) SETTLE PASS — camera.moveEnd forces a full rotation pass on the
|
||||
// next frame (the pose-signature gate can eat a fly-to's settle:
|
||||
// the final easing frames land inside one 10 m/0.06° quantization
|
||||
@@ -2840,39 +2930,25 @@ async function main() {
|
||||
// idles gets its rotation refreshed the same tick (it used to
|
||||
// reappear wearing its stale/creation-north nose for up to 1 s).
|
||||
// Staged deterministically: park the camera nadir over the synthetic
|
||||
// cluster, let rotations settle, TAMPER a billboard's rotation, then
|
||||
// trigger each path with the camera idle. The fleet runs every 80 ms,
|
||||
// independently of rendered FPS. Observe the first completed settle frame
|
||||
// within 500 ms of forcing moveEnd and the first reveal frame within
|
||||
// 500 ms of that settle frame: each budget sits inside the 1 s idle
|
||||
// rotation refresh that could otherwise repair an incorrect first reveal,
|
||||
// and a ~300 ms headless SwiftShader frame fits inside each of them.
|
||||
// cluster, let it settle, then trigger each path with the camera idle.
|
||||
// Observe the first completed settle frame within 500 ms of forcing
|
||||
// moveEnd and the first reveal frame within 500 ms of that settle frame
|
||||
// (the budgets once sat inside the 1 s idle rotation refresh; they are
|
||||
// kept as they were).
|
||||
// ============================================================
|
||||
console.log('\nChange 4 — arrival rotation: moveEnd settle pass + horizon-reveal pass');
|
||||
console.log('\nChange 4 — arrival rotation: the drawn nose on the settle frame and the first reveal');
|
||||
const arrival = await evalPage(async () => {
|
||||
const v = window.__godsEyeView.viewer;
|
||||
const dm = window.__godsEyeView.dataManager;
|
||||
const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/data/iconOrientation.js`);
|
||||
const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/render/cesium/iconOrientation.js`);
|
||||
const { observeArrivalRotationWithRetry } = await import(`${window.__gevQaSourceBase || '/src'}/tooling/trackArrivalObservation.mjs`);
|
||||
// 3D models OFF for this phase: a model-handed-off billboard is hidden
|
||||
// and skips rotation updates entirely — the probes need live billboards
|
||||
// (this is also the app's default state the field report came from).
|
||||
// 3D models OFF for this phase: a model-handed-off icon is hidden, and
|
||||
// the probes need shown icons (this is also the app's default state the
|
||||
// field report came from).
|
||||
dm.layers.get('flights').module.setParams({ models3d: false });
|
||||
dm.layers.get('military').module.setParams({ models3d: false });
|
||||
const findBB = (id) => {
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p;
|
||||
try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
return window.__qaFindIcon(id);
|
||||
};
|
||||
const nextFrames = (n) => new Promise((res) => {
|
||||
let count = 0;
|
||||
@@ -2896,8 +2972,8 @@ async function main() {
|
||||
});
|
||||
// Park the camera straight above the flights cluster (lift a live
|
||||
// billboard's position radially — no Cesium global needed in-page) so
|
||||
// every probe plane projects on-screen, then let rotations settle at
|
||||
// the new pose (the setView pose change forces a pass on the next tick).
|
||||
// every probe plane projects on-screen, then let a few frames draw at
|
||||
// the new pose.
|
||||
// aaa002 — aaa001 was evicted for good by the M3 age-out phase.
|
||||
const anchor = findBB('aaa002');
|
||||
if (!anchor) return { error: 'anchor aaa002 missing' };
|
||||
@@ -2911,62 +2987,99 @@ async function main() {
|
||||
});
|
||||
await nextFrames(3);
|
||||
const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b)));
|
||||
const probe = async (id, course) => {
|
||||
const probe = async (layer, id, course) => {
|
||||
const bb = findBB(id);
|
||||
if (!bb || !bb.show) return { error: `${id} missing/hidden` };
|
||||
const r0 = bb.rotation; // settled tamper origin; correctness uses a fresh projection below
|
||||
if (!Number.isFinite(bb.course) && !Number.isFinite(bb.rotation)) {
|
||||
return { error: `${id} has no drawn course or rotation` };
|
||||
}
|
||||
const setIconShown = layer.testing?._setIconForTest;
|
||||
if (typeof setIconShown !== 'function') return { error: `${id}: the layer has no icon test seam` };
|
||||
// The on-screen nose the drawn row shows now, against the feed's.
|
||||
const drawnError = () => {
|
||||
const now = findBB(id);
|
||||
if (!now) return { shown: false, rotationError: NaN };
|
||||
// A GPU row is turned along its drawn course, or drawn upright; a
|
||||
// billboard carries its screen rotation itself.
|
||||
const drawn = Number.isFinite(now.course)
|
||||
? (now.rotates ? screenProjectedRotation(v.scene, now.position, now.course, null) : 0)
|
||||
: now.rotation;
|
||||
return {
|
||||
shown: !!now.show,
|
||||
rotationError: angDiff(drawn, screenProjectedRotation(v.scene, now.position, course, null)),
|
||||
};
|
||||
};
|
||||
const hasModel = !!(window.__g3dFindModel && window.__g3dFindModel(id));
|
||||
// A wall-clock timeout is inconclusive, not a wrong angle: the frame
|
||||
// landed where the 1 s idle refresh could already have repaired it
|
||||
// (seen once on headless SwiftShader: a 926 ms first frame). Such an
|
||||
// observation gets one more attempt; one that measured a wrong angle —
|
||||
// a wrong first reveal, or a wrong settle frame before a reveal
|
||||
// timeout — never does.
|
||||
// The settle/reveal budgets and the retry were written for the removed
|
||||
// CPU passes (a frame late enough for the 1 s idle refresh to repair
|
||||
// it was inconclusive); they are kept unchanged as a guard. A
|
||||
// wall-clock timeout gets one more attempt; one that measured a wrong
|
||||
// angle — a wrong first reveal, or a wrong settle frame before a
|
||||
// reveal timeout — never does.
|
||||
//
|
||||
// The reveal: the row is hidden right after the settle frame, frames
|
||||
// must actually draw it hidden, and only then is it shown again, so
|
||||
// the frame measured is the first one that draws it after a hidden
|
||||
// frame. It stays hidden for two drawn frames, past the frame that
|
||||
// follows the settle frame, so the reveal is timed on an ordinary
|
||||
// frame rather than on whether that one was pipelined; each hidden
|
||||
// frame restarts the reveal's clock, and the setup is `hiddenMs`.
|
||||
const REVEAL_HIDDEN_FRAMES = 2;
|
||||
let revealArmed = false;
|
||||
let hiddenFrames = 0;
|
||||
const observed = await observeArrivalRotationWithRetry({
|
||||
async prepare() {
|
||||
// Freshen both layers' rotation passes right before the probe, so
|
||||
// the settle frame is measured against a pass that just ran rather
|
||||
// than one left over from the previous probe — with the camera
|
||||
// idle, a layer otherwise runs a pass only every
|
||||
// ROTATION_REFRESH_MS.
|
||||
// One settled camera move and a frame before each attempt, as the
|
||||
// passes once needed (the layers' moveEnd now runs their fleet
|
||||
// pass on the next frame).
|
||||
revealArmed = false;
|
||||
hiddenFrames = 0;
|
||||
v.camera.moveEnd.raiseEvent();
|
||||
await nextFrames(1);
|
||||
},
|
||||
scene: v.scene,
|
||||
startMoveEnd() {
|
||||
// Only moveEnd can repair the tampered angle at the idle pose.
|
||||
bb.rotation = r0 + 1.5;
|
||||
v.camera.moveEnd.raiseEvent();
|
||||
},
|
||||
startReveal() {
|
||||
// Hide immediately after the confirmed settle frame. The next
|
||||
// eligible fleet tick must reveal AND re-aim in that same tick.
|
||||
bb.rotation = r0 + 1.5;
|
||||
bb.show = false;
|
||||
// Hide immediately after the confirmed settle frame, through the
|
||||
// layer's icon book (written to the draw set as this task ends).
|
||||
setIconShown(id, { shown: false });
|
||||
revealArmed = true;
|
||||
},
|
||||
read() {
|
||||
return {
|
||||
shown: bb.show,
|
||||
rotationError: angDiff(bb.rotation,
|
||||
screenProjectedRotation(v.scene, bb.position, course, null)),
|
||||
};
|
||||
const sample = drawnError();
|
||||
// A frame drew it hidden: after the last one, show it again for
|
||||
// the next frame; the reveal is measured from here.
|
||||
if (revealArmed && sample.shown === false) {
|
||||
hiddenFrames += 1;
|
||||
if (hiddenFrames >= REVEAL_HIDDEN_FRAMES) {
|
||||
revealArmed = false;
|
||||
setIconShown(id, { shown: true });
|
||||
}
|
||||
return { ...sample, revealStartsNow: true };
|
||||
}
|
||||
return sample;
|
||||
},
|
||||
});
|
||||
return { r0, ...observed, hasModel };
|
||||
// A reveal is only one after a frame drew the row hidden.
|
||||
if (!observed.error && hiddenFrames === 0) {
|
||||
return { ...observed, error: 'no frame drew the row hidden before its reveal', hasModel };
|
||||
}
|
||||
return { ...observed, hiddenFrames, hasModel };
|
||||
};
|
||||
const flightCourse = window.__SYNTH.flights.find((f) => f.icao === 'aaa002')?.track ?? 0;
|
||||
const militaryCourse = window.__SYNTH.military.find((m) => m.hex === 'bbb101')?.track ?? 0;
|
||||
return {
|
||||
flights: await probe('aaa002', flightCourse),
|
||||
military: await probe('bbb101', militaryCourse),
|
||||
flights: await probe(dm.layers.get('flights').module, 'aaa002', flightCourse),
|
||||
military: await probe(dm.layers.get('military').module, 'bbb101', militaryCourse),
|
||||
};
|
||||
});
|
||||
const fmtArr = (a) => (!a ? `no result (${arrival?.error || 'phase error'})` : a.error ? `${a.error}; ${arrivalAngleViolated(a) ? 'angle violation (not retried); ' : ''}${Number.isFinite(a.dMoveEnd) ? `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° ` : ''}${Number.isFinite(a.dReveal) ? `reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° ` : ''}elapsed=${Number(a.elapsedMs).toFixed(1)} ms attempts=${a.attempts}`
|
||||
: `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`);
|
||||
const TAMPER_DEG = 1.5 * 180 / Math.PI; // ≈ 86° — an uncorrected nose stays this far off
|
||||
record(`arrival: moveEnd + first reveal both re-aim before idle refresh, flights (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
: `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms hidden=${a.hiddenMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`);
|
||||
record('arrival: the drawn nose is right on the settle frame and the first reveal, flights',
|
||||
arrivalRotationPassed(arrival.flights), fmtArr(arrival.flights));
|
||||
record(`arrival: moveEnd + first reveal both re-aim before idle refresh, military (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
record('arrival: the drawn nose is right on the settle frame and the first reveal, military',
|
||||
arrivalRotationPassed(arrival.military), fmtArr(arrival.military));
|
||||
|
||||
// ============================================================
|
||||
@@ -3027,18 +3140,7 @@ async function main() {
|
||||
};
|
||||
fl.setParams({ models3d: false }); // billboards own the visual (T7 gate open)
|
||||
window.__dfFindBB = (id) => {
|
||||
let found = null;
|
||||
const walk = (coll) => {
|
||||
const n = coll.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let p; try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
return window.__qaFindIcon(id);
|
||||
};
|
||||
window.__dfCarto = (pos) => {
|
||||
const c = Cesium.Cartographic.fromCartesian(pos, Cesium.Ellipsoid.WGS84);
|
||||
@@ -3124,7 +3226,7 @@ async function main() {
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined) {
|
||||
if (icao !== undefined && p.id !== icao) continue;
|
||||
if (icao !== undefined && window.__qaModelIcao(p) !== icao) continue;
|
||||
if (p.show) {
|
||||
shown += 1;
|
||||
if (p.ready === true) rendering += 1;
|
||||
@@ -3149,7 +3251,7 @@ async function main() {
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined
|
||||
&& p.id === icao && p.modelMatrix) {
|
||||
&& window.__qaModelIcao(p) === icao && p.modelMatrix) {
|
||||
const m = p.modelMatrix;
|
||||
// Cesium's default is the IDENTITY matrix — translation (0,0,0),
|
||||
// the Earth's centre, which `Cartographic.fromCartesian` refuses.
|
||||
@@ -3167,23 +3269,18 @@ async function main() {
|
||||
walk(v.scene.primitives);
|
||||
return h;
|
||||
};
|
||||
// Tracked-contact model regime (2026-08-20). The tracked contact's model
|
||||
// is NOT governed by the DISPLAY-rail 3D toggle — that toggle owns the
|
||||
// FLEET's draw-call budget. The tracked model is default-on and driven by
|
||||
// camera distance, entering below TRACKED_MODEL_ENTER_ALT_M and handing
|
||||
// back to the billboard only above TRACKED_MODEL_EXIT_ALT_M (the
|
||||
// anti-flap band). The CAMERA is therefore what decides whether a model
|
||||
// or a billboard is the visual for a tracked contact, which is exactly
|
||||
// what the display floor stands aside for — so these pins drive the
|
||||
// camera explicitly instead of the toggle.
|
||||
// Tracked-contact model regime. The tracked contact draws as a model
|
||||
// exactly when the fleet's rule would draw it so: 3D on, the camera
|
||||
// below the fleet ceiling, and the contact inside the nearest-first
|
||||
// add/keep band from the eye. These pins drive the camera across that
|
||||
// band: a model inside the ADD radius, the billboard past the KEEP one.
|
||||
//
|
||||
// Read the thresholds from the app's own policy module so a later retune
|
||||
// of the swap distance moves these pins with it rather than stranding
|
||||
// them on stale numbers.
|
||||
const reg = await import(`${window.__gevQaSourceBase || '/src'}/data/trackedModelRegime.js`);
|
||||
// Read the radii from the app's own policy module so a retune moves
|
||||
// these pins with it rather than stranding them on stale numbers.
|
||||
const reg = await import(`${window.__gevQaSourceBase || '/src'}/layers/flights/policy.js`);
|
||||
window.__dfRegime = {
|
||||
enter: reg.TRACKED_MODEL_ENTER_ALT_M,
|
||||
exit: reg.TRACKED_MODEL_EXIT_ALT_M,
|
||||
enter: reg.MODEL_PROX_ADD_M,
|
||||
exit: reg.MODEL_PROX_KEEP_M,
|
||||
};
|
||||
// Zooming while following is safe: the tracked-camera framer positions
|
||||
// the camera ONCE per selection and is deliberately read-only on normal
|
||||
@@ -3529,9 +3626,29 @@ async function main() {
|
||||
// after d0 was read; a lower seed makes the negative model-ownership
|
||||
// assertion impossible even when the clamp correctly stands aside.
|
||||
const seeded = Math.max(d0.h, 400) + 40;
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
gf.reportMeshFloorCell(cell(d0.lat) + dy * 0.001, cell(d0.lon) + dx * 0.001, seeded);
|
||||
// The contact keeps taxiing while the regimes below are driven (the
|
||||
// model wait alone can run to 20 s), so the planted floor reaches
|
||||
// along its heading as well: the 3×3 cells around it, and the same
|
||||
// three cells across the track every ~100 m for 600 m ahead. A
|
||||
// contact that left a 3×3 patch was read over an unplanted cell,
|
||||
// where a DEM floor that had already landed under its raw height
|
||||
// decided the assertion instead of the regime.
|
||||
const headingDeg = window.__SYNTH.flights.find((f) => f.icao === 'aaa097')?.track ?? 0;
|
||||
const headingRad = headingDeg * Math.PI / 180;
|
||||
const metresPerDegLat = 111320;
|
||||
const metresPerDegLon = metresPerDegLat * Math.cos(d0.lat * Math.PI / 180);
|
||||
const plantedCells = new Set();
|
||||
for (let aheadM = 0; aheadM <= 600; aheadM += 100) {
|
||||
const lat = d0.lat + (aheadM * Math.cos(headingRad)) / metresPerDegLat;
|
||||
const lon = d0.lon + (aheadM * Math.sin(headingRad)) / metresPerDegLon;
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
const c = [cell(lat) + dy * 0.001, cell(lon) + dx * 0.001];
|
||||
const key = `${c[0].toFixed(3)},${c[1].toFixed(3)}`;
|
||||
if (plantedCells.has(key)) continue;
|
||||
plantedCells.add(key);
|
||||
gf.reportMeshFloorCell(c[0], c[1], seeded);
|
||||
}
|
||||
}
|
||||
}
|
||||
const fleetClampDeadline = Date.now() + 5000;
|
||||
@@ -3549,7 +3666,7 @@ async function main() {
|
||||
// the sensor value the data APIs report, at whatever regime the camera
|
||||
// is currently in.
|
||||
const readTracked = () => {
|
||||
const pos = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const pos = window.__qaFollowed()?.position?.();
|
||||
if (!pos) return null;
|
||||
const c = window.__dfCarto(pos);
|
||||
const info = fl.getTrackedInfo();
|
||||
@@ -3624,19 +3741,19 @@ async function main() {
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const item = collection.get(i);
|
||||
if (typeof item?.get === 'function' && typeof item.length === 'number') walk(item);
|
||||
else if (item?.id === 'aaa097' && item.activeAnimations !== undefined
|
||||
else if (window.__qaModelIcao(item) === 'aaa097' && item.activeAnimations !== undefined
|
||||
&& item.minimumPixelSize !== undefined) found = item;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
return found;
|
||||
};
|
||||
const trackedEntity = v.trackedEntity;
|
||||
const trackedEntity = window.__qaFollowed();
|
||||
const trackedModel = findOwnModel();
|
||||
const achievedOut = await window.__dfZoomAbove(window.__dfRegime.exit + 5000);
|
||||
const zoomedOut = await window.__dfObserveTrackedExit({
|
||||
scene: v.scene, trackedEntity, trackedModel, getTrackedModel: findOwnModel,
|
||||
getTrackedEntity: () => v.trackedEntity,
|
||||
getTrackedEntity: () => window.__qaFollowed(),
|
||||
getTrackedId: () => fl.getTrackedInfo()?.icao24,
|
||||
getCameraHeight: window.__dfCamH, exitHeight: window.__dfRegime.exit,
|
||||
read: readTracked,
|
||||
@@ -3804,7 +3921,7 @@ async function main() {
|
||||
return { skipped: 'no tracked model rendered in this browser' };
|
||||
}
|
||||
// While the model IS the visual the clamp must stand aside (T7).
|
||||
const entWith = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const entWith = window.__qaFollowed()?.position?.();
|
||||
const withModelH = entWith ? window.__dfCarto(entWith).h : null;
|
||||
// Close the deterministic skin again for the rest of the group. The
|
||||
// model is up on a snap that is already cached, so it stays up until the
|
||||
@@ -3819,7 +3936,7 @@ async function main() {
|
||||
// contact's primitive, and an unrelated model in the scene must not be
|
||||
// able to answer it either way.
|
||||
const afterOut = window.__dfCountModels('aaa097');
|
||||
const ent = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const ent = window.__qaFollowed()?.position?.();
|
||||
const c = ent ? window.__dfCarto(ent) : null;
|
||||
// Plant a floor above wherever it now renders so "floored" is decisive.
|
||||
// Mesh cells latch ONE-SHOT, so the earlier scenario's seed would win
|
||||
@@ -3840,7 +3957,7 @@ async function main() {
|
||||
// from mistaking a cached same-frame position for a failed clamp.
|
||||
v.scene.requestRender();
|
||||
await window.__dfSettle(900);
|
||||
const ent2 = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const ent2 = window.__qaFollowed()?.position?.();
|
||||
const c2 = ent2 ? window.__dfCarto(ent2) : null;
|
||||
const out = {
|
||||
toggleOff,
|
||||
@@ -3932,7 +4049,7 @@ async function main() {
|
||||
let p; try { p = coll.get(i); } catch { continue; }
|
||||
if (!p) continue;
|
||||
if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; }
|
||||
if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && p.id === id) found = p;
|
||||
if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && window.__qaModelIcao(p) === id) found = p;
|
||||
}
|
||||
};
|
||||
walk(v.scene.primitives);
|
||||
@@ -3948,19 +4065,30 @@ async function main() {
|
||||
fl.setParams({ models3d: false });
|
||||
return { skipped: 'no fleet model for aaa097 in this browser' };
|
||||
}
|
||||
// The layer decides who owns the visual from its OWN record of the
|
||||
// model (data/modelRecord.js: `ready` from the draw set's ready event,
|
||||
// `show` as it last sent it), not from the renderer's model object, so
|
||||
// the shown-but-not-ready state is planted on that record. The record
|
||||
// is the registered layer's own, reached through its test seam.
|
||||
const fleetRecord = await fl.testing?._ensureFleetModelForTest?.('aaa097');
|
||||
if (!fleetRecord || typeof fleetRecord !== 'object') {
|
||||
fl.setParams({ models3d: false });
|
||||
return { error: 'the flights layer has no model record for aaa097' };
|
||||
}
|
||||
// Accessors with SWALLOWING setters, not data properties: the fleet tick
|
||||
// assigns `model.show = false` for a not-ready model, and assigning to a
|
||||
// assigns `show = false` for a not-ready model, and assigning to a
|
||||
// non-writable own property throws in strict mode — which lands inside
|
||||
// Cesium's render loop and stops rendering for the rest of the run.
|
||||
const priorReady = Object.getOwnPropertyDescriptor(fleetModel, 'ready');
|
||||
const priorShow = Object.getOwnPropertyDescriptor(fleetModel, 'show');
|
||||
// the render loop and stops rendering for the rest of the run.
|
||||
const priorReady = Object.getOwnPropertyDescriptor(fleetRecord, 'ready');
|
||||
const priorShow = Object.getOwnPropertyDescriptor(fleetRecord, 'show');
|
||||
let armed = false;
|
||||
let processedFrame = null;
|
||||
let sample = null;
|
||||
let sampledRecord = null;
|
||||
let removePostRender = null;
|
||||
try {
|
||||
Object.defineProperty(fleetModel, 'ready', { get: () => false, set: () => {}, configurable: true });
|
||||
Object.defineProperty(fleetModel, 'show', {
|
||||
Object.defineProperty(fleetRecord, 'ready', { get: () => false, set: () => {}, configurable: true });
|
||||
Object.defineProperty(fleetRecord, 'show', {
|
||||
get: () => true,
|
||||
set: (value) => {
|
||||
// Both the not-ready handoff and horizon cull clear show AFTER
|
||||
@@ -3974,7 +4102,10 @@ async function main() {
|
||||
});
|
||||
const bb = window.__dfFindBB('aaa097');
|
||||
if (!bb) return { error: 'aaa097 billboard missing' };
|
||||
bb.show = true; // the handoff would not have hidden it: the model is not ready
|
||||
// (The icon is not forced shown here, as the old billboard fixture did:
|
||||
// the renderer draws what the layer sends, so the handoff the record
|
||||
// drives is the only thing that decides it.)
|
||||
const sameIcon = (a, b) => !!a && !!b && (a === b || (a.setId === b.setId && a.id === b.id));
|
||||
const d0 = window.__dfCarto(bb.position);
|
||||
gf._clearMeshFloorCellsForTest();
|
||||
// Earlier display-floor scenarios deliberately leave this contact's
|
||||
@@ -3997,13 +4128,18 @@ async function main() {
|
||||
sample = {
|
||||
fleetTickCompleted: true,
|
||||
fleetFrame: v.scene.frameState.frameNumber,
|
||||
fleetModelReady: fleetModel.ready,
|
||||
fleetModelShow: fleetModel.show,
|
||||
fleetModelReady: fleetRecord.ready,
|
||||
fleetModelShow: fleetRecord.show,
|
||||
fleetBillboardVisible: !!currentBb?.show,
|
||||
fleetSeeded: seededFleet,
|
||||
fleetH: currentBb ? window.__dfCarto(currentBb.position).h : null,
|
||||
};
|
||||
if (currentBb !== bb || currentModel !== fleetModel || fleetModel.isDestroyed()
|
||||
// (An older build's seam answers asynchronously: its answer is
|
||||
// checked once the frame is done, below.)
|
||||
const currentRecord = fl.testing._ensureFleetModelForTest('aaa097');
|
||||
if (typeof currentRecord?.then === 'function') sampledRecord = currentRecord;
|
||||
else if (currentRecord !== fleetRecord) sample.error = 'fleet loading fixture changed before its completed frame';
|
||||
if (!sameIcon(currentBb, bb) || currentModel !== fleetModel || fleetModel.isDestroyed()
|
||||
|| fl.getTrackedInfo()) sample.error = 'fleet loading fixture changed before its completed frame';
|
||||
});
|
||||
armed = true;
|
||||
@@ -4014,14 +4150,17 @@ async function main() {
|
||||
await window.__dfSettle(50);
|
||||
} while (!sample && Date.now() < tickDeadline);
|
||||
if (!sample) return { error: 'fleet loading fixture did not complete an aircraft update within 5000 ms' };
|
||||
if (sampledRecord && (await sampledRecord) !== fleetRecord) {
|
||||
sample.error = 'fleet loading fixture changed before its completed frame';
|
||||
}
|
||||
Object.assign(out, sample);
|
||||
} finally {
|
||||
armed = false;
|
||||
removePostRender?.();
|
||||
if (priorReady) Object.defineProperty(fleetModel, 'ready', priorReady);
|
||||
else delete fleetModel.ready;
|
||||
if (priorShow) Object.defineProperty(fleetModel, 'show', priorShow);
|
||||
else delete fleetModel.show;
|
||||
if (priorReady) Object.defineProperty(fleetRecord, 'ready', priorReady);
|
||||
else delete fleetRecord.ready;
|
||||
if (priorShow) Object.defineProperty(fleetRecord, 'show', priorShow);
|
||||
else delete fleetRecord.show;
|
||||
fl.setParams({ models3d: false });
|
||||
}
|
||||
await window.__dfSettle(400);
|
||||
@@ -4032,7 +4171,7 @@ async function main() {
|
||||
// it finishes. Sample within that window.
|
||||
if (!fl.trackById('aaa097')) return { ...out, error: 'trackById(aaa097) failed' };
|
||||
await window.__dfSettle(500);
|
||||
const entBefore = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const entBefore = window.__qaFollowed()?.position?.();
|
||||
const cBefore = entBefore ? window.__dfCarto(entBefore) : null;
|
||||
gf._clearMeshFloorCellsForTest();
|
||||
fl._clearDisplayFloorStateForTest();
|
||||
@@ -4054,7 +4193,7 @@ async function main() {
|
||||
// billboard-owned. The shared helper keys models by their pick id and
|
||||
// uses the production ownership pair (`show && ready`).
|
||||
out.renderingModelsDuringLoad = window.__dfCountModels('aaa097').rendering;
|
||||
const entLoad = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now());
|
||||
const entLoad = window.__qaFollowed()?.position?.();
|
||||
out.trackedSeeded = seededTracked;
|
||||
out.trackedLoadH = entLoad ? window.__dfCarto(entLoad).h : null;
|
||||
fl.setParams({ models3d: false });
|
||||
@@ -4174,7 +4313,12 @@ async function main() {
|
||||
const taxiCarto = window.__dfCarto(taxiPos);
|
||||
const baseMeshM = gfns?.cachedMeshFloor?.(baseCarto.lat, baseCarto.lon) ?? null;
|
||||
const taxiMeshM = gfns?.cachedMeshFloor?.(taxiCarto.lat, taxiCarto.lon) ?? null;
|
||||
// The layer writes its icon changes to the draw set together once the
|
||||
// current task's microtasks run (data/aircraftIconLayer.js), so the
|
||||
// drawn row is read after that write, with no frame in between.
|
||||
const iconWrites = () => Promise.resolve();
|
||||
const heldOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: taxiPos, course: 90 });
|
||||
await iconWrites();
|
||||
const heldH = window.__dfModelHeight(holdIcao);
|
||||
const heldBb = !!window.__dfFindBB(holdIcao)?.show;
|
||||
|
||||
@@ -4182,6 +4326,7 @@ async function main() {
|
||||
// been. It is released rather than stretched, and the gate takes over.
|
||||
const farPos = Cesium.Cartesian3.fromDegrees(base.lon + 0.004, base.lat, base.h);
|
||||
const releasedOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: farPos, course: 90 });
|
||||
await iconWrites();
|
||||
const releasedBb = !!window.__dfFindBB(holdIcao)?.show;
|
||||
|
||||
fl.setParams({ models3d: false });
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Lower `src/render/viewerAccessAllowList.json` to the Cesium-shaped viewer
|
||||
* accesses the files off the Cesium list still hold
|
||||
* (`src/render/viewerAccess.test.mjs`). It only lowers counts and drops
|
||||
* entries (files with none left, gone, or back on the Cesium list); it never
|
||||
* adds a file or raises a count. A file over its count is reported and the
|
||||
* script exits 1: port that access instead.
|
||||
*
|
||||
* `--check` reports what it would change without writing, and exits 1 when
|
||||
* there is anything to lower.
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
BASELINE,
|
||||
countedFiles,
|
||||
currentHits,
|
||||
readBaseline,
|
||||
ROOT,
|
||||
} from '../src/testSupport/viewerAccess.mjs';
|
||||
|
||||
const check = process.argv.includes('--check');
|
||||
const baseline = readBaseline();
|
||||
const hits = currentHits();
|
||||
const counted = new Set(countedFiles());
|
||||
|
||||
const next = {};
|
||||
const changes = [];
|
||||
for (const [file, allowed] of Object.entries(baseline)) {
|
||||
const found = counted.has(file) ? (hits.get(file)?.length ?? 0) : 0;
|
||||
const count = Math.min(allowed, found);
|
||||
if (count > 0) next[file] = count;
|
||||
if (count !== allowed) changes.push(`${file}: ${allowed} → ${count}`);
|
||||
}
|
||||
const over = [...hits]
|
||||
.filter(([file, found]) => found.length > (baseline[file] ?? 0))
|
||||
.map(
|
||||
([file, found]) =>
|
||||
`${file}: ${found.length} found, ${baseline[file] ?? 0} recorded`,
|
||||
);
|
||||
|
||||
if (changes.length) {
|
||||
console.log(
|
||||
`${check ? 'Would lower' : 'Lowered'}:\n ${changes.join('\n ')}`,
|
||||
);
|
||||
if (!check) {
|
||||
const sorted = Object.fromEntries(
|
||||
Object.keys(next)
|
||||
.sort()
|
||||
.map((file) => [file, next[file]]),
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(ROOT, BASELINE),
|
||||
`${JSON.stringify(sorted, null, 2)}\n`,
|
||||
);
|
||||
} else process.exitCode = 1;
|
||||
} else console.log(`${BASELINE} is as low as it goes.`);
|
||||
if (over.length) {
|
||||
console.error(
|
||||
`Over their counts (never raised; port these):\n ${over.join('\n ')}`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const DIR = fileURLToPath(
|
||||
new URL('../../src/render/conformance/goldens/visual/', import.meta.url),
|
||||
);
|
||||
const NAME = /^[a-z0-9-]+\.(png|json)$/;
|
||||
const MAX_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Dev server only: lets `/dev/conformance/` save the visual references it
|
||||
* records into `src/render/conformance/goldens/visual/`. Takes a PUT of one
|
||||
* PNG or the manifest, named in the path; nothing else is written.
|
||||
*/
|
||||
export function conformanceReferencesPlugin() {
|
||||
return {
|
||||
name: 'conformance-references',
|
||||
apply: 'serve',
|
||||
configureServer(server) {
|
||||
server.middlewares.use('/__conformance/references/', (req, res) => {
|
||||
const name = decodeURIComponent((req.url ?? '').replace(/^\//, ''));
|
||||
// Only the page on this machine: a loopback peer, sent from the
|
||||
// dev server's own origin.
|
||||
const peer = req.socket.remoteAddress ?? '';
|
||||
const loopback = /^(127\.|::1$|::ffff:127\.)/.test(peer);
|
||||
let sameOrigin = false;
|
||||
try {
|
||||
sameOrigin = new URL(req.headers.origin).host === req.headers.host;
|
||||
} catch {
|
||||
// No Origin, or not a URL.
|
||||
}
|
||||
if (!loopback || !sameOrigin) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'PUT' || !NAME.test(name)) {
|
||||
res.writeHead(400).end();
|
||||
return;
|
||||
}
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
req.on('data', (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > MAX_BYTES) req.destroy();
|
||||
else chunks.push(chunk);
|
||||
});
|
||||
req.on('end', async () => {
|
||||
try {
|
||||
await mkdir(DIR, { recursive: true });
|
||||
await writeFile(DIR + name, Buffer.concat(chunks));
|
||||
res.writeHead(204).end();
|
||||
} catch (error) {
|
||||
res.writeHead(500).end(String(error?.message ?? error));
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { createBrowserViteConfig } from '../../build/vite.js';
|
||||
import { localProviderPlugins } from '../providers/local.js';
|
||||
import { localMcpPlugin } from '../mcp/plugin.js';
|
||||
import { apiNotFoundPlugin } from './api-not-found.js';
|
||||
import { conformanceReferencesPlugin } from './conformance-references.js';
|
||||
import { googleTokenUnavailablePlugin } from './google-token-unavailable.js';
|
||||
import { standaloneVoiceTools } from './voiceTools.js';
|
||||
import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js';
|
||||
@@ -30,6 +31,7 @@ export function standaloneConfig(
|
||||
}),
|
||||
localMcpPlugin(),
|
||||
googleTokenUnavailablePlugin(),
|
||||
conformanceReferencesPlugin(),
|
||||
apiNotFoundPlugin(),
|
||||
unwatchedRuntimeDirsPlugin(),
|
||||
],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import {
|
||||
feedProvenanceEnvelope,
|
||||
layerSnapshot,
|
||||
@@ -104,14 +104,12 @@ export function getWorldPacket(options = {}) {
|
||||
// A default parameter only covers undefined; null or NaN would age every
|
||||
// feed against the epoch and report stale data as "just now".
|
||||
const now = Number.isFinite(requestedNow) ? requestedNow : Date.now();
|
||||
if (!viewer?.camera?.positionWC)
|
||||
throw new TypeError('World Packet requires a viewer camera');
|
||||
const pose = findCamera(viewer)?.pose();
|
||||
if (!pose) throw new TypeError('World Packet requires a viewer camera');
|
||||
if (!dataManager || typeof dataManager.getAll !== 'function')
|
||||
throw new TypeError('World Packet requires a data manager');
|
||||
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(
|
||||
viewer.camera.positionWC,
|
||||
);
|
||||
const eye = { lon: pose.lon, lat: pose.lat, height: pose.height };
|
||||
// Read the roster once. Voice must not rewalk disabled layers: preserving the
|
||||
// current enabled-only view keeps the model's context budget bounded.
|
||||
const rows = dataManager.getAll();
|
||||
@@ -126,9 +124,9 @@ export function getWorldPacket(options = {}) {
|
||||
ok: true,
|
||||
action: 'get_current_view_state',
|
||||
camera: {
|
||||
latitude: Cesium.Math.toDegrees(cartographic.latitude),
|
||||
longitude: Cesium.Math.toDegrees(cartographic.longitude),
|
||||
heightM: cartographic.height,
|
||||
latitude: eye.lat,
|
||||
longitude: eye.lon,
|
||||
heightM: eye.height,
|
||||
},
|
||||
style: styleManager?.activeStyle || 'normal',
|
||||
context: contextState
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
import { getWorldPacket } from './worldPacket.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { createStubRenderer } from '../render/stub/index.js';
|
||||
import { createGevActionRunner } from '../voice/gevActions.js';
|
||||
|
||||
function withoutVoicePresentation(result) {
|
||||
@@ -18,6 +20,9 @@ function harness() {
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
get canvas() {
|
||||
return this.scene.canvas;
|
||||
},
|
||||
scene: {
|
||||
canvas: {
|
||||
clientWidth: 1200,
|
||||
@@ -60,6 +65,14 @@ function harness() {
|
||||
getCockpitState: () => null,
|
||||
getControlState: () => ({ hud: { visible: 'auto' } }),
|
||||
};
|
||||
// The packet reads the eye from the camera port of the renderer bound to
|
||||
// the scene object.
|
||||
const renderer = createStubRenderer();
|
||||
renderer.camera.setView({
|
||||
destination: { lon: -97.74, lat: 30.26, height: 500 },
|
||||
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-45), roll: 0 },
|
||||
});
|
||||
bindRenderer(viewer, renderer);
|
||||
return { viewer, dataManager, styleManager };
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,13 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
|
||||
import { createAnnotationResolver } from './resolver.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { createAnnotationEngine } from './annotationEngine.js';
|
||||
import { _resetRenderGovernorForTest } from '../renderGovernor.js';
|
||||
|
||||
function viewerAt(lat, lon, height = 20_000) {
|
||||
return {
|
||||
// The resolver reads the camera through the renderer's camera port.
|
||||
return bindFakeCesiumCamera({
|
||||
camera: {
|
||||
positionCartographic: {
|
||||
latitude: (lat * Math.PI) / 180,
|
||||
@@ -16,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) {
|
||||
height,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** A resolver whose boundary lookups and geocoder record every call. */
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { isUnavailableCapability } from '../sources/capability.js';
|
||||
import { defaultGeospatial } from '../search/defaults.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { cameraOf, findCamera, findQuery } from '../render/rendererOf.js';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { sphereFromPoints } from '../geo/sphere.js';
|
||||
import { distance, toRadians } from '../geo/vector.js';
|
||||
import { greatCircleMeters } from '../geoDistance.js';
|
||||
import {
|
||||
holdContinuousRender,
|
||||
@@ -20,11 +23,6 @@ import {
|
||||
} from '../sources/phaseTiming.js';
|
||||
import { formatDistanceText } from '../data/distanceFormat.js';
|
||||
|
||||
// Dev convenience: expose the app's Cesium instance for console/preview probing
|
||||
// (single shared module instance — avoids dual-Cesium state bugs when testing).
|
||||
if (typeof window !== 'undefined' && !window.__CESIUM__)
|
||||
window.__CESIUM__ = Cesium;
|
||||
|
||||
/**
|
||||
* Annotation engine — the voice agent's "whiteboard" over the 3D world.
|
||||
*
|
||||
@@ -1717,18 +1715,20 @@ export function createAnnotationEngine({
|
||||
frameAnnotation(marks[0]);
|
||||
return;
|
||||
}
|
||||
const cart = points.map((p) =>
|
||||
Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0),
|
||||
const cart = points.map((p) => fromDegrees(p.lon, p.lat, p.height || 0));
|
||||
const sphere = sphereFromPoints(cart);
|
||||
const camera = cameraOf(viewer);
|
||||
camera.flyToBounds(
|
||||
{ center: sphere.center, radius: sphere.radius },
|
||||
{
|
||||
offset: {
|
||||
heading: camera.pose().heading,
|
||||
pitch: toRadians(-35),
|
||||
range: Math.max(900, sphere.radius * 2.6),
|
||||
},
|
||||
durationS: 1.6,
|
||||
},
|
||||
);
|
||||
const sphere = Cesium.BoundingSphere.fromPoints(cart);
|
||||
viewer.camera.flyToBoundingSphere(sphere, {
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
viewer.camera.heading,
|
||||
Cesium.Math.toRadians(-35),
|
||||
Math.max(900, sphere.radius * 2.6),
|
||||
),
|
||||
duration: 1.6,
|
||||
});
|
||||
} catch {
|
||||
/* camera assist is best-effort */
|
||||
}
|
||||
@@ -1738,23 +1738,35 @@ export function createAnnotationEngine({
|
||||
* globe. On any API hiccup, report visible — bad data must never move the camera. */
|
||||
function isPointOnScreen(p) {
|
||||
try {
|
||||
const camera = viewer.camera;
|
||||
const pos = Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0);
|
||||
const cv = camera.frustum.computeCullingVolume(
|
||||
camera.position,
|
||||
camera.direction,
|
||||
camera.up,
|
||||
);
|
||||
if (
|
||||
cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) ===
|
||||
Cesium.Intersect.OUTSIDE
|
||||
)
|
||||
return false;
|
||||
const occluder = new Cesium.EllipsoidalOccluder(
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
camera.position,
|
||||
);
|
||||
return occluder.isPointVisible(pos);
|
||||
const camera = findCamera(viewer);
|
||||
const query = findQuery(viewer);
|
||||
if (!camera || !query) return true;
|
||||
const pos = fromDegrees(p.lon, p.lat, p.height || 0);
|
||||
// Inside the view frustum: a 1 m sphere at the point is not wholly
|
||||
// outside any of its six planes, read off the view-projection (depth
|
||||
// runs -1..1). An invalid matrix measures no distance and reads as
|
||||
// visible.
|
||||
const { view, projection } = camera.matrices();
|
||||
const m = new Float64Array(16);
|
||||
for (let col = 0; col < 4; col++)
|
||||
for (let row = 0; row < 4; row++) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 4; k++)
|
||||
sum += projection[k * 4 + row] * view[col * 4 + k];
|
||||
m[col * 4 + row] = sum;
|
||||
}
|
||||
const at = (row, col) => m[col * 4 + row];
|
||||
for (const [axis, sign] of FRUSTUM_PLANES) {
|
||||
const a = at(3, 0) + sign * at(axis, 0);
|
||||
const b = at(3, 1) + sign * at(axis, 1);
|
||||
const c = at(3, 2) + sign * at(axis, 2);
|
||||
const d = at(3, 3) + sign * at(axis, 3);
|
||||
const distanceM =
|
||||
(a * pos.x + b * pos.y + c * pos.z + d) / Math.hypot(a, b, c);
|
||||
if (distanceM < -1) return false;
|
||||
}
|
||||
// On the near side of the globe.
|
||||
return !query.isOccluded(pos);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
@@ -1778,22 +1790,23 @@ export function createAnnotationEngine({
|
||||
: anno.ring,
|
||||
)
|
||||
: viewportRange(anno.viewport) || 600;
|
||||
viewer.camera.flyToBoundingSphere(
|
||||
new Cesium.BoundingSphere(
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
target.lon,
|
||||
target.lat,
|
||||
anno.anchor.height || 0,
|
||||
),
|
||||
range,
|
||||
),
|
||||
const camera = cameraOf(viewer);
|
||||
camera.flyToBounds(
|
||||
{
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
viewer.camera.heading,
|
||||
Cesium.Math.toRadians(-35),
|
||||
range * 2.4,
|
||||
),
|
||||
duration: 1.8,
|
||||
center: {
|
||||
lon: target.lon,
|
||||
lat: target.lat,
|
||||
height: anno.anchor.height || 0,
|
||||
},
|
||||
radius: range,
|
||||
},
|
||||
{
|
||||
offset: {
|
||||
heading: camera.pose().heading,
|
||||
pitch: toRadians(-35),
|
||||
range: range * 2.4,
|
||||
},
|
||||
durationS: 1.8,
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
@@ -2005,15 +2018,17 @@ export function createAnnotationEngine({
|
||||
}) {
|
||||
if (destroyed) return;
|
||||
try {
|
||||
viewer.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(heading),
|
||||
pitch: Cesium.Math.toRadians(pitch),
|
||||
roll: 0,
|
||||
cameraOf(viewer).flyTo(
|
||||
{ lon, lat, height },
|
||||
{
|
||||
orientation: {
|
||||
heading: toRadians(heading),
|
||||
pitch: toRadians(pitch),
|
||||
roll: 0,
|
||||
},
|
||||
durationS: duration,
|
||||
},
|
||||
duration,
|
||||
});
|
||||
);
|
||||
} catch {
|
||||
/* camera flight best-effort */
|
||||
}
|
||||
@@ -2175,13 +2190,23 @@ function pendingAnimation(anno, now) {
|
||||
// fly_to_location natural-region heuristic uses (owner field test 2026-07-23).
|
||||
const VIEWPORT_ASSIST_RANGE_CAP_M = 120000;
|
||||
|
||||
/** The view frustum's planes as `row 3 ± row axis` of the view-projection. */
|
||||
const FRUSTUM_PLANES = [
|
||||
[0, 1],
|
||||
[0, -1],
|
||||
[1, 1],
|
||||
[1, -1],
|
||||
[2, 1],
|
||||
[2, -1],
|
||||
];
|
||||
|
||||
/** flyTo range from a Places viewport box (low/high lat-lng corners), or null. */
|
||||
function viewportRange(vp) {
|
||||
if (!vp?.low || !vp?.high) return null;
|
||||
try {
|
||||
const span = Cesium.Cartesian3.distance(
|
||||
Cesium.Cartesian3.fromDegrees(vp.low.longitude, vp.low.latitude),
|
||||
Cesium.Cartesian3.fromDegrees(vp.high.longitude, vp.high.latitude),
|
||||
const span = distance(
|
||||
fromDegrees(vp.low.longitude, vp.low.latitude),
|
||||
fromDegrees(vp.high.longitude, vp.high.latitude),
|
||||
);
|
||||
return Number.isFinite(span) && span > 0
|
||||
? Math.max(300, Math.min(span * 0.7, VIEWPORT_ASSIST_RANGE_CAP_M))
|
||||
@@ -2206,9 +2231,9 @@ function ringRange(ring) {
|
||||
if (lon < minLon) minLon = lon;
|
||||
if (lon > maxLon) maxLon = lon;
|
||||
}
|
||||
const span = Cesium.Cartesian3.distance(
|
||||
Cesium.Cartesian3.fromDegrees(minLon, minLat),
|
||||
Cesium.Cartesian3.fromDegrees(maxLon, maxLat),
|
||||
const span = distance(
|
||||
fromDegrees(minLon, minLat),
|
||||
fromDegrees(maxLon, maxLat),
|
||||
);
|
||||
return Math.max(300, span * 0.7);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { createStandalonePlaceSearch } from '../standalone/placeSearch.js';
|
||||
// Voice-annotation resilience contract tests — pure logic, no network, no browser.
|
||||
//
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
installRenderGovernor,
|
||||
_resetRenderGovernorForTest,
|
||||
} from '../renderGovernor.js';
|
||||
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
|
||||
|
||||
// A resolver that replays a scripted sequence of outcomes (undefined = transient,
|
||||
// null = definitive miss, object = footprint) and counts its invocations.
|
||||
@@ -1471,7 +1473,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and
|
||||
const { renderer, calls } = fakeRenderer();
|
||||
const flights = [];
|
||||
const engine = createAnnotationEngine({
|
||||
viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } },
|
||||
viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }),
|
||||
renderer,
|
||||
});
|
||||
let changes = 0;
|
||||
@@ -1540,12 +1542,12 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec
|
||||
const { renderer, calls } = fakeRenderer();
|
||||
const flights = [];
|
||||
const engine = createAnnotationEngine({
|
||||
viewer: {
|
||||
viewer: bindFakeCesiumCamera({
|
||||
camera: {
|
||||
heading: 0,
|
||||
flyToBoundingSphere: (sphere) => flights.push(sphere),
|
||||
},
|
||||
},
|
||||
}),
|
||||
renderer,
|
||||
});
|
||||
let changes = 0;
|
||||
@@ -1757,7 +1759,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one
|
||||
_resetRenderGovernorForTest();
|
||||
t.after(() => _resetRenderGovernorForTest());
|
||||
let renders = 0;
|
||||
installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } });
|
||||
installRenderGovernor(framePortFor({ requestRenderMode: true, requestRender: () => (renders += 1) }));
|
||||
const { renderer } = fakeRenderer();
|
||||
const engine = createAnnotationEngine({ viewer: {}, renderer });
|
||||
await engine.annotate([
|
||||
@@ -1898,3 +1900,67 @@ test('plain recaption keeps the old mark addressable when its removal throws', a
|
||||
);
|
||||
assert.equal(engine.count(), 0);
|
||||
});
|
||||
|
||||
// The camera assist frames a fresh mark only when none of it is in view:
|
||||
// off the frustum or behind the globe, as the renderer's camera and query
|
||||
// ports see it. A camera that cannot answer leaves the view alone.
|
||||
test('camera assist frames marks out of view and leaves visible ones alone', async (t) => {
|
||||
installAnimationFrameStubs(t);
|
||||
const { bindRenderer } = await import('../render/rendererOf.js');
|
||||
const { horizonFrom } = await import('../geo/horizon.js');
|
||||
const viewerOver = (lon, lat, height, { broken = false } = {}) => {
|
||||
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
|
||||
const direction = Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const right = Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
|
||||
const view = Cesium.Matrix4.computeView(position, direction, up, right, new Cesium.Matrix4());
|
||||
const frustum = new Cesium.PerspectiveFrustum({
|
||||
fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, far: 5e7,
|
||||
});
|
||||
const flights = [];
|
||||
const viewer = {};
|
||||
const horizon = horizonFrom(position);
|
||||
bindRenderer(viewer, {
|
||||
camera: {
|
||||
pose: () => ({ heading: 0 }),
|
||||
matrices() {
|
||||
if (broken) throw new Error('no camera');
|
||||
return {
|
||||
view: Float64Array.from(Cesium.Matrix4.toArray(view)),
|
||||
projection: Float64Array.from(Cesium.Matrix4.toArray(frustum.projectionMatrix)),
|
||||
};
|
||||
},
|
||||
flyTo: (...args) => flights.push(['flyTo', ...args]),
|
||||
flyToBounds: (...args) => flights.push(['flyToBounds', ...args]),
|
||||
},
|
||||
query: { isOccluded: (p) => !horizon.isPointVisible(p) },
|
||||
});
|
||||
return { viewer, flights };
|
||||
};
|
||||
const pinAt = async (viewer, lon, lat) => {
|
||||
const engine = createAnnotationEngine({ viewer, renderer: fakeRenderer().renderer });
|
||||
await engine.annotate([{ type: 'pin', manual: true, latitude: lat, longitude: lon }], { persist: true, flyTo: false });
|
||||
};
|
||||
|
||||
const inView = viewerOver(-97.74, 30.27, 9000);
|
||||
await pinAt(inView.viewer, -97.742, 30.268);
|
||||
assert.equal(inView.flights.length, 0, 'a mark in view is left alone');
|
||||
|
||||
const aside = viewerOver(-97.74, 30.27, 9000);
|
||||
await pinAt(aside.viewer, -97.5, 30.6);
|
||||
assert.equal(aside.flights.length, 1, 'a mark off the frustum is framed');
|
||||
|
||||
const behind = viewerOver(60, 30, 9_000_000);
|
||||
await pinAt(behind.viewer, -120, -30);
|
||||
assert.equal(behind.flights.length, 1, 'a mark behind the globe is framed');
|
||||
|
||||
const broken = viewerOver(-97.74, 30.27, 9000, { broken: true });
|
||||
await pinAt(broken.viewer, -97.5, 30.6);
|
||||
assert.equal(broken.flights.length, 0, 'a camera that cannot answer moves nothing');
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { createPlaceSearch } from '../search/placeSearch.js';
|
||||
// Run with: npm test (node --test)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import {
|
||||
resolveAnnotationTarget as resolveTarget,
|
||||
selectFootprint,
|
||||
@@ -157,7 +158,8 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => {
|
||||
});
|
||||
|
||||
function closeViewportViewer() {
|
||||
return {
|
||||
// The resolver reads the camera through the renderer's camera port.
|
||||
return bindFakeCesiumCamera({
|
||||
camera: {
|
||||
positionCartographic: {
|
||||
latitude: 30.2672 * Math.PI / 180,
|
||||
@@ -165,7 +167,7 @@ function closeViewportViewer() {
|
||||
height: 1000,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function geocodePayload({ lat, lon, types, label }) {
|
||||
@@ -369,11 +371,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township
|
||||
// Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs.
|
||||
const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 };
|
||||
function capitolViewer() {
|
||||
return { camera: { positionCartographic: {
|
||||
return bindFakeCesiumCamera({ camera: { positionCartographic: {
|
||||
latitude: CAPITOL_ANCHOR.lat * Math.PI / 180,
|
||||
longitude: CAPITOL_ANCHOR.lon * Math.PI / 180,
|
||||
height: 1000,
|
||||
} } };
|
||||
} } });
|
||||
}
|
||||
function installCapitolMocks(t, elements, components = [
|
||||
{ long_name: 'Washington', types: ['locality', 'political'] },
|
||||
|
||||
+150
-175
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Manual whiteboard drawing: the Cesium + DOM half.
|
||||
* Manual whiteboard drawing: the scene + DOM half.
|
||||
*
|
||||
* UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
|
||||
* shape (area, line or pin) and a colour, click the vertices on the real world,
|
||||
@@ -15,12 +15,13 @@
|
||||
* (`src/data/inputOwnership.js`), and every ambient selection handler yields,
|
||||
* so a vertex clicked on top of an aircraft or a camera is a vertex and
|
||||
* nothing else. It is one claim consulted by all of them, not a list of
|
||||
* exceptions inside each.
|
||||
* exceptions inside each. Turning Draw on takes the pointer from any tool
|
||||
* holding it; a newer tool taking it turns Draw off.
|
||||
* - Cesium's Viewer binds its OWN left click (select the entity under the
|
||||
* pointer) and double click (track it) on the viewer's handler, outside every
|
||||
* layer and therefore outside the shared claim. Both are borrowed for the
|
||||
* layer and therefore outside the shared claim. Both are suppressed for the
|
||||
* session and given back on the way out, and `destroy()` gives back every
|
||||
* listener, the Cesium handler, the preview data source and the window
|
||||
* listener, the pointer subscriptions, the preview draw sets and the window
|
||||
* handle, so the tool can be turned off or the shell disposed without leaving
|
||||
* anything behind.
|
||||
*
|
||||
@@ -30,14 +31,13 @@
|
||||
* drapes finished areas and routes onto the surface, so the height is dropped
|
||||
* at finish, deliberately and in one place — see `finishSpec` in drawMode.js.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { pickWorldFromScreen } from './annotationResolver.js';
|
||||
import {
|
||||
claimPointer,
|
||||
pointerOwner,
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import {
|
||||
DRAW_SHAPES,
|
||||
MAX_VERTICES,
|
||||
@@ -59,7 +59,14 @@ import {
|
||||
presentDrawMarks,
|
||||
} from './drawMarks.js';
|
||||
|
||||
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
|
||||
import { onLocaleChange, t } from '../i18n/index.js';
|
||||
import { fromDegrees } from '../geo/index.js';
|
||||
import { cssColor } from '../render/color.js';
|
||||
import {
|
||||
canvasOf as sceneCanvasOf,
|
||||
drawOf,
|
||||
findFrame,
|
||||
} from '../render/rendererOf.js';
|
||||
/** The longest note a row action leaves under its row, in characters. */
|
||||
const NOTE_MAX = 200;
|
||||
/** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */
|
||||
@@ -74,7 +81,15 @@ function noteText(text) {
|
||||
|
||||
/** The id this tool claims the pointer under. */
|
||||
const DRAW_POINTER_OWNER = 'draw';
|
||||
const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview';
|
||||
/** Each tool's preview sets get their own ids. */
|
||||
let previewSerial = 0;
|
||||
/**
|
||||
* Preview sets drawn on each viewer by its live tools, so a tool left
|
||||
* undestroyed beside its replacement shows up in `diagnostics()`.
|
||||
*/
|
||||
const livePreviewSets = new WeakMap();
|
||||
const countPreviewSets = (viewer, delta) =>
|
||||
livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta);
|
||||
|
||||
const PREVIEW = DRAW_COLOR_CSS;
|
||||
|
||||
@@ -89,7 +104,7 @@ const PREVIEW = DRAW_COLOR_CSS;
|
||||
* `markActions` are the application's own buttons on an area's or a line's
|
||||
* row (drawMarks.js `drawMarkActions`); a press runs the action with the
|
||||
* shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`).
|
||||
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
|
||||
* @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
|
||||
* @returns {{destroy: Function}|null}
|
||||
*/
|
||||
export function initDrawTool({
|
||||
@@ -115,16 +130,13 @@ export function initDrawTool({
|
||||
let shape = 'area';
|
||||
let color = 'primary';
|
||||
let hint = '';
|
||||
let handler = null;
|
||||
let unbindScene = null;
|
||||
let lease = null;
|
||||
let savedDoubleClick = null;
|
||||
let savedSingleClick = null;
|
||||
let cursor = null; // last mouse position on the canvas, for the rubber band
|
||||
// Bumped by anything that supersedes an in-flight finish: cancelling, clearing
|
||||
// the board, leaving draw mode, teardown. An `annotate()` that resolves after
|
||||
// one of those must not write its outcome over the newer state.
|
||||
let generation = 0;
|
||||
const previewEntities = [];
|
||||
// Every DOM listener this tool adds (the session's keydown), so teardown is
|
||||
// one loop rather than a list that can fall out of step with the bindings.
|
||||
const domListeners = [];
|
||||
@@ -133,14 +145,26 @@ export function initDrawTool({
|
||||
domListeners.push([target, type, listener, options]);
|
||||
};
|
||||
|
||||
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
|
||||
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
|
||||
// remove a source that had not been attached yet and leave the attachment to
|
||||
// land afterwards — a preview data source nobody owns. Chain the removal onto
|
||||
// the attachment instead of racing it.
|
||||
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
|
||||
() => null,
|
||||
);
|
||||
// The preview: one dashed rubber band and a dot per vertex, drawn through
|
||||
// the renderer's draw port. Both sets live as long as the tool.
|
||||
const draw = drawOf(viewer);
|
||||
const previewId = `draw-preview:${++previewSerial}`;
|
||||
const previewLines = draw.lines({ id: `${previewId}:line` });
|
||||
const previewPoints = draw.points({ id: `${previewId}:vertices` });
|
||||
countPreviewSets(viewer, 2);
|
||||
let previewReleased = false;
|
||||
const releasePreview = () => {
|
||||
if (previewReleased) return;
|
||||
previewReleased = true;
|
||||
countPreviewSets(viewer, -2);
|
||||
previewLines.dispose();
|
||||
previewPoints.dispose();
|
||||
};
|
||||
/** The canvas the renderer draws in (the viewer's own when none is bound). */
|
||||
const canvasOf = () => sceneCanvasOf(viewer);
|
||||
const requestRender = () => findFrame(viewer)?.requestRender('draw-preview');
|
||||
// Teardown finishes synchronously; `whenSettled()` keeps its promise.
|
||||
const attaching = Promise.resolve();
|
||||
|
||||
const present = () => {
|
||||
const marks = annotations.list?.() || [];
|
||||
@@ -169,70 +193,71 @@ export function initDrawTool({
|
||||
|
||||
// ---- preview ---------------------------------------------------------
|
||||
const vertexPositions = () =>
|
||||
session.vertices.map((v) =>
|
||||
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
|
||||
);
|
||||
const previewLine = dataSource.entities.add({
|
||||
show: false,
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => {
|
||||
if (!session) return [];
|
||||
const pts = vertexPositions();
|
||||
if (cursor && session.shape !== 'pin') pts.push(cursor);
|
||||
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
|
||||
return pts;
|
||||
}, false),
|
||||
width: 3,
|
||||
material: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
}),
|
||||
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
|
||||
dashLength: 16,
|
||||
}),
|
||||
clampToGround: false,
|
||||
},
|
||||
});
|
||||
const syncPreview = () => {
|
||||
session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0));
|
||||
/** The rubber band, from the vertices to the pointer (and closed for an area). */
|
||||
const syncPreviewLine = () => {
|
||||
if (destroyed) return;
|
||||
previewEntities.forEach((e) => dataSource.entities.remove(e));
|
||||
previewEntities.length = 0;
|
||||
if (!session) {
|
||||
previewLine.show = false;
|
||||
setHint(() => drawHint(null));
|
||||
viewer.scene.requestRender();
|
||||
if (!session || session.shape === 'pin') {
|
||||
previewLines.clear();
|
||||
return;
|
||||
}
|
||||
const stroke = Cesium.Color.fromCssColorString(
|
||||
PREVIEW[color] || PREVIEW.primary,
|
||||
);
|
||||
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
|
||||
color: stroke.withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
});
|
||||
previewLine.show = session.shape !== 'pin';
|
||||
for (const v of session.vertices) {
|
||||
previewEntities.push(
|
||||
dataSource.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
|
||||
point: {
|
||||
pixelSize: 8,
|
||||
color: stroke,
|
||||
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
|
||||
outlineWidth: 2,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const pts = vertexPositions();
|
||||
if (cursor) pts.push(cursor);
|
||||
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
|
||||
if (pts.length < 2) {
|
||||
previewLines.clear();
|
||||
return;
|
||||
}
|
||||
previewLines.upsert([
|
||||
{
|
||||
id: 'band',
|
||||
positions: pts,
|
||||
widthPx: 3,
|
||||
// Along the ellipsoid between vertices, as the entity polyline was.
|
||||
mode: 'geodesic',
|
||||
style: {
|
||||
kind: 'dash',
|
||||
color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9),
|
||||
length: 16,
|
||||
},
|
||||
// Dashed behind the surface too, as the band in front of it is.
|
||||
depthFail: {
|
||||
kind: 'dash',
|
||||
color: withAlpha(cssColor(PREVIEW.primary), 0.35),
|
||||
length: 16,
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
const syncPreview = () => {
|
||||
if (destroyed) return;
|
||||
if (!session) {
|
||||
previewPoints.clear();
|
||||
previewLines.clear();
|
||||
setHint(() => drawHint(null));
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
const stroke = cssColor(PREVIEW[color] || PREVIEW.primary);
|
||||
previewPoints.set(
|
||||
session.vertices.map((v, index) => ({
|
||||
id: String(index),
|
||||
pos: { lon: v.lon, lat: v.lat, height: v.height || 0 },
|
||||
pixelSize: 8,
|
||||
color: stroke,
|
||||
outlineColor: [0, 0, 0, 0.6],
|
||||
outlineWidth: 2,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
})),
|
||||
);
|
||||
syncPreviewLine();
|
||||
setHint(() => drawHint(session));
|
||||
viewer.scene.requestRender();
|
||||
requestRender();
|
||||
};
|
||||
|
||||
// ---- vertices from clicks --------------------------------------------
|
||||
const worldAt = (position) => {
|
||||
const canvas = viewer.scene.canvas;
|
||||
const canvas = canvasOf();
|
||||
const w = canvas.clientWidth || canvas.width || 1;
|
||||
const h = canvas.clientHeight || canvas.height || 1;
|
||||
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
|
||||
@@ -260,11 +285,12 @@ export function initDrawTool({
|
||||
};
|
||||
const onMove = (event) => {
|
||||
if (!session || session.shape === 'pin' || destroyed) return;
|
||||
const p = worldAt(event.endPosition);
|
||||
cursor = p
|
||||
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0)
|
||||
: null;
|
||||
viewer.scene.requestRender();
|
||||
// The click's own position is sensor-corrected; the rubber band must
|
||||
// follow the same point the click would place.
|
||||
const p = worldAt(event.pickPosition ?? event.endPosition);
|
||||
cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null;
|
||||
syncPreviewLine();
|
||||
requestRender();
|
||||
};
|
||||
|
||||
// ---- finish / cancel -------------------------------------------------
|
||||
@@ -344,9 +370,7 @@ export function initDrawTool({
|
||||
t.closest('button, a, select, [role="button"], [role="radio"]')
|
||||
)
|
||||
return false;
|
||||
return (
|
||||
t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS'
|
||||
);
|
||||
return t === document.body || t === canvasOf() || t.tagName === 'CANVAS';
|
||||
};
|
||||
const onKey = (event) => {
|
||||
if (!active || destroyed || typingElsewhere(event)) return;
|
||||
@@ -383,18 +407,15 @@ export function initDrawTool({
|
||||
function setActive(next) {
|
||||
if (destroyed || next === active) return active;
|
||||
if (next) {
|
||||
lease = claimPointer(DRAW_POINTER_OWNER);
|
||||
if (!lease) {
|
||||
// Somebody else is using the pointer — possibly an older instance of
|
||||
// this same tool that has not finished tearing down. Say so instead of
|
||||
// half-starting.
|
||||
setHint(() =>
|
||||
t('{owner} is using the pointer — close it first.', {
|
||||
owner: translateKnown(pointerOwnerName(pointerOwner())),
|
||||
}),
|
||||
);
|
||||
return active;
|
||||
}
|
||||
// The newest claim takes over: a tool holding the pointer is told and
|
||||
// turns itself off, and a newer one turns Draw off as if the person had.
|
||||
const claimed = claimPointer(DRAW_POINTER_OWNER, {
|
||||
onLost: () => {
|
||||
if (lease === claimed) setActive(false);
|
||||
},
|
||||
});
|
||||
if (!claimed) return active;
|
||||
lease = claimed;
|
||||
}
|
||||
active = next;
|
||||
present();
|
||||
@@ -416,50 +437,29 @@ export function initDrawTool({
|
||||
}
|
||||
|
||||
function bindSceneHandler() {
|
||||
if (handler) return;
|
||||
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
handler.setInputAction(() => {
|
||||
void finish();
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
|
||||
// single click picks an entity into `viewer.selectedEntity`, the double
|
||||
// click tracks it. Neither goes through a layer, so neither can be fixed by
|
||||
// the shared pointer claim — they have to be borrowed outright for the
|
||||
// session and given back on the way out. Borrowing the single click is what
|
||||
// stops a vertex placed on a contact from also selecting it.
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
savedSingleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
|
||||
savedDoubleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null;
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
if (unbindScene) return;
|
||||
const input = inputFor(viewer);
|
||||
const held = { lease: () => lease };
|
||||
const offs = [
|
||||
input.onPointer('click', onClick, held),
|
||||
input.onPointer('move', onMove, held),
|
||||
input.onPointer('dblclick', () => void finish(), held),
|
||||
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
|
||||
// single click picks an entity into `viewer.selectedEntity`, the double
|
||||
// click tracks it. Neither goes through a layer, so neither yields to the
|
||||
// shared pointer claim — they are suppressed for the session and given
|
||||
// back on the way out. Suppressing the single click is what stops a
|
||||
// vertex placed on a contact from also selecting it.
|
||||
input.suppressStockClicks(),
|
||||
];
|
||||
unbindScene = () => offs.forEach((off) => off());
|
||||
listen(document, 'keydown', onKey, true);
|
||||
}
|
||||
|
||||
function releaseSceneHandler() {
|
||||
if (handler) {
|
||||
handler.destroy();
|
||||
handler = null;
|
||||
}
|
||||
if (savedSingleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedSingleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
);
|
||||
savedSingleClick = null;
|
||||
}
|
||||
if (savedDoubleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedDoubleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
savedDoubleClick = null;
|
||||
}
|
||||
// Drop the keydown listener bound alongside this handler.
|
||||
unbindScene?.();
|
||||
unbindScene = null;
|
||||
// Drop the keydown listener bound alongside the pointer subscriptions.
|
||||
for (let i = domListeners.length - 1; i >= 0; i -= 1) {
|
||||
const [target, type, listener, options] = domListeners[i];
|
||||
if (listener !== onKey) continue;
|
||||
@@ -608,26 +608,18 @@ export function initDrawTool({
|
||||
return {
|
||||
active,
|
||||
destroyed,
|
||||
sceneHandler: Boolean(handler),
|
||||
sceneHandler: Boolean(unbindScene),
|
||||
domListeners: domListeners.length,
|
||||
previewDataSources: countPreviewDataSources(viewer),
|
||||
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
|
||||
// Every live tool's on this viewer: 2 while one tool lives.
|
||||
previewSets: livePreviewSets.get(viewer) ?? 0,
|
||||
previewItems: previewReleased
|
||||
? 0
|
||||
: previewLines.size() + previewPoints.size(),
|
||||
pointerOwner: pointerOwner(),
|
||||
// The viewer's OWN click actions. While a session is open both are
|
||||
// borrowed (absent here); after it closes both are back. A harness can
|
||||
// compare the restored functions by identity with what it captured
|
||||
// before, which is the only way to prove they were given back rather
|
||||
// than replaced.
|
||||
stockSingleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
),
|
||||
),
|
||||
stockDoubleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
),
|
||||
),
|
||||
// The viewer's own select and follow, which the input port runs: off
|
||||
// while a session is open, back on after it closes.
|
||||
stockSingleClick: inputFor(viewer).stockEnabled('select'),
|
||||
stockDoubleClick: inputFor(viewer).stockEnabled('dblclickFollow'),
|
||||
};
|
||||
},
|
||||
/** Resolves once every deferred teardown step has run. */
|
||||
@@ -649,18 +641,7 @@ export function initDrawTool({
|
||||
for (const [target, type, listener, options] of domListeners.splice(0)) {
|
||||
target.removeEventListener(type, listener, options);
|
||||
}
|
||||
previewEntities.length = 0;
|
||||
dataSource.entities.removeAll();
|
||||
// Wait for the pending add() before removing: a destroy() in the same
|
||||
// tick as init would otherwise remove nothing and let the attachment land
|
||||
// behind it.
|
||||
attaching = attaching.then(() => {
|
||||
try {
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
} catch {
|
||||
/* viewer already disposed — nothing to detach from */
|
||||
}
|
||||
});
|
||||
releasePreview();
|
||||
document.body.classList.remove('gev-drawing');
|
||||
hint = '';
|
||||
present();
|
||||
@@ -672,13 +653,7 @@ export function initDrawTool({
|
||||
return api;
|
||||
}
|
||||
|
||||
/** How many draw previews are attached — more than one means a leaked tool. */
|
||||
function countPreviewDataSources(viewer) {
|
||||
const sources = viewer?.dataSources;
|
||||
if (!sources) return 0;
|
||||
let found = 0;
|
||||
for (let index = 0; index < sources.length; index += 1) {
|
||||
if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1;
|
||||
}
|
||||
return found;
|
||||
/** `color` at `alpha`. */
|
||||
function withAlpha(color, alpha) {
|
||||
return [color[0], color[1], color[2], alpha];
|
||||
}
|
||||
@@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => {
|
||||
// rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels
|
||||
// against a keyless server; this stops the constant being narrowed again.
|
||||
const renderer = read('src/annotations/worldAnnotationRenderer.js');
|
||||
assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/);
|
||||
assert.doesNotMatch(
|
||||
renderer,
|
||||
/classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/,
|
||||
);
|
||||
assert.match(renderer, /const CLAMP_TO = 'both';/);
|
||||
assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/);
|
||||
});
|
||||
|
||||
test('the draw modules are registered for formatting and boundary checks', () => {
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
releasePointer,
|
||||
resetPointerOwnership,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
/* ── DOM doubles ───────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -68,9 +70,17 @@ class FakeElement {
|
||||
}
|
||||
closest(selector) {
|
||||
// Only what the tool asks: "am I inside an activatable control?"
|
||||
const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]'];
|
||||
const activatable = [
|
||||
'button',
|
||||
'a',
|
||||
'select',
|
||||
'[role="button"]',
|
||||
'[role="radio"]',
|
||||
];
|
||||
if (!activatable.some((part) => selector.includes(part))) return null;
|
||||
return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT'
|
||||
return this.tagName === 'BUTTON' ||
|
||||
this.tagName === 'A' ||
|
||||
this.tagName === 'SELECT'
|
||||
? this
|
||||
: null;
|
||||
}
|
||||
@@ -143,39 +153,22 @@ function fakeViewer() {
|
||||
setInputAction: (action, type) => actions.set(type, action),
|
||||
removeInputAction: (type) => actions.delete(type),
|
||||
};
|
||||
const attached = [];
|
||||
const pendingAdds = [];
|
||||
const dataSources = {
|
||||
get length() {
|
||||
return attached.length;
|
||||
},
|
||||
get: (index) => attached[index],
|
||||
add(source) {
|
||||
// Cesium resolves this on a later tick — the whole point of finding 7.
|
||||
const promise = Promise.resolve().then(() => {
|
||||
attached.push(source);
|
||||
return source;
|
||||
});
|
||||
pendingAdds.push(promise);
|
||||
return promise;
|
||||
},
|
||||
remove(source) {
|
||||
const at = attached.indexOf(source);
|
||||
if (at >= 0) attached.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
};
|
||||
return {
|
||||
scene: { canvas, requestRender() {} },
|
||||
screenSpaceEventHandler: stockHandler,
|
||||
dataSources,
|
||||
_attached: attached,
|
||||
_actions: actions,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeAnnotations() {
|
||||
const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] };
|
||||
const calls = {
|
||||
annotate: [],
|
||||
clear: 0,
|
||||
restyle: [],
|
||||
setHidden: [],
|
||||
frame: [],
|
||||
remove: [],
|
||||
};
|
||||
const marks = [];
|
||||
const listeners = new Set();
|
||||
const changed = () => listeners.forEach((listener) => listener());
|
||||
@@ -223,10 +216,21 @@ function fakeAnnotations() {
|
||||
}
|
||||
|
||||
/** Stand up a tool against fresh doubles, with globals restored afterwards. */
|
||||
function harness({ navigation = null, markActions = [] } = {}) {
|
||||
function harness({
|
||||
navigation = null,
|
||||
beforeInput = () => {},
|
||||
markActions = [],
|
||||
} = {}) {
|
||||
resetPointerOwnership();
|
||||
const { byId, documentDouble } = fakeDom();
|
||||
const viewer = fakeViewer();
|
||||
// The viewer's own actions are bound before its input port takes them.
|
||||
beforeInput(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
// The renderer the tool draws its preview with, drawing in the viewer's canvas.
|
||||
const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, {
|
||||
canvas: viewer.scene.canvas,
|
||||
});
|
||||
const annotations = fakeAnnotations();
|
||||
const previousDocument = globalThis.document;
|
||||
const previousWindow = globalThis.window;
|
||||
@@ -250,6 +254,7 @@ function harness({ navigation = null, markActions = [] } = {}) {
|
||||
tool,
|
||||
shown,
|
||||
viewer,
|
||||
draw,
|
||||
annotations,
|
||||
byId,
|
||||
documentDouble,
|
||||
@@ -257,7 +262,10 @@ function harness({ navigation = null, markActions = [] } = {}) {
|
||||
controls,
|
||||
/** A control's change, as the view sends it. */
|
||||
act: (name, ...args) => controls.actions?.[name]?.(...args),
|
||||
input,
|
||||
restore() {
|
||||
input.destroy();
|
||||
unbindDraw();
|
||||
resetPointerOwnership();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
@@ -288,23 +296,42 @@ test('turning Draw on takes a lease and turning it off gives it back', async ()
|
||||
}
|
||||
});
|
||||
|
||||
test('Draw refuses to start when something else holds the pointer', async () => {
|
||||
test('Draw takes the pointer from another tool, which is told', async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
const other = claimPointer('directions');
|
||||
let lost = 0;
|
||||
claimPointer('directions', { onLost: () => (lost += 1) });
|
||||
h.act('toggleDraw');
|
||||
assert.equal(h.tool.active, false, 'it must not half-start');
|
||||
assert.equal(pointerOwner(), 'directions', 'and must not steal the claim');
|
||||
// Named by its tool, not by the internal owner id.
|
||||
assert.equal(
|
||||
h.shown.view.hint,
|
||||
'Directions is using the pointer — close it first.',
|
||||
);
|
||||
assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound');
|
||||
assert.equal(h.tool.active, true, 'the newest claim takes over');
|
||||
assert.equal(pointerOwner(), 'draw');
|
||||
assert.equal(lost, 1, 'the other tool is told once');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('Draw turns off, as if toggled off, when a newer tool takes the pointer', async () => {
|
||||
const h = harness({
|
||||
beforeInput(viewer) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(() => {}, LEFT_CLICK);
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.act('toggleDraw');
|
||||
assert.equal(h.tool.diagnostics().stockSingleClick, false);
|
||||
assert.ok(h.tool.addVertex(10, 20), 'a shape is under way');
|
||||
const other = claimPointer('directions');
|
||||
assert.equal(h.tool.active, false);
|
||||
assert.equal(h.tool.session, null, 'the half-drawn shape is dropped');
|
||||
assert.equal(h.shown.view.active, false, 'the Draw control reads off');
|
||||
const after = h.tool.diagnostics();
|
||||
assert.equal(after.sceneHandler, false, 'its subscriptions are gone');
|
||||
assert.equal(after.stockSingleClick, true, 'the stock clicks are back');
|
||||
assert.equal(after.previewItems, 0, 'the preview is cleared');
|
||||
assert.equal(pointerOwner(), 'directions', 'the newer tool keeps it');
|
||||
releasePointer(other);
|
||||
h.act('toggleDraw');
|
||||
assert.equal(h.tool.active, true, 'and it starts once the pointer is free');
|
||||
assert.equal(h.tool.active, true, 'and it turns on again when asked');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
@@ -336,30 +363,36 @@ test('a destroyed instance cannot free the pointer its replacement holds', async
|
||||
}
|
||||
});
|
||||
|
||||
test('both stock viewer click actions are borrowed for the session and given back', async () => {
|
||||
const h = harness();
|
||||
test('both stock viewer click actions are held off for the session and given back', async () => {
|
||||
const stockClick = () => 'viewer picks and selects';
|
||||
const stockDouble = () => 'viewer tracks';
|
||||
const h = harness({
|
||||
beforeInput(viewer) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
stockDouble,
|
||||
LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
},
|
||||
});
|
||||
try {
|
||||
const stockClick = () => 'viewer picks and selects';
|
||||
const stockDouble = () => 'viewer tracks';
|
||||
h.viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
|
||||
h.viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK);
|
||||
|
||||
assert.equal(h.input.stockEnabled('select'), true);
|
||||
h.act('toggleDraw');
|
||||
assert.equal(
|
||||
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
|
||||
undefined,
|
||||
h.input.stockEnabled('select'),
|
||||
false,
|
||||
"the viewer's own selecting click must not run while drawing",
|
||||
);
|
||||
assert.equal(
|
||||
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(h.input.stockEnabled('dblclickFollow'), false);
|
||||
|
||||
h.act('toggleDraw');
|
||||
assert.equal(h.input.stockEnabled('select'), true);
|
||||
assert.equal(h.input.stockEnabled('dblclickFollow'), true);
|
||||
h.input.destroy();
|
||||
assert.equal(
|
||||
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
|
||||
stockClick,
|
||||
'the exact function is restored, not a replacement',
|
||||
'the exact function goes back to the viewer, not a replacement',
|
||||
);
|
||||
assert.equal(
|
||||
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
|
||||
@@ -380,20 +413,34 @@ test('Enter finishes from the canvas and the label field, never from a focused b
|
||||
h.tool.addVertex(-97.74, 30.27);
|
||||
|
||||
// Enter while the Clear button has keyboard focus means "press Clear".
|
||||
h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') });
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Enter',
|
||||
target: h.element('draw-clear'),
|
||||
});
|
||||
await Promise.resolve();
|
||||
assert.equal(
|
||||
h.annotations.calls.annotate.length,
|
||||
0,
|
||||
'a focused button keeps its own Enter',
|
||||
);
|
||||
assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched');
|
||||
assert.equal(
|
||||
h.tool.session.vertices.length,
|
||||
3,
|
||||
'and the shape is untouched',
|
||||
);
|
||||
|
||||
// Enter from the page body (the canvas has focus in practice) finishes it.
|
||||
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Enter',
|
||||
target: h.documentDouble.body,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes');
|
||||
assert.equal(
|
||||
h.annotations.calls.annotate.length,
|
||||
1,
|
||||
'Enter on the map finishes',
|
||||
);
|
||||
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
|
||||
} finally {
|
||||
h.restore();
|
||||
@@ -429,21 +476,29 @@ test('the live preview hangs at the height the click landed on', async () => {
|
||||
h.tool.addVertex(-97.75, 30.26, 187.5);
|
||||
h.tool.addVertex(-97.74, 30.26, 212.25);
|
||||
|
||||
await h.tool.whenSettled();
|
||||
const source = h.viewer._attached[0] ?? null;
|
||||
assert.ok(source, 'the preview data source is attached');
|
||||
const points = source.entities.values.filter((entity) => entity.point);
|
||||
assert.equal(points.length, 2, 'one preview dot per vertex');
|
||||
const heights = points.map((entity) => {
|
||||
const position = entity.position.getValue(Cesium.JulianDate.now());
|
||||
return Cesium.Cartographic.fromCartesian(position).height;
|
||||
});
|
||||
const dots = [...h.draw.sets.values()].find(
|
||||
(set) => !set.disposed && set.kind === 'points',
|
||||
);
|
||||
assert.equal(dots.items.size, 2, 'one preview dot per vertex');
|
||||
const heights = [...dots.items.values()].map((item) => item.pos.height);
|
||||
const band = [...h.draw.sets.values()]
|
||||
.find((set) => !set.disposed && set.kind === 'lines')
|
||||
.items.get('band');
|
||||
assert.equal(
|
||||
band.positions.length,
|
||||
2,
|
||||
'the rubber band joins the vertices',
|
||||
);
|
||||
assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped');
|
||||
assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`);
|
||||
assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`);
|
||||
|
||||
// …and the finished shape is still flattened, deliberately: the renderer
|
||||
// drapes, so a height carried further would be discarded out of sight.
|
||||
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Enter',
|
||||
target: h.documentDouble.body,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const spec = h.annotations.calls.annotate[0].specs[0];
|
||||
@@ -456,17 +511,60 @@ test('the live preview hangs at the height the click landed on', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('destroy in the same tick as init still removes the preview data source', async () => {
|
||||
test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
// Nothing has been attached yet — dataSources.add() resolves later.
|
||||
assert.equal(h.viewer._attached.length, 0, 'the add is still pending');
|
||||
await h.tool.destroy();
|
||||
await Promise.resolve();
|
||||
const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
|
||||
const band = () =>
|
||||
sets()
|
||||
.find((set) => set.kind === 'lines')
|
||||
.items.get('band');
|
||||
h.act('toggleDraw');
|
||||
h.tool.setShape('area');
|
||||
h.tool.addVertex(-97.75, 30.26);
|
||||
assert.equal(band(), undefined, 'one vertex and no pointer draw no band');
|
||||
h.tool.addVertex(-97.74, 30.26);
|
||||
h.tool.addVertex(-97.74, 30.27);
|
||||
assert.equal(
|
||||
h.viewer._attached.length,
|
||||
band().positions.length,
|
||||
4,
|
||||
'an area of three closes back to its first vertex',
|
||||
);
|
||||
assert.deepEqual(band().positions[3], band().positions[0]);
|
||||
|
||||
h.tool.setColor('red');
|
||||
assert.deepEqual(
|
||||
band().style.color,
|
||||
[1, 107 / 255, 107 / 255, 0.9],
|
||||
'the band takes the colour',
|
||||
);
|
||||
assert.deepEqual(
|
||||
band().depthFail,
|
||||
{ kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 },
|
||||
'behind the surface it stays the primary colour, dashed, as before',
|
||||
);
|
||||
assert.equal(band().style.kind, 'dash');
|
||||
assert.equal(band().style.length, 16);
|
||||
assert.equal(band().widthPx, 3);
|
||||
|
||||
h.tool.setShape('pin');
|
||||
assert.equal(band(), undefined, 'a pin has no rubber band');
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('destroy in the same tick as init disposes the preview sets', async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
|
||||
assert.equal(live().length, 2, 'the rubber band and the vertex dots');
|
||||
await h.tool.destroy();
|
||||
assert.equal(live().length, 0, 'nothing is left drawn behind the teardown');
|
||||
assert.equal(
|
||||
h.tool.diagnostics().previewSets,
|
||||
0,
|
||||
'the preview must not be left attached behind the teardown',
|
||||
'no live tool draws a preview',
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
@@ -490,7 +588,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
|
||||
assert.equal(isPointerFree(), true, 'the pointer is free');
|
||||
const after = h.tool.diagnostics();
|
||||
assert.equal(after.destroyed, true);
|
||||
assert.equal(after.sceneHandler, false, 'the Cesium handler is gone');
|
||||
assert.equal(
|
||||
after.sceneHandler,
|
||||
false,
|
||||
'the pointer subscriptions are gone',
|
||||
);
|
||||
assert.equal(after.domListeners, 0, 'every DOM listener came off');
|
||||
assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown');
|
||||
assert.equal(h.controls.actions, null, 'and the controls are disconnected');
|
||||
@@ -499,8 +601,12 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
|
||||
stockClick,
|
||||
'the viewer got its selecting click back',
|
||||
);
|
||||
assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached');
|
||||
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
|
||||
assert.equal(after.previewSets, 0, 'the preview sets are disposed');
|
||||
assert.equal(
|
||||
h.annotations.listeners.size,
|
||||
0,
|
||||
'and it no longer follows the board',
|
||||
);
|
||||
|
||||
// Idempotent: a second destroy is harmless.
|
||||
await h.tool.destroy();
|
||||
@@ -519,7 +625,11 @@ test('Clear wipes the board and the shape in progress', async () => {
|
||||
|
||||
h.act('clearDraw');
|
||||
assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed');
|
||||
assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress');
|
||||
assert.equal(
|
||||
h.tool.session.vertices.length,
|
||||
0,
|
||||
'and so is the shape in progress',
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
@@ -533,7 +643,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it
|
||||
h.act('setDrawColor', 'amber');
|
||||
assert.deepEqual(
|
||||
{ ...h.shown.view, hint: undefined },
|
||||
{ active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] },
|
||||
{
|
||||
active: true,
|
||||
shape: 'line',
|
||||
color: 'amber',
|
||||
hint: undefined,
|
||||
marks: [],
|
||||
},
|
||||
'the view shows what the controls chose',
|
||||
);
|
||||
h.act('setDrawColor', 'purple');
|
||||
@@ -545,7 +661,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it
|
||||
assert.equal(h.tool.session.vertices.length, 0);
|
||||
h.tool.addVertex(-97.75, 30.26);
|
||||
h.tool.addVertex(-97.74, 30.26);
|
||||
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Enter',
|
||||
target: h.documentDouble.body,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const spec = h.annotations.calls.annotate[0].specs[0];
|
||||
@@ -570,12 +689,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
|
||||
try {
|
||||
const board = h.annotations;
|
||||
board.marks.push(
|
||||
{ id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false },
|
||||
{ id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false },
|
||||
{
|
||||
id: 'a1',
|
||||
type: 'route',
|
||||
manual: true,
|
||||
name: null,
|
||||
label: '950 m',
|
||||
color: 'amber',
|
||||
hidden: false,
|
||||
},
|
||||
{
|
||||
id: 'a2',
|
||||
type: 'pin',
|
||||
manual: false,
|
||||
label: 'Voice pin',
|
||||
color: 'primary',
|
||||
hidden: false,
|
||||
},
|
||||
);
|
||||
board.changed();
|
||||
assert.deepEqual(
|
||||
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })),
|
||||
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({
|
||||
id,
|
||||
placeholder,
|
||||
hidden,
|
||||
})),
|
||||
[{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }],
|
||||
'only hand-drawn marks are listed, an unnamed line by its length',
|
||||
);
|
||||
@@ -590,7 +728,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
|
||||
]);
|
||||
assert.deepEqual(board.calls.setHidden, [['a1', true]]);
|
||||
assert.deepEqual(board.calls.frame, ['a1']);
|
||||
assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy');
|
||||
assert.deepEqual(
|
||||
navigations,
|
||||
['drawing'],
|
||||
'fly-to goes through the navigation policy',
|
||||
);
|
||||
assert.deepEqual(board.calls.remove, ['a1']);
|
||||
assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark');
|
||||
} finally {
|
||||
@@ -598,7 +740,7 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
|
||||
}
|
||||
});
|
||||
|
||||
test('an application\'s row actions show on the shapes they are for and run with the shape', async () => {
|
||||
test("row actions given to the tool show on the shapes they are for and run with the shape", async () => {
|
||||
const ran = [];
|
||||
const h = harness({
|
||||
markActions: [
|
||||
@@ -622,30 +764,102 @@ test('an application\'s row actions show on the shapes they are for and run with
|
||||
try {
|
||||
const board = h.annotations;
|
||||
board.marks.push(
|
||||
{ id: 'r1', type: 'area', manual: true, name: 'Strait', color: 'primary', hidden: false, ring: [[29, 41], [29.1, 41], [29.1, 41.1]] },
|
||||
{ id: 'l1', type: 'route', manual: true, name: null, label: '9 km', color: 'amber', hidden: false, path: [{ lon: 29, lat: 41.05, height: 0 }, { lon: 29.1, lat: 41.05, height: 0 }] },
|
||||
{ id: 'p1', type: 'pin', manual: true, name: 'Camp', color: 'red', hidden: false },
|
||||
{
|
||||
id: 'r1',
|
||||
type: 'area',
|
||||
manual: true,
|
||||
name: 'Strait',
|
||||
color: 'primary',
|
||||
hidden: false,
|
||||
ring: [
|
||||
[29, 41],
|
||||
[29.1, 41],
|
||||
[29.1, 41.1],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'l1',
|
||||
type: 'route',
|
||||
manual: true,
|
||||
name: null,
|
||||
label: '9 km',
|
||||
color: 'amber',
|
||||
hidden: false,
|
||||
path: [
|
||||
{ lon: 29, lat: 41.05, height: 0 },
|
||||
{ lon: 29.1, lat: 41.05, height: 0 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p1',
|
||||
type: 'pin',
|
||||
manual: true,
|
||||
name: 'Camp',
|
||||
color: 'red',
|
||||
hidden: false,
|
||||
},
|
||||
);
|
||||
board.changed();
|
||||
assert.deepEqual(
|
||||
h.shown.view.marks.map(({ id, actions }) => [id, actions]),
|
||||
[
|
||||
['r1', [
|
||||
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
|
||||
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
|
||||
]],
|
||||
[
|
||||
'r1',
|
||||
[
|
||||
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
|
||||
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
|
||||
],
|
||||
],
|
||||
['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]],
|
||||
['p1', []],
|
||||
],
|
||||
);
|
||||
assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true);
|
||||
assert.equal(h.act('runDrawMarkAction', 'l1', 'measure'), false, 'a line is not offered an area action');
|
||||
assert.equal(
|
||||
h.act('runDrawMarkAction', 'l1', 'measure'),
|
||||
false,
|
||||
'a line is not offered an area action',
|
||||
);
|
||||
assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false);
|
||||
assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false);
|
||||
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
|
||||
assert.deepEqual(ran, [
|
||||
['tag', { id: 'l1', shape: 'line', name: '', title: 'Line · 9 km', geometry: { type: 'LineString', coordinates: [[29, 41.05], [29.1, 41.05]] } }],
|
||||
['measure', { id: 'r1', shape: 'area', name: 'Strait', title: 'Strait', geometry: { type: 'Polygon', coordinates: [[[29, 41], [29.1, 41], [29.1, 41.1], [29, 41]]] } }],
|
||||
[
|
||||
'tag',
|
||||
{
|
||||
id: 'l1',
|
||||
shape: 'line',
|
||||
name: '',
|
||||
title: 'Line · 9 km',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[29, 41.05],
|
||||
[29.1, 41.05],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
'measure',
|
||||
{
|
||||
id: 'r1',
|
||||
shape: 'area',
|
||||
name: 'Strait',
|
||||
title: 'Strait',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[29, 41],
|
||||
[29.1, 41],
|
||||
[29.1, 41.1],
|
||||
[29, 41],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
]);
|
||||
} finally {
|
||||
h.restore();
|
||||
@@ -655,16 +869,40 @@ test('an application\'s row actions show on the shapes they are for and run with
|
||||
test('an action that throws is reported and leaves the row alone', async () => {
|
||||
const h = harness({
|
||||
markActions: [
|
||||
{ id: 'boom', icon: 'bolt', label: () => { throw new Error('label'); }, shapes: ['area'], run: () => { throw new Error('run'); } },
|
||||
{
|
||||
id: 'boom',
|
||||
icon: 'bolt',
|
||||
label: () => {
|
||||
throw new Error('label');
|
||||
},
|
||||
shapes: ['area'],
|
||||
run: () => {
|
||||
throw new Error('run');
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const warn = console.warn;
|
||||
const warned = [];
|
||||
console.warn = (...args) => warned.push(args[0]);
|
||||
try {
|
||||
h.annotations.marks.push({ id: 'r1', type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] });
|
||||
h.annotations.marks.push({
|
||||
id: 'r1',
|
||||
type: 'area',
|
||||
manual: true,
|
||||
name: null,
|
||||
color: 'primary',
|
||||
hidden: false,
|
||||
ring: [
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
],
|
||||
});
|
||||
h.annotations.changed();
|
||||
assert.deepEqual(h.shown.view.marks[0].actions, [{ id: 'boom', icon: 'bolt', label: 'boom' }]);
|
||||
assert.deepEqual(h.shown.view.marks[0].actions, [
|
||||
{ id: 'boom', icon: 'bolt', label: 'boom' },
|
||||
]);
|
||||
assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false);
|
||||
assert.deepEqual(warned, ['[draw] boom failed']);
|
||||
} finally {
|
||||
@@ -673,7 +911,7 @@ test('an action that throws is reported and leaves the row alone', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('what a row action answers is its row\'s note; the row is busy until then, and a removed shape drops it', async () => {
|
||||
test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => {
|
||||
const pending = [];
|
||||
const h = harness({
|
||||
markActions: [
|
||||
@@ -682,34 +920,73 @@ test('what a row action answers is its row\'s note; the row is busy until then,
|
||||
icon: 'straighten',
|
||||
label: (name) => `Measure ${name}`,
|
||||
shapes: ['area'],
|
||||
run: () => new Promise((resolve, reject) => pending.push({ resolve, reject })),
|
||||
run: () =>
|
||||
new Promise((resolve, reject) => pending.push({ resolve, reject })),
|
||||
},
|
||||
{
|
||||
id: 'now',
|
||||
icon: 'bolt',
|
||||
label: () => 'Now',
|
||||
shapes: ['area'],
|
||||
run: () => ' 12 km² ',
|
||||
},
|
||||
{
|
||||
id: 'long',
|
||||
icon: 'notes',
|
||||
label: () => 'Long',
|
||||
shapes: ['area'],
|
||||
run: () => `${'word '.repeat(60)}end`,
|
||||
},
|
||||
{ id: 'now', icon: 'bolt', label: () => 'Now', shapes: ['area'], run: () => ' 12 km² ' },
|
||||
{ id: 'long', icon: 'notes', label: () => 'Long', shapes: ['area'], run: () => `${'word '.repeat(60)}end` },
|
||||
],
|
||||
});
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const board = h.annotations;
|
||||
const area = (id) => ({ id, type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] });
|
||||
const area = (id) => ({
|
||||
id,
|
||||
type: 'area',
|
||||
manual: true,
|
||||
name: null,
|
||||
color: 'primary',
|
||||
hidden: false,
|
||||
ring: [
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
],
|
||||
});
|
||||
board.marks.push(area('r1'), area('r2'));
|
||||
board.changed();
|
||||
const row = (id) => h.shown.view.marks.find((entry) => entry.id === id);
|
||||
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true);
|
||||
assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']);
|
||||
h.act('runDrawMarkAction', 'r1', 'long');
|
||||
assert.ok(row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), 'a long note is cut at a word');
|
||||
assert.ok(
|
||||
row('r1').note.length <= 200 && row('r1').note.endsWith('word…'),
|
||||
'a long note is cut at a word',
|
||||
);
|
||||
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
|
||||
assert.deepEqual([row('r1').busy, row('r1').note], [true, '']);
|
||||
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), false, 'a busy row takes no second press');
|
||||
assert.equal(
|
||||
h.act('runDrawMarkAction', 'r1', 'now'),
|
||||
false,
|
||||
'a busy row takes no second press',
|
||||
);
|
||||
pending[0].resolve('412 km², 38 km of edge');
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual([row('r1').busy, row('r1').note], [false, '412 km², 38 km of edge']);
|
||||
assert.deepEqual(
|
||||
[row('r1').busy, row('r1').note],
|
||||
[false, '412 km², 38 km of edge'],
|
||||
);
|
||||
h.act('runDrawMarkAction', 'r1', 'measure');
|
||||
pending[1].reject(new Error('refused'));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual([row('r1').busy, row('r1').note], [false, ''], 'a failure clears the note');
|
||||
assert.deepEqual(
|
||||
[row('r1').busy, row('r1').note],
|
||||
[false, ''],
|
||||
'a failure clears the note',
|
||||
);
|
||||
h.act('runDrawMarkAction', 'r2', 'measure');
|
||||
board.marks.splice(1, 1);
|
||||
board.changed();
|
||||
@@ -718,7 +995,11 @@ test('what a row action answers is its row\'s note; the row is busy until then,
|
||||
assert.equal(row('r2'), undefined);
|
||||
board.marks.push(area('r2'));
|
||||
board.changed();
|
||||
assert.deepEqual([row('r2').busy, row('r2').note], [false, ''], 'a late answer never reaches a shape that went');
|
||||
assert.deepEqual(
|
||||
[row('r2').busy, row('r2').note],
|
||||
[false, ''],
|
||||
'a late answer never reaches a shape that went',
|
||||
);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
h.restore();
|
||||
@@ -731,30 +1012,49 @@ test('Backspace on the page removes the last vertex', () => {
|
||||
h.act('toggleDraw');
|
||||
h.tool.addVertex(-97.75, 30.26);
|
||||
h.tool.addVertex(-97.74, 30.26);
|
||||
h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body });
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Backspace',
|
||||
target: h.documentDouble.body,
|
||||
});
|
||||
assert.equal(h.tool.session.vertices.length, 1);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('keys on the shape list are the list\'s, not the drawing\'s', async () => {
|
||||
test("keys on the shape list are the list's, not the drawing's", async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
const listButton = new FakeElement('BUTTON');
|
||||
listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null);
|
||||
listButton.closest = (selector) =>
|
||||
selector === '#draw-mark-list' ? {} : null;
|
||||
const elsewhere = new FakeElement('INPUT', 'location-search');
|
||||
h.act('toggleDraw');
|
||||
h.tool.addVertex(-97.75, 30.26);
|
||||
h.tool.addVertex(-97.74, 30.26);
|
||||
h.documentDouble.emit('keydown', { key: 'Escape', target: listButton });
|
||||
assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape');
|
||||
assert.equal(
|
||||
h.tool.session.vertices.length,
|
||||
2,
|
||||
'Escape in the list keeps the shape',
|
||||
);
|
||||
assert.equal(h.tool.active, true, 'and keeps Draw on');
|
||||
h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere });
|
||||
await Promise.resolve();
|
||||
assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter');
|
||||
h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body });
|
||||
assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape');
|
||||
assert.equal(
|
||||
h.annotations.calls.annotate.length,
|
||||
0,
|
||||
'another field keeps its Enter',
|
||||
);
|
||||
h.documentDouble.emit('keydown', {
|
||||
key: 'Escape',
|
||||
target: h.documentDouble.body,
|
||||
});
|
||||
assert.equal(
|
||||
h.tool.session.vertices.length,
|
||||
0,
|
||||
'Escape on the page drops the open shape',
|
||||
);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import { createPinia } from 'pinia';
|
||||
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
|
||||
import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
|
||||
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
|
||||
import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
|
||||
|
||||
/** A hybrid renderer whose screen board is presented to its own store. */
|
||||
function hybridWithBoard(viewer) {
|
||||
@@ -89,11 +92,41 @@ function installBrowserGlobals(t) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `viewer` with the fake scene's camera, query, frame and draw ports and the
|
||||
* fake credits bound over it as one renderer.
|
||||
*/
|
||||
function withScenePorts(viewer) {
|
||||
const { unbind, ...ports } = bindFakeCesiumScene(viewer);
|
||||
unbind();
|
||||
bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) });
|
||||
return ports.draw;
|
||||
}
|
||||
|
||||
/** What the world renderer draws, each item of its live sets (of `kind`). */
|
||||
function worldItems(draw, kind) {
|
||||
const items = [];
|
||||
for (const record of draw.sets.values())
|
||||
if (
|
||||
!record.disposed &&
|
||||
record.spec.id.startsWith('annotations:') &&
|
||||
(!kind || record.kind === kind)
|
||||
)
|
||||
items.push(...record.items.values());
|
||||
return items;
|
||||
}
|
||||
|
||||
/** Surface heights the scene samples: `height(lon, lat)` in degrees. */
|
||||
function sampleHeights(scene, height) {
|
||||
scene.sampleHeightSupported = true;
|
||||
scene.sampleHeight = (carto) =>
|
||||
height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude));
|
||||
}
|
||||
|
||||
/** A viewer whose scene/camera is just enough for both sub-renderers. */
|
||||
function fakeViewer(lon, lat) {
|
||||
const credits = new Set();
|
||||
const camera = cameraLookingAt(lon, lat);
|
||||
const dataSources = [];
|
||||
const frames = controlledFrames();
|
||||
const scene = {
|
||||
camera,
|
||||
@@ -107,31 +140,19 @@ function fakeViewer(lon, lat) {
|
||||
scene.renderRequests += 1;
|
||||
},
|
||||
};
|
||||
return {
|
||||
dataSources,
|
||||
frames,
|
||||
viewer: {
|
||||
credits,
|
||||
creditDisplay: {
|
||||
addStaticCredit: (credit) => credits.add(credit),
|
||||
removeStaticCredit: (credit) => credits.delete(credit),
|
||||
},
|
||||
scene,
|
||||
camera,
|
||||
trackedEntity: null,
|
||||
dataSources: {
|
||||
add(dataSource) {
|
||||
dataSources.push(dataSource);
|
||||
return dataSource;
|
||||
},
|
||||
remove(dataSource) {
|
||||
const index = dataSources.indexOf(dataSource);
|
||||
if (index >= 0) dataSources.splice(index, 1);
|
||||
return index >= 0;
|
||||
},
|
||||
},
|
||||
const viewer = {
|
||||
credits,
|
||||
creditDisplay: {
|
||||
addStaticCredit: (credit) => credits.add(credit),
|
||||
removeStaticCredit: (credit) => credits.delete(credit),
|
||||
},
|
||||
scene,
|
||||
camera,
|
||||
canvas: scene.canvas,
|
||||
trackedEntity: null,
|
||||
};
|
||||
const draw = withScenePorts(viewer);
|
||||
return { draw, frames, viewer };
|
||||
}
|
||||
|
||||
function controlledFrames() {
|
||||
@@ -192,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
});
|
||||
|
||||
const camera = cameraLookingAt(-99, 31);
|
||||
const dataSources = [];
|
||||
const frames = controlledFrames();
|
||||
const scene = {
|
||||
camera,
|
||||
@@ -206,19 +226,12 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
const viewer = {
|
||||
scene,
|
||||
camera,
|
||||
canvas: scene.canvas,
|
||||
trackedEntity: null,
|
||||
dataSources: {
|
||||
add(dataSource) {
|
||||
dataSources.push(dataSource);
|
||||
return dataSource;
|
||||
},
|
||||
remove(dataSource) {
|
||||
const index = dataSources.indexOf(dataSource);
|
||||
if (index >= 0) dataSources.splice(index, 1);
|
||||
return index >= 0;
|
||||
},
|
||||
},
|
||||
};
|
||||
// The screen board projects through the renderer's camera and query; the
|
||||
// world renderer draws through its draw port.
|
||||
const { draw } = bindFakeCesiumScene(viewer);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const anno = {
|
||||
id: 'anno-hybrid-fb3',
|
||||
@@ -235,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
renderer.add(anno);
|
||||
const [before] = annotationGroups(store);
|
||||
assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2);
|
||||
assert.equal(dataSources.length, 1);
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
|
||||
const ring = [
|
||||
[-106, 25],
|
||||
@@ -268,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1));
|
||||
assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1));
|
||||
assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned');
|
||||
assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline');
|
||||
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1);
|
||||
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1);
|
||||
assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy');
|
||||
assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline');
|
||||
assert.equal(worldItems(draw, 'shapes').length, 1);
|
||||
assert.equal(worldItems(draw, 'lines').length, 1);
|
||||
assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy');
|
||||
const outer = [
|
||||
[-99, 31],
|
||||
[-98.999, 31],
|
||||
@@ -298,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
buildingHeight: 20,
|
||||
};
|
||||
const completion = renderer.add(building);
|
||||
assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes');
|
||||
assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes');
|
||||
for (let frame = 0; frame < 8; frame += 1) frames.emit();
|
||||
assert.equal((await completion).status, 'installed');
|
||||
const added = dataSources[0].entities.values.slice(2);
|
||||
const fills = added.filter(
|
||||
(entity) => entity.polygon && entity.polygon.fill?.getValue() !== false,
|
||||
);
|
||||
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
|
||||
assert.equal(
|
||||
fills.length,
|
||||
2,
|
||||
'every building part gets a classification volume',
|
||||
'every building part gets a volume',
|
||||
);
|
||||
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1);
|
||||
assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0);
|
||||
assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole');
|
||||
assert.equal(fills[1].geometry.rings.length, 1);
|
||||
assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour');
|
||||
assert.equal(
|
||||
fills[0].polygon.material,
|
||||
fills[1].polygon.material,
|
||||
'parts share the fill material',
|
||||
);
|
||||
assert.equal(
|
||||
added.filter((entity) => entity.polyline).length,
|
||||
worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length,
|
||||
3,
|
||||
'all outer and hole outlines are retained',
|
||||
);
|
||||
renderer.remove(building);
|
||||
assert.equal(
|
||||
dataSources[0].entities.values.length,
|
||||
worldItems(draw).length,
|
||||
2,
|
||||
'multipart removal leaves only the earlier area',
|
||||
);
|
||||
@@ -341,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
|
||||
|
||||
test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => {
|
||||
installBrowserGlobals(t);
|
||||
const { viewer, dataSources } = fakeViewer(-99, 31);
|
||||
const { viewer, draw } = fakeViewer(-99, 31);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
||||
const anno = {
|
||||
@@ -369,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove',
|
||||
};
|
||||
|
||||
assert.throws(() => renderer.add(anno), /screen insert failed/);
|
||||
assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live');
|
||||
assert.equal(worldItems(draw).length, 2, 'the world drape is already live');
|
||||
assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself');
|
||||
|
||||
// The engine's rollback path — it must reach the partial state by id.
|
||||
renderer.remove(anno);
|
||||
assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released');
|
||||
assert.equal(worldItems(draw).length, 0, 'partial world state must be released');
|
||||
|
||||
// …and the id is free again: a retry draws ONE mark, not a second one over
|
||||
// an orphan nothing owns.
|
||||
renderer.add(anno);
|
||||
assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape');
|
||||
assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape');
|
||||
assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption');
|
||||
renderer.remove(anno);
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('a release that throws keeps the mark addressable for a retry cleanup', (t) => {
|
||||
installBrowserGlobals(t);
|
||||
const { viewer, dataSources } = fakeViewer(-99, 31);
|
||||
const { viewer, draw } = fakeViewer(-99, 31);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
||||
const anno = {
|
||||
@@ -404,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
|
||||
};
|
||||
|
||||
renderer.add(anno);
|
||||
assert.equal(dataSources[0].entities.values.length, 2);
|
||||
assert.equal(worldItems(draw).length, 2);
|
||||
assert.equal(annotationGroups(store).length, 1);
|
||||
|
||||
// The world route releases fine, then the screen release fails part-way
|
||||
@@ -412,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
|
||||
const workingSetTimeout = globalThis.window.setTimeout;
|
||||
globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); };
|
||||
assert.throws(() => renderer.remove(anno), /teardown scheduling failed/);
|
||||
assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release');
|
||||
assert.equal(worldItems(draw).length, 0, 'the world route did release');
|
||||
assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan');
|
||||
|
||||
// Dropping the routing entry here would make that orphan permanently
|
||||
@@ -420,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
|
||||
globalThis.window.setTimeout = workingSetTimeout;
|
||||
renderer.remove(anno);
|
||||
assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan');
|
||||
assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route');
|
||||
assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route');
|
||||
|
||||
// Fully released now — a third call is inert.
|
||||
renderer.remove(anno);
|
||||
@@ -430,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
|
||||
|
||||
test('a world add that fails mid-way leaves its landed entities removable', (t) => {
|
||||
installBrowserGlobals(t);
|
||||
const { viewer, dataSources } = fakeViewer(-99, 31);
|
||||
const { viewer, draw } = fakeViewer(-99, 31);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
||||
const anno = {
|
||||
@@ -446,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t)
|
||||
};
|
||||
|
||||
// The draped fill lands; the outline throws (bad geometry / lost context).
|
||||
const entities = dataSources[0].entities;
|
||||
const realAdd = entities.add.bind(entities);
|
||||
let addsLeft = 1;
|
||||
entities.add = (options) => {
|
||||
if (addsLeft <= 0) throw new Error('entity add failed');
|
||||
addsLeft -= 1;
|
||||
return realAdd(options);
|
||||
const realLines = draw.lines;
|
||||
draw.lines = (spec) => {
|
||||
const set = realLines(spec);
|
||||
set.set = () => { throw new Error('draw failed'); };
|
||||
return set;
|
||||
};
|
||||
|
||||
assert.throws(() => renderer.add(anno), /entity add failed/);
|
||||
assert.equal(entities.values.length, 1, 'one entity landed before the failure');
|
||||
assert.throws(() => renderer.add(anno), /draw failed/);
|
||||
assert.equal(worldItems(draw).length, 1, 'one item landed before the failure');
|
||||
|
||||
entities.add = realAdd;
|
||||
draw.lines = realLines;
|
||||
renderer.remove(anno);
|
||||
assert.equal(entities.values.length, 0,
|
||||
'the rollback must see the entities that landed before the throw');
|
||||
assert.equal(worldItems(draw).length, 0,
|
||||
'the rollback must see the items that landed before the throw');
|
||||
|
||||
renderer.add(anno);
|
||||
assert.equal(entities.values.length, 2, 'the retry draws a complete mark');
|
||||
assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark');
|
||||
assert.equal(annotationGroups(store).length, 1);
|
||||
renderer.destroy();
|
||||
});
|
||||
@@ -475,7 +478,7 @@ function workTrace() {
|
||||
|
||||
test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => {
|
||||
installBrowserGlobals(t);
|
||||
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
|
||||
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
||||
const renderer = createHybridAnnotationRenderer(viewer);
|
||||
t.after(() => renderer.destroy());
|
||||
const first = buildingAnnotation('sampled-building');
|
||||
@@ -485,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
|
||||
showOsmCredit(viewer, otherOwner);
|
||||
const probes = [];
|
||||
const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90];
|
||||
viewer.scene.clampToHeight = (position) => {
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(position);
|
||||
const lon = Cesium.Math.toDegrees(cartographic.longitude);
|
||||
const lat = Cesium.Math.toDegrees(cartographic.latitude);
|
||||
sampleHeights(viewer.scene, (lon, lat) => {
|
||||
probes.push([lon, lat]);
|
||||
const outcome = outcomes[probes.length - 1];
|
||||
if (outcome instanceof Error) throw outcome;
|
||||
return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome);
|
||||
};
|
||||
return outcome == null ? undefined : outcome;
|
||||
});
|
||||
// Suppress screen points: these counts concern the eight outside-building
|
||||
// probes, not the screen renderer's separate anchor-height sampling.
|
||||
const firstTrace = workTrace();
|
||||
@@ -510,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
|
||||
const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace });
|
||||
const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace });
|
||||
assert.equal(probes.length, 0, 'enqueue must not probe synchronously');
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1,
|
||||
'pending outlines add no tile credit to the other owner');
|
||||
for (let frame = 0; frame < 16; frame += 1) {
|
||||
const before = probes.length;
|
||||
frames.emit();
|
||||
assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget');
|
||||
if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts');
|
||||
if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts');
|
||||
}
|
||||
const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]);
|
||||
assert.equal(installed.status, 'installed');
|
||||
@@ -540,8 +540,9 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
|
||||
const detail = parent.detail;
|
||||
assert.equal(detail.index, index);
|
||||
assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing');
|
||||
// The fourth probe finds nothing and the fifth throws: both are misses.
|
||||
assert.equal(detail.clampResult,
|
||||
trace === firstTrace && index === 4 ? 'threw' : 'returned');
|
||||
trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed');
|
||||
assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd));
|
||||
assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end);
|
||||
if (index === 7) {
|
||||
@@ -571,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
|
||||
assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10);
|
||||
}
|
||||
assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8);
|
||||
const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon);
|
||||
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
|
||||
assert.equal(fills.length, 2);
|
||||
assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
|
||||
assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
|
||||
assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
|
||||
assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
|
||||
const afterCompletion = probes.length;
|
||||
frames.emit();
|
||||
assert.equal(probes.length, afterCompletion, 'completion releases the sampler');
|
||||
@@ -597,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as
|
||||
t.mock.method(globalThis.performance, 'now', () => now);
|
||||
const { viewer, frames } = fakeViewer(-99, 31);
|
||||
const renderer = createHybridAnnotationRenderer(viewer);
|
||||
viewer.scene.clampToHeight = (position) => position;
|
||||
sampleHeights(viewer.scene, () => 0);
|
||||
const traces = [workTrace(), workTrace(), workTrace()];
|
||||
const completions = [0, 0.01, 0.02].map((offset, index) =>
|
||||
renderer.add(buildingAnnotation(`queued-${index}`, offset), {
|
||||
@@ -626,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
|
||||
installBrowserGlobals(t);
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
t.after(() => t.mock.timers.reset());
|
||||
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
|
||||
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
||||
const renderer = createHybridAnnotationRenderer(viewer);
|
||||
let probeCount = 0;
|
||||
viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; };
|
||||
sampleHeights(viewer.scene, () => { probeCount += 1; return 0; });
|
||||
const cancelled = buildingAnnotation('cancelled-building');
|
||||
const cancelledTrace = workTrace();
|
||||
const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace });
|
||||
@@ -671,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
|
||||
assert.equal(viewer.credits.size, 0);
|
||||
for (const listener of savedTimeout) listener();
|
||||
assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks');
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
|
||||
const pending = buildingAnnotation('destroyed-building');
|
||||
const destruction = renderer.add(pending, { pendingVisible: false });
|
||||
@@ -681,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
|
||||
for (const listener of savedDestroy) listener();
|
||||
t.mock.timers.tick(2000);
|
||||
assert.equal(probeCount, 1);
|
||||
assert.equal(dataSources.length, 0, 'destroy removes the owned data source');
|
||||
assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go');
|
||||
assert.equal(frames.size, 0, 'destroy removes frame listeners');
|
||||
assert.equal(viewer.credits.size, 0);
|
||||
});
|
||||
@@ -690,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
|
||||
installBrowserGlobals(t);
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
t.after(() => t.mock.timers.reset());
|
||||
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
|
||||
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' };
|
||||
renderer.add(anno);
|
||||
@@ -703,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
|
||||
assert.equal(after.key, before.key);
|
||||
assert.equal(others.length, 0);
|
||||
assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted');
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
frames.emit();
|
||||
assert.equal(dataSources[0].entities.values.length, 0);
|
||||
assert.equal(worldItems(draw).length, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => {
|
||||
installBrowserGlobals(t);
|
||||
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
|
||||
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
||||
const { store, renderer } = hybridWithBoard(viewer);
|
||||
const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' };
|
||||
renderer.add(anno);
|
||||
@@ -724,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
|
||||
// Frame projection is still ordinary pending-point work. Arm the failure
|
||||
// only after sampling completes, before its promise converts the caption.
|
||||
for (let frame = 0; frame < 8; frame += 1) frames.emit();
|
||||
assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion');
|
||||
assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion');
|
||||
assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy');
|
||||
// The caption conversion fails when it presents the converted mark.
|
||||
const publish = store.publish;
|
||||
@@ -747,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
|
||||
assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8);
|
||||
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
|
||||
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1);
|
||||
assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back');
|
||||
assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back');
|
||||
assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy');
|
||||
assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable');
|
||||
globalThis.window.setTimeout = workingSetTimeout;
|
||||
@@ -781,6 +782,7 @@ test('a deadline passed during caption conversion leaves a drawn pending point',
|
||||
const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out'));
|
||||
assert.equal(live.length, 1);
|
||||
assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws');
|
||||
assert.notEqual(live[0].display, 'none', 'and is on screen');
|
||||
renderer.remove(anno);
|
||||
renderer.destroy();
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
outlineQueryText,
|
||||
} from './outlineRungs.js';
|
||||
import { createAnnotationResolver } from './resolver.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { decodeOpenFreeMapOutlineTile } from '../sources/openFreeMapOutlines.js';
|
||||
import { createNominatimOutlineClient } from '../sources/nominatimOutlines.js';
|
||||
import { createApplicationRequestServices } from '../services/requests.js';
|
||||
@@ -924,15 +925,17 @@ const PLACES = {
|
||||
},
|
||||
};
|
||||
|
||||
const viewerAt = (lat, lon, height = 4000) => ({
|
||||
camera: {
|
||||
positionCartographic: {
|
||||
latitude: (lat * Math.PI) / 180,
|
||||
longitude: (lon * Math.PI) / 180,
|
||||
height,
|
||||
// The resolver reads the camera through the renderer's camera port.
|
||||
const viewerAt = (lat, lon, height = 4000) =>
|
||||
bindFakeCesiumCamera({
|
||||
camera: {
|
||||
positionCartographic: {
|
||||
latitude: (lat * Math.PI) / 180,
|
||||
longitude: (lon * Math.PI) / 180,
|
||||
height,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('default settings: outline, street and building asks send nothing to Overpass', async (t) => {
|
||||
const prior = process.env.OVERPASS_UPSTREAMS;
|
||||
|
||||
@@ -5,11 +5,14 @@ import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
|
||||
import { createAnnotationResolver } from './resolver.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { polygonsContain } from '../data/adminBoundaries.js';
|
||||
import { streetFootprint } from './outlineRungs.js';
|
||||
import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
|
||||
|
||||
function viewerAt(lat, lon, height = 20_000) {
|
||||
return {
|
||||
// The resolver reads the camera through the renderer's camera port.
|
||||
return bindFakeCesiumCamera({
|
||||
camera: {
|
||||
positionCartographic: {
|
||||
latitude: (lat * Math.PI) / 180,
|
||||
@@ -17,7 +20,7 @@ function viewerAt(lat, lon, height = 20_000) {
|
||||
height,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** A resolver whose boundary lookups and geocoder record every call. */
|
||||
@@ -180,10 +183,10 @@ test('a geocoded city or neighborhood upgrades to the bundled outline', async ()
|
||||
const credits = [];
|
||||
const cancelled = await city.resolve(
|
||||
'Austin',
|
||||
{
|
||||
bindFakeCesiumCredits({
|
||||
...viewerAt(39, -100, 5_000_000),
|
||||
creditDisplay: { addStaticCredit: (credit) => credits.push(credit) },
|
||||
},
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const pending = cancelled.resolveOutline();
|
||||
|
||||
+43
-71
@@ -14,7 +14,6 @@ import {
|
||||
nearestPointOnLines,
|
||||
} from '../sources/featureGeometry.js';
|
||||
import { defaultGeospatial } from '../search/defaults.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js';
|
||||
import {
|
||||
lookupNaturalRegionOutline,
|
||||
@@ -45,6 +44,9 @@ import {
|
||||
import { createOutlineRungs } from './outlineRungs.js';
|
||||
import { unavailablePlaceSearch } from '../search/placeSearch.js';
|
||||
import { isPickedWorldPosition } from '../data/scenePick.js';
|
||||
import { heightsOf } from '../queries/heights.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js';
|
||||
|
||||
/** Prepare only local dateline outlines for planar admission and centering. */
|
||||
function localOutlineFrame(fp) {
|
||||
@@ -178,7 +180,7 @@ export function createAnnotationResolver({
|
||||
* Resolve a single annotation target to a normalized world anchor.
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {Cesium.Viewer} opts.viewer
|
||||
* @param {object} opts.viewer The viewer the renderer is bound to.
|
||||
* @param {string} [opts.target] Place name to geocode.
|
||||
* @param {number} [opts.latitude] Explicit latitude (wins over target).
|
||||
* @param {number} [opts.longitude] Explicit longitude.
|
||||
@@ -2216,11 +2218,10 @@ export function createAnnotationResolver({
|
||||
*/
|
||||
function viewportProximity(viewer) {
|
||||
try {
|
||||
const carto = viewer?.camera?.positionCartographic;
|
||||
if (!carto) return null;
|
||||
const lat = Cesium.Math.toDegrees(carto.latitude);
|
||||
const lon = Cesium.Math.toDegrees(carto.longitude);
|
||||
const radiusKm = Math.max((carto.height / 1000) * 3, 5);
|
||||
const pose = viewer ? findCamera(viewer)?.pose() : null;
|
||||
if (!pose) return null;
|
||||
const { lat, lon } = pose;
|
||||
const radiusKm = Math.max((pose.height / 1000) * 3, 5);
|
||||
if (![lat, lon, radiusKm].every(Number.isFinite)) return null;
|
||||
return { lat, lon, radiusKm };
|
||||
} catch {
|
||||
@@ -2231,12 +2232,12 @@ export function createAnnotationResolver({
|
||||
/** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */
|
||||
function viewportBias(viewer) {
|
||||
try {
|
||||
const rect = viewer?.camera?.computeViewRectangle?.();
|
||||
const rect = viewer ? findCamera(viewer)?.viewRectangle() : null;
|
||||
if (!rect) return null;
|
||||
const swLat = Cesium.Math.toDegrees(rect.south).toFixed(4);
|
||||
const swLng = Cesium.Math.toDegrees(rect.west).toFixed(4);
|
||||
const neLat = Cesium.Math.toDegrees(rect.north).toFixed(4);
|
||||
const neLng = Cesium.Math.toDegrees(rect.east).toFixed(4);
|
||||
const swLat = rect.south.toFixed(4);
|
||||
const swLng = rect.west.toFixed(4);
|
||||
const neLat = rect.north.toFixed(4);
|
||||
const neLng = rect.east.toFixed(4);
|
||||
if ([swLat, swLng, neLat, neLng].some((v) => v === 'NaN')) return null;
|
||||
return `${swLat},${swLng}|${neLat},${neLng}`;
|
||||
} catch {
|
||||
@@ -2289,58 +2290,39 @@ export function createAnnotationResolver({
|
||||
* name the place, and we anchor the mark to the actual world point under it.
|
||||
*/
|
||||
function pickWorldFromScreen(viewer, nx, ny) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return null;
|
||||
const canvas = scene.canvas;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
// The renderer's canvas; a viewer with no renderer bound, its own.
|
||||
const canvas = canvasOf(viewer);
|
||||
if (!query || !canvas) return null;
|
||||
const w = canvas.clientWidth || canvas.width || 0;
|
||||
const h = canvas.clientHeight || canvas.height || 0;
|
||||
if (!w || !h) return null;
|
||||
const px = Math.max(0, Math.min(1, nx)) * w;
|
||||
const py = Math.max(0, Math.min(1, ny)) * h;
|
||||
const pos = new Cesium.Cartesian2(px, py);
|
||||
|
||||
// Each stage is validated before it is accepted: a depth pick over empty sky
|
||||
// can return a NaN or centre-of-the-earth Cartesian, and converting one of
|
||||
// those throws inside Cesium. A degenerate pick IS a missed pick, so it falls
|
||||
// through to the next stage and ultimately to the caller's null.
|
||||
let cart = null;
|
||||
if (
|
||||
scene.pickPositionSupported &&
|
||||
typeof scene.pickPosition === 'function'
|
||||
) {
|
||||
// can return a NaN or centre-of-the-earth position, and converting one of
|
||||
// those throws inside the renderer. A degenerate pick IS a missed pick, so it
|
||||
// falls through to the next stage and ultimately to the caller's null.
|
||||
const attempt = (pick) => {
|
||||
try {
|
||||
cart = scene.pickPosition(pos);
|
||||
return pick();
|
||||
} catch {
|
||||
cart = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (
|
||||
!isPickedWorldPosition(cart) &&
|
||||
typeof viewer.camera.pickEllipsoid === 'function'
|
||||
) {
|
||||
try {
|
||||
cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84);
|
||||
} catch {
|
||||
cart = null;
|
||||
}
|
||||
}
|
||||
if (
|
||||
!isPickedWorldPosition(cart) &&
|
||||
typeof viewer.camera.getPickRay === 'function'
|
||||
) {
|
||||
try {
|
||||
const ray = viewer.camera.getPickRay(pos);
|
||||
cart = ray ? scene.globe?.pick(ray, scene) || null : null;
|
||||
} catch {
|
||||
cart = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
// The depth pick answers null where the renderer has no depth support.
|
||||
let cart = attempt(() => query.pickPosition(px, py));
|
||||
if (!isPickedWorldPosition(cart))
|
||||
cart = attempt(() => query.pickEllipsoid(px, py));
|
||||
if (!isPickedWorldPosition(cart))
|
||||
cart = attempt(() => query.pickGlobe(query.pickRay(px, py)));
|
||||
if (!isPickedWorldPosition(cart)) return null;
|
||||
const carto = Cesium.Cartographic.fromCartesian(cart);
|
||||
const carto = toLonLatH(cart);
|
||||
if (!carto) return null;
|
||||
return {
|
||||
lat: Cesium.Math.toDegrees(carto.latitude),
|
||||
lon: Cesium.Math.toDegrees(carto.longitude),
|
||||
lat: carto.lat,
|
||||
lon: carto.lon,
|
||||
// The height the pick actually landed on — a roof, a hillside, or 0 on
|
||||
// the ellipsoid. Callers that only want a coordinate ignore it; the draw
|
||||
// tool's live preview needs it, or the rubber band sinks to sea level
|
||||
@@ -2355,28 +2337,18 @@ export function createAnnotationResolver({
|
||||
* the tiles for that spot aren't loaded we fall back to the ellipsoid (0).
|
||||
*/
|
||||
function sampleGroundHeight(viewer, lon, lat) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return 0;
|
||||
try {
|
||||
if (
|
||||
scene.clampToHeightSupported &&
|
||||
typeof scene.clampToHeight === 'function'
|
||||
) {
|
||||
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
|
||||
const surface = Cesium.Cartographic.toCartesian(carto);
|
||||
const clamped = scene.clampToHeight(surface);
|
||||
if (clamped) {
|
||||
const h = Cesium.Cartographic.fromCartesian(clamped).height;
|
||||
if (Number.isFinite(h)) return h;
|
||||
}
|
||||
if (!viewer) return 0;
|
||||
const heights = heightsOf(viewer);
|
||||
// A miss is tiles not ready: fall through to the terrain, then 0.
|
||||
if (heights.supported().clamp) {
|
||||
const clamped = heights.clampNow(fromDegrees(lon, lat, 0));
|
||||
if (clamped) {
|
||||
const h = toLonLatH(clamped)?.height;
|
||||
if (Number.isFinite(h)) return h;
|
||||
}
|
||||
} catch {
|
||||
/* tiles not ready — fall through */
|
||||
}
|
||||
const globeHeight = scene.globe?.getHeight?.(
|
||||
Cesium.Cartographic.fromDegrees(lon, lat),
|
||||
);
|
||||
return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0;
|
||||
const globeHeight = heights.now({ lon, lat }, { against: 'terrain' });
|
||||
return globeHeight !== null && globeHeight > 0 ? globeHeight : 0;
|
||||
}
|
||||
|
||||
function shortLabel(formattedAddress) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { getOverlayPaintRect } from '../overlays/worldOverlay.js';
|
||||
import {
|
||||
getActiveTrackedReadoutId,
|
||||
@@ -8,6 +8,15 @@ import { t } from '../i18n/index.js';
|
||||
import { nextTick } from 'vue';
|
||||
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { heightsOf } from '../queries/heights.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { distance } from '../geo/vector.js';
|
||||
import {
|
||||
canvasOf as sceneCanvasOf,
|
||||
findCamera,
|
||||
findFrame,
|
||||
findQuery,
|
||||
} from '../render/rendererOf.js';
|
||||
|
||||
/** A label whose detailed outline could not be resolved. */
|
||||
function outlineUnavailableLabel(label) {
|
||||
@@ -78,11 +87,13 @@ export function createScreenAnnotationRenderer(
|
||||
const arrowMarkers = new Map();
|
||||
let viewBox = null;
|
||||
|
||||
const scene = viewer.scene;
|
||||
const occluder = new Cesium.EllipsoidalOccluder(
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
scene.camera.positionWC,
|
||||
);
|
||||
// The eye this frame is projected from (the camera port's pose), and the
|
||||
// query port and canvas it is projected through, read once per pass.
|
||||
let pose = null;
|
||||
let passQuery = null;
|
||||
let passCanvas = null;
|
||||
// The renderer's canvas; a viewer with no renderer bound, its own.
|
||||
const canvasOf = () => sceneCanvasOf(viewer);
|
||||
const records = new Map(); // anno.id -> { key, anno, group, parts }
|
||||
const leaving = new Map(); // key -> a removed mark's record while it fades out
|
||||
const byKey = new Map(); // key -> record, live or fading
|
||||
@@ -91,8 +102,6 @@ export function createScreenAnnotationRenderer(
|
||||
let published = '';
|
||||
// Only the renderer whose board the store shows may change or remove it.
|
||||
const shown = () => store.board?.owner === owner;
|
||||
const scratch = new Cesium.Cartesian2();
|
||||
const scratchDir = new Cesium.Cartesian3();
|
||||
// Per-point ground height cache. Marks must sit on the real surface, not at
|
||||
// sea level — otherwise in elevated cities (Austin ~150 m) they project
|
||||
// underground and parallax sinks them at oblique angles. Sampled once the
|
||||
@@ -121,7 +130,7 @@ export function createScreenAnnotationRenderer(
|
||||
// Re-project every annotation each rendered frame so marks stay glued to the
|
||||
// world. postRender runs after the camera/tiles update, so positions are exact.
|
||||
const onPostRender = () => projectAll();
|
||||
scene.postRender.addEventListener(onPostRender);
|
||||
const removePostRender = findFrame(viewer)?.on('postRender', onPostRender);
|
||||
|
||||
function color(anno) {
|
||||
return PALETTE[anno.color] || PALETTE.primary;
|
||||
@@ -141,15 +150,12 @@ export function createScreenAnnotationRenderer(
|
||||
return cached.h;
|
||||
}
|
||||
try {
|
||||
if (
|
||||
scene.clampToHeightSupported &&
|
||||
typeof scene.clampToHeight === 'function'
|
||||
) {
|
||||
const c = scene.clampToHeight(
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, 0),
|
||||
);
|
||||
const heights = heightsOf(viewer);
|
||||
if (heights.supported().clamp) {
|
||||
// A miss is tiles not ready.
|
||||
const c = heights.clampNow(fromDegrees(lon, lat, 0));
|
||||
if (c) {
|
||||
const h = Cesium.Cartographic.fromCartesian(c).height;
|
||||
const h = toLonLatH(c)?.height;
|
||||
if (Number.isFinite(h) && h > -430 && h < 9000) {
|
||||
heightCache.set(key, { h, settled: true, gen: projGen });
|
||||
trimHeightCache();
|
||||
@@ -278,7 +284,7 @@ export function createScreenAnnotationRenderer(
|
||||
}
|
||||
|
||||
// Record the mark BEFORE it reaches the board, then unwind on any throw
|
||||
// from here down (projectAll reaches into Cesium and can fail on a lost
|
||||
// from here down (projectAll reaches into the renderer and can fail on a lost
|
||||
// context). Previously a throw past the insert left an ORPHANED mark: the
|
||||
// engine's rollback only deletes its own map entry, so the next annotate
|
||||
// of the same geometry stacked a fresh mark on top of the corpse.
|
||||
@@ -363,26 +369,27 @@ export function createScreenAnnotationRenderer(
|
||||
// Anchor at the real surface height (cached + validated), so marks sit on
|
||||
// the ground/building instead of at sea level. The settle-once cache keeps
|
||||
// it stable (no per-frame jitter that earlier broke nearby projections).
|
||||
const world = Cesium.Cartesian3.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
groundHeight(lon, lat),
|
||||
);
|
||||
const world = fromDegrees(lon, lat, groundHeight(lon, lat));
|
||||
if (!pose) return null;
|
||||
// Reject points behind the camera (they produce wrapped/extreme coords).
|
||||
Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir);
|
||||
if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0)
|
||||
const eye = pose.position;
|
||||
const look = pose.direction;
|
||||
if (
|
||||
(world.x - eye.x) * look.x +
|
||||
(world.y - eye.y) * look.y +
|
||||
(world.z - eye.z) * look.z <=
|
||||
0
|
||||
)
|
||||
return null;
|
||||
// Reject points beyond the globe horizon.
|
||||
if (!occluder.isPointVisible(world)) return null;
|
||||
const win = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
world,
|
||||
scratch,
|
||||
);
|
||||
const query = passQuery;
|
||||
if (!query || query.isOccluded(world)) return null;
|
||||
const win = query.project(world);
|
||||
if (!win || !Number.isFinite(win.x) || !Number.isFinite(win.y)) return null;
|
||||
// Reject absurd off-screen projections (anchor not in view).
|
||||
const w = scene.canvas.clientWidth || scene.canvas.width;
|
||||
const h = scene.canvas.clientHeight || scene.canvas.height;
|
||||
const canvas = passCanvas;
|
||||
const w = canvas.clientWidth || canvas.width;
|
||||
const h = canvas.clientHeight || canvas.height;
|
||||
if (
|
||||
!allowOffscreen &&
|
||||
(win.x < -w || win.x > 2 * w || win.y < -h || win.y > 2 * h)
|
||||
@@ -406,7 +413,6 @@ export function createScreenAnnotationRenderer(
|
||||
const TRACKED_FADE_FRAME_MS = 1000 / 60;
|
||||
let trackedFadeAtMs = -Infinity;
|
||||
const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop
|
||||
const _scratchTrackedWin = new Cesium.Cartesian2();
|
||||
|
||||
// Evaluate a NearFarScalar (billboard scaleByDistance) at a camera distance.
|
||||
function nearFarValue(nfs, dist) {
|
||||
@@ -427,32 +433,23 @@ export function createScreenAnnotationRenderer(
|
||||
let top = painted?.y;
|
||||
let bottom = painted ? painted.y + painted.h : undefined;
|
||||
|
||||
const ent = viewer.trackedEntity;
|
||||
const now = Cesium.JulianDate.now();
|
||||
const followed = followedOf(viewer);
|
||||
const displayPosition = followed?.displayPosition;
|
||||
const world =
|
||||
typeof ent?.gevDisplayPosition === 'function'
|
||||
? ent.gevDisplayPosition()
|
||||
: null;
|
||||
const win = world
|
||||
? Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
world,
|
||||
_scratchTrackedWin,
|
||||
)
|
||||
: null;
|
||||
typeof displayPosition === 'function' ? displayPosition() : null;
|
||||
const win = world ? (passQuery?.project(world) ?? null) : null;
|
||||
|
||||
// Billboard box — centered on the anchor, magnified by scaleByDistance.
|
||||
const bb = ent?.billboard;
|
||||
if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
|
||||
const baseW = bb.width?.getValue?.(now) ?? 28;
|
||||
const baseH = bb.height?.getValue?.(now) ?? 28;
|
||||
// Billboard box — centered on the anchor, magnified by scaleByDistance, from
|
||||
// the size the tracking layer recorded for its sprite.
|
||||
const sprite = followed?.sprite;
|
||||
if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
|
||||
const baseW = sprite.width ?? 28;
|
||||
const baseH = sprite.height ?? 28;
|
||||
let scale = 1;
|
||||
const sbd = bb.scaleByDistance?.getValue?.(now);
|
||||
if (sbd)
|
||||
scale = nearFarValue(
|
||||
sbd,
|
||||
Cesium.Cartesian3.distance(scene.camera.positionWC, world),
|
||||
);
|
||||
const sbd = sprite.scaleByDistance;
|
||||
// No eye to measure from: the sprite's own size.
|
||||
if (sbd && pose)
|
||||
scale = nearFarValue(sbd, distance(pose.position, world));
|
||||
const hw = (baseW * scale) / 2;
|
||||
const hh = (baseH * scale) / 2;
|
||||
const bbLeft = win.x - hw;
|
||||
@@ -481,14 +478,17 @@ export function createScreenAnnotationRenderer(
|
||||
return;
|
||||
}
|
||||
projGen += 1; // new frame: entries touched below are "hot" and survive trimming
|
||||
pose = findCamera(viewer)?.pose() ?? null;
|
||||
passQuery = findQuery(viewer);
|
||||
passCanvas = canvasOf();
|
||||
const trackedRect = trackedEntityRect();
|
||||
occluder.cameraPosition = scene.camera.positionWC;
|
||||
const h = scene.canvas.clientHeight || scene.canvas.height;
|
||||
const w = scene.canvas.clientWidth || scene.canvas.width;
|
||||
const canvas = passCanvas;
|
||||
const h = canvas.clientHeight || canvas.height;
|
||||
const w = canvas.clientWidth || canvas.width;
|
||||
viewBox = `0 0 ${w} ${h}`;
|
||||
// Shrink point-marker geometry as the camera pulls back (declutter the blob).
|
||||
const mScale = markScale(
|
||||
viewer.camera.positionCartographic?.height ?? 1000,
|
||||
Number.isFinite(pose?.height) ? pose.height : 1000,
|
||||
);
|
||||
|
||||
for (const rec of records.values()) {
|
||||
@@ -834,7 +834,7 @@ export function createScreenAnnotationRenderer(
|
||||
|
||||
function destroy() {
|
||||
try {
|
||||
scene.postRender.removeEventListener(onPostRender);
|
||||
removePostRender?.();
|
||||
} catch {
|
||||
/* torn down */
|
||||
}
|
||||
|
||||
@@ -6,7 +6,19 @@ import { createApp, nextTick } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
|
||||
import ScreenAnnotations from '../ui/views/panels/ScreenAnnotations.vue';
|
||||
import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js';
|
||||
import { createScreenAnnotationRenderer as createRenderer } from './screenAnnotationRenderer.js';
|
||||
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { rendererOf } from '../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* The renderer over a viewer double with the camera, query and frame ports
|
||||
* bound over it (once per double), and the scene's canvas as the viewer's.
|
||||
*/
|
||||
function createScreenAnnotationRenderer(viewer, options) {
|
||||
if (!rendererOf(viewer)) bindFakeCesiumScene(viewer);
|
||||
viewer.canvas ??= viewer.scene?.canvas;
|
||||
return createRenderer(viewer, options);
|
||||
}
|
||||
|
||||
// happy-dom does not lay out SVG; every element measures as a 40 x 16 box.
|
||||
for (const type of [globalThis.SVGElement, globalThis.SVGGraphicsElement]) {
|
||||
@@ -53,7 +65,7 @@ function sceneFor(camera, extra = {}) {
|
||||
return {
|
||||
camera,
|
||||
canvas: { clientWidth: 800, clientHeight: 600, width: 800, height: 600 },
|
||||
clampToHeightSupported: false,
|
||||
sampleHeightSupported: false,
|
||||
postRender: { addEventListener() {}, removeEventListener() {} },
|
||||
...extra,
|
||||
};
|
||||
@@ -173,14 +185,13 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
|
||||
const sampledAnchors = [];
|
||||
const scene = sceneFor(camera, {
|
||||
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
|
||||
clampToHeightSupported: true,
|
||||
clampToHeight(world) {
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(world);
|
||||
sampleHeightSupported: true,
|
||||
sampleHeight(cartographic) {
|
||||
sampledAnchors.push([
|
||||
Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)),
|
||||
Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)),
|
||||
]);
|
||||
return world;
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
const renderer = createScreenAnnotationRenderer(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,70 +1,448 @@
|
||||
// A mark hidden from Draw's list leaves the globe whole: every entity it put
|
||||
// there is taken out on sync and comes back when shown, and the line's
|
||||
// flowing stroke, which keeps its own colour, follows the mark's alpha.
|
||||
// The world renderer draws each mark through the draw port, in sets of its
|
||||
// own: a hidden mark has its sets hidden on sync and shown again; a fading
|
||||
// mark takes its new colours in place; every kind draws what it drew as
|
||||
// entities, draped and clamped to terrain and tiles alike.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as C from 'cesium';
|
||||
import {
|
||||
FlowMaterialProperty,
|
||||
createWorldAnnotationRenderer,
|
||||
} from './worldAnnotationRenderer.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js';
|
||||
|
||||
const noop = () => {};
|
||||
function viewer(t) {
|
||||
for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) {
|
||||
const original = globalThis[name];
|
||||
globalThis[name] = class {};
|
||||
t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; });
|
||||
}
|
||||
const before = globalThis.document;
|
||||
globalThis.document = { addEventListener: noop, removeEventListener: noop };
|
||||
t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; });
|
||||
/**
|
||||
* A viewer with a fake draw port, frame, camera and query bound. The camera
|
||||
* stands at `camera.height`; `preRender()` runs the frame's preRender
|
||||
* listeners, `emit()` its postRender ones.
|
||||
*/
|
||||
function viewer(t, { heights = () => null } = {}) {
|
||||
const draw = fakeDrawPort();
|
||||
const frames = new Set();
|
||||
const before = new Set();
|
||||
const v = { requests: 0 };
|
||||
const frame = {
|
||||
on(phase, cb) {
|
||||
const listeners =
|
||||
phase === 'postRender' ? frames : phase === 'preRender' ? before : null;
|
||||
if (!listeners) return () => {};
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
requestRender() {
|
||||
v.requests += 1;
|
||||
},
|
||||
};
|
||||
const camera = { height: 2000, pose: () => ({ height: camera.height }) };
|
||||
const query = { sampleHeightNow: (point) => heights(point) };
|
||||
const unbind = bindRenderer(v, { draw, frame, query, camera });
|
||||
t.after(unbind);
|
||||
return {
|
||||
creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop },
|
||||
entities: new C.EntityCollection(),
|
||||
dataSources: new C.DataSourceCollection(),
|
||||
camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } },
|
||||
scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(),
|
||||
primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } },
|
||||
v,
|
||||
draw,
|
||||
frames,
|
||||
before,
|
||||
camera,
|
||||
emit: () => [...frames].forEach((cb) => cb()),
|
||||
preRender: () => [...before].forEach((cb) => cb()),
|
||||
};
|
||||
}
|
||||
|
||||
const marks = () => [
|
||||
{ id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] },
|
||||
{ id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] },
|
||||
{ id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } },
|
||||
{
|
||||
id: 'route',
|
||||
type: 'route',
|
||||
color: 'amber',
|
||||
alpha: 1,
|
||||
anchor: { lat: 0, lon: 0 },
|
||||
path: [
|
||||
{ lat: 0, lon: 0 },
|
||||
{ lat: 0.01, lon: 0.01 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'area',
|
||||
type: 'area',
|
||||
color: 'green',
|
||||
alpha: 1,
|
||||
anchor: { lat: 0.005, lon: 0.005 },
|
||||
ring: [
|
||||
[0, 0],
|
||||
[0.01, 0],
|
||||
[0.01, 0.01],
|
||||
[0, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'pin',
|
||||
type: 'pin',
|
||||
color: 'primary',
|
||||
alpha: 1,
|
||||
anchor: { lat: 0.02, lon: 0.02 },
|
||||
},
|
||||
];
|
||||
|
||||
test('a hidden mark has every entity taken off on sync, and back when shown', (t) => {
|
||||
const renderer = createWorldAnnotationRenderer(viewer(t));
|
||||
/** The live sets a mark draws into. */
|
||||
const setsOf = (draw, anno) =>
|
||||
[...draw.sets.values()].filter(
|
||||
(record) =>
|
||||
!record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`),
|
||||
);
|
||||
|
||||
test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => {
|
||||
const { v, draw } = viewer(t);
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const [route, area, pin] = marks();
|
||||
for (const anno of [route, area, pin]) renderer.add(anno);
|
||||
const shown = (anno) => anno._entities.map((entity) => entity.show);
|
||||
for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id);
|
||||
for (const anno of [route, area, pin])
|
||||
assert.ok(setsOf(draw, anno).length > 0, anno.id);
|
||||
const shown = (anno) => setsOf(draw, anno).map((record) => record.show);
|
||||
|
||||
route.hidden = true;
|
||||
area.hidden = true;
|
||||
renderer.sync();
|
||||
assert.ok(shown(route).every((show) => show === false), 'the line is off');
|
||||
assert.ok(shown(area).every((show) => show === false), 'the area is off');
|
||||
assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays');
|
||||
assert.ok(
|
||||
shown(route).every((show) => show === false),
|
||||
'the line is off',
|
||||
);
|
||||
assert.ok(
|
||||
shown(area).every((show) => show === false),
|
||||
'the area is off',
|
||||
);
|
||||
assert.ok(
|
||||
shown(pin).every((show) => show === true),
|
||||
'a visible mark stays',
|
||||
);
|
||||
|
||||
route.hidden = false;
|
||||
renderer.sync();
|
||||
assert.ok(shown(route).every((show) => show === true), 'the line is back');
|
||||
assert.ok(
|
||||
shown(route).every((show) => show === true),
|
||||
'the line is back',
|
||||
);
|
||||
const areaSets = setsOf(draw, area);
|
||||
renderer.remove(area);
|
||||
assert.ok(
|
||||
areaSets.every((record) => record.disposed),
|
||||
'a removed mark lets its sets go',
|
||||
);
|
||||
renderer.sync();
|
||||
assert.equal(area._entities, null, 'a removed mark is no longer synced');
|
||||
renderer.destroy();
|
||||
assert.equal(
|
||||
[...draw.sets.values()].filter((record) => !record.disposed).length,
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test('a fading mark takes its new colours in place, its pulses with them', (t) => {
|
||||
const { v, draw } = viewer(t);
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const [route, area] = marks();
|
||||
renderer.add(route);
|
||||
renderer.add(area);
|
||||
const line = () => [...setsOf(draw, route)[0].items.values()][0];
|
||||
const fill = () =>
|
||||
setsOf(draw, area)
|
||||
.find((r) => r.kind === 'shapes')
|
||||
.items.get('fill:0');
|
||||
assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9);
|
||||
assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9);
|
||||
route.alpha = 0.5;
|
||||
area.alpha = 0.5;
|
||||
renderer.sync();
|
||||
assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading');
|
||||
assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9);
|
||||
assert.deepEqual(
|
||||
[fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)),
|
||||
[60, 100],
|
||||
'its pulse swings between 60% and all of its alpha',
|
||||
);
|
||||
route.alpha = 0;
|
||||
renderer.sync();
|
||||
assert.equal(line().style.color[3], 0, 'faded out: nothing painted');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('the line\'s flowing stroke follows its mark\'s alpha', () => {
|
||||
let alpha = 1;
|
||||
const material = new FlowMaterialProperty('#ffb547', () => alpha);
|
||||
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9);
|
||||
alpha = 0;
|
||||
assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted');
|
||||
alpha = 0.5;
|
||||
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading');
|
||||
assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before');
|
||||
test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => {
|
||||
const { v, draw } = viewer(t);
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const [route, area, pin] = marks();
|
||||
const synth = { ...area, id: 'synth', synthesized: true };
|
||||
const arrow = {
|
||||
id: 'arrow',
|
||||
type: 'arrow',
|
||||
color: 'red',
|
||||
alpha: 1,
|
||||
anchor: { lon: 0, lat: 0 },
|
||||
to: { lon: 0.01, lat: 0 },
|
||||
};
|
||||
const label = {
|
||||
id: 'label',
|
||||
type: 'label',
|
||||
color: 'amber',
|
||||
alpha: 1,
|
||||
anchor: { lon: 0.03, lat: 0 },
|
||||
};
|
||||
for (const anno of [route, area, pin, synth, arrow, label])
|
||||
renderer.add(anno);
|
||||
const items = (anno, kind) => [
|
||||
...(setsOf(draw, anno)
|
||||
.find((r) => r.kind === kind)
|
||||
?.items.values() ?? []),
|
||||
];
|
||||
for (const record of [...draw.sets.values()])
|
||||
assert.equal(record.spec.clampTo, 'both');
|
||||
|
||||
const [flow] = items(route, 'lines');
|
||||
assert.equal(flow.mode, 'draped');
|
||||
assert.equal(flow.widthPx, 9);
|
||||
assert.deepEqual(
|
||||
{ ...flow.style, color: undefined },
|
||||
{ kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 },
|
||||
);
|
||||
|
||||
const [areaFill] = items(area, 'shapes');
|
||||
assert.equal(areaFill.height, 'clampGround');
|
||||
assert.equal(areaFill.animate.property, 'alpha');
|
||||
assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9);
|
||||
const [areaLine] = items(area, 'lines');
|
||||
assert.deepEqual(
|
||||
[areaLine.widthPx, areaLine.style.kind, areaLine.style.power],
|
||||
[6, 'glow', 0.35],
|
||||
);
|
||||
const [synthLine] = items(synth, 'lines');
|
||||
assert.deepEqual(
|
||||
[synthLine.style.kind, synthLine.style.length],
|
||||
['dash', 24],
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9,
|
||||
'an approximate area is fainter',
|
||||
);
|
||||
|
||||
const [arrowLine] = items(arrow, 'lines');
|
||||
assert.deepEqual(
|
||||
[arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind],
|
||||
['draped', 16, 'arrow'],
|
||||
);
|
||||
|
||||
const [ring] = items(pin, 'shapes');
|
||||
assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height');
|
||||
assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor);
|
||||
const [marker] = items(pin, 'points');
|
||||
assert.deepEqual(
|
||||
[
|
||||
marker.pixelSize,
|
||||
marker.height,
|
||||
marker.outlineWidth,
|
||||
marker.disableDepthTest,
|
||||
],
|
||||
[14, 'clampGround', 3, Infinity],
|
||||
);
|
||||
assert.equal(items(label, 'shapes').length, 0, 'a label has no ring');
|
||||
assert.equal(items(label, 'points')[0].pixelSize, 8);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => {
|
||||
const { v, draw, camera, preRender, before } = viewer(t);
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const [, , pin] = marks();
|
||||
const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } };
|
||||
renderer.add(pin);
|
||||
renderer.add(other);
|
||||
const ringOf = (anno) =>
|
||||
setsOf(draw, anno)
|
||||
.find((r) => r.kind === 'shapes')
|
||||
.items.get('ring');
|
||||
// Writes to the rings' sets since they were drawn.
|
||||
const shapeSets = [pin, other].map((anno) =>
|
||||
setsOf(draw, anno).find((r) => r.kind === 'shapes'),
|
||||
);
|
||||
const upserts = {
|
||||
get length() {
|
||||
return shapeSets.reduce((n, record) => n + record.writes - 1, 0);
|
||||
},
|
||||
};
|
||||
assert.equal(ringOf(pin).geometry.semiMajor, 60);
|
||||
assert.equal(before.size, 1, 'one listener for every ring');
|
||||
// The camera has not moved: nothing is sent.
|
||||
preRender();
|
||||
assert.equal(upserts.length, 0);
|
||||
// It climbs: both rings are sent at the new radius, once.
|
||||
camera.height = 4000;
|
||||
preRender();
|
||||
preRender();
|
||||
assert.equal(upserts.length, 2);
|
||||
assert.equal(ringOf(pin).geometry.semiMajor, 120);
|
||||
assert.equal(ringOf(pin).geometry.semiMinor, 120);
|
||||
assert.equal(ringOf(other).geometry.semiMajor, 120);
|
||||
// A change under 0.1% sends nothing.
|
||||
camera.height = 4002;
|
||||
preRender();
|
||||
assert.equal(upserts.length, 2);
|
||||
// Held within 14 m and 170 m.
|
||||
camera.height = 1e6;
|
||||
preRender();
|
||||
assert.equal(ringOf(pin).geometry.semiMajor, 170);
|
||||
camera.height = 10;
|
||||
preRender();
|
||||
assert.equal(ringOf(pin).geometry.semiMajor, 14);
|
||||
// A hidden mark waits, and catches up when shown.
|
||||
other.hidden = true;
|
||||
renderer.sync();
|
||||
camera.height = 3000;
|
||||
preRender();
|
||||
assert.equal(ringOf(pin).geometry.semiMajor, 90);
|
||||
assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent');
|
||||
other.hidden = false;
|
||||
renderer.sync();
|
||||
assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up');
|
||||
// The last ring gone, the listener goes with it.
|
||||
renderer.remove(pin);
|
||||
renderer.remove(other);
|
||||
assert.equal(before.size, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => {
|
||||
const { v, draw, emit, frames } = viewer(t, { heights: () => 150 });
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const ring = [
|
||||
[0, 0],
|
||||
[0.001, 0],
|
||||
[0.001, 0.001],
|
||||
[0, 0.001],
|
||||
[0, 0],
|
||||
];
|
||||
const anno = {
|
||||
id: 'b',
|
||||
type: 'area',
|
||||
color: 'amber',
|
||||
alpha: 1,
|
||||
footprintKind: 'building',
|
||||
buildingHeight: 40,
|
||||
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
|
||||
ring,
|
||||
};
|
||||
const done = renderer.add(anno);
|
||||
assert.equal(frames.size, 1, 'probing on the frames');
|
||||
assert.equal(
|
||||
setsOf(draw, anno).length,
|
||||
0,
|
||||
'nothing until its ground is known',
|
||||
);
|
||||
for (let i = 0; i < 8; i++) emit();
|
||||
assert.equal((await done).status, 'installed');
|
||||
assert.equal(frames.size, 0, 'done probing');
|
||||
const shapes = [
|
||||
...setsOf(draw, anno)
|
||||
.find((r) => r.kind === 'shapes')
|
||||
.items.values(),
|
||||
];
|
||||
const volume = shapes.find((s) => s.id === 'volume:0');
|
||||
assert.equal(volume.extrudeHeight, 150 + 40 + 24);
|
||||
assert.equal(volume.geometry.rings[0][0].height, 147);
|
||||
assert.equal(volume.height, 'absolute');
|
||||
const cage = shapes.find((s) => s.id === 'cage:0');
|
||||
assert.equal(cage.outlineOnly, true);
|
||||
assert.ok(cage.geometry.rings[0].length <= 14);
|
||||
const [base] = setsOf(draw, anno)
|
||||
.find((r) => r.kind === 'lines')
|
||||
.items.values();
|
||||
assert.deepEqual(
|
||||
[base.mode, base.widthPx, base.style.kind, base.style.power],
|
||||
['draped', 3, 'glow', 0.25],
|
||||
);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('each kind paints the alphas it painted as entities, at full alpha', (t) => {
|
||||
const { v, draw } = viewer(t, { heights: () => 150 });
|
||||
const renderer = createWorldAnnotationRenderer(v);
|
||||
const [route, area, pin] = marks();
|
||||
const synth = { ...area, id: 'synth', synthesized: true };
|
||||
const arrow = {
|
||||
id: 'arrow',
|
||||
type: 'arrow',
|
||||
color: 'red',
|
||||
alpha: 1,
|
||||
anchor: { lon: 0, lat: 0 },
|
||||
to: { lon: 0.01, lat: 0 },
|
||||
};
|
||||
const ring = Array.from({ length: 40 }, (_, i) => [
|
||||
0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI),
|
||||
0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI),
|
||||
]);
|
||||
const building = {
|
||||
id: 'b',
|
||||
type: 'area',
|
||||
color: 'amber',
|
||||
alpha: 1,
|
||||
footprintKind: 'building',
|
||||
buildingHeight: 40,
|
||||
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
|
||||
ring,
|
||||
};
|
||||
for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno);
|
||||
renderer.add(building, { sampledGroundHeight: 150 });
|
||||
const items = (anno, kind) => [
|
||||
...(setsOf(draw, anno)
|
||||
.find((r) => r.kind === kind)
|
||||
?.items.values() ?? []),
|
||||
];
|
||||
const alpha = (c) => Math.round(c[3] * 1000) / 1000;
|
||||
assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95);
|
||||
assert.equal(alpha(items(area, 'lines')[0].style.color), 1);
|
||||
assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95);
|
||||
assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95);
|
||||
assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38);
|
||||
const marker = items(pin, 'points')[0];
|
||||
assert.deepEqual(
|
||||
[alpha(marker.color), alpha(marker.outlineColor)],
|
||||
[1, 0.95],
|
||||
);
|
||||
assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]);
|
||||
const [volume, cage] = items(building, 'shapes');
|
||||
assert.equal(alpha(volume.fill), 0.45);
|
||||
assert.equal(alpha(cage.outline), 0.32);
|
||||
assert.equal(
|
||||
Math.round(cage.animate.from * 1000) / 1000,
|
||||
0.192,
|
||||
'the cage pulses too',
|
||||
);
|
||||
assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14');
|
||||
assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => {
|
||||
const { v, draw } = viewer(t);
|
||||
const first = createWorldAnnotationRenderer(v);
|
||||
const second = createWorldAnnotationRenderer(v);
|
||||
const [route, area] = marks();
|
||||
first.add(route);
|
||||
const prefix = route._draw.prefix;
|
||||
first.remove(route);
|
||||
assert.doesNotThrow(() => first.add(route));
|
||||
assert.notEqual(route._draw.prefix, prefix, 'fresh sets');
|
||||
assert.doesNotThrow(() => second.add(area));
|
||||
assert.ok(
|
||||
!area._draw.prefix.startsWith(
|
||||
route._draw.prefix.split(':').slice(0, 2).join(':') + ':',
|
||||
),
|
||||
);
|
||||
// Added again as another kind, its old sets go.
|
||||
const kinds = () =>
|
||||
setsOf(draw, route)
|
||||
.map((r) => r.kind)
|
||||
.sort();
|
||||
assert.deepEqual(kinds(), ['lines']);
|
||||
Object.assign(route, { type: 'pin', path: undefined });
|
||||
first.add(route);
|
||||
assert.deepEqual(kinds(), ['points', 'shapes']);
|
||||
assert.doesNotThrow(() => first.remove(null));
|
||||
first.destroy();
|
||||
second.destroy();
|
||||
assert.equal(route._draw, null);
|
||||
first.add(route);
|
||||
assert.equal(route._draw, null, 'a destroyed renderer draws nothing more');
|
||||
assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0);
|
||||
});
|
||||
+109
-38
@@ -2,20 +2,74 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createApplication } from './application.js';
|
||||
import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js';
|
||||
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
installFreeLookHeightLimit,
|
||||
installGlobeInViewRecovery,
|
||||
installTrackpadPinchZoom,
|
||||
} from './viewer.js';
|
||||
import {
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
globeFrameShare,
|
||||
globeOutOfFrame,
|
||||
lookAngleWithinFrame,
|
||||
lookStepLosesGlobe,
|
||||
} from '../globeInView.js';
|
||||
import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js';
|
||||
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
|
||||
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js';
|
||||
import * as globeInView from '../globeInView.js';
|
||||
import { createCesiumCamera } from '../render/cesium/camera.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { entityFollowTarget } from '../data/followed.js';
|
||||
|
||||
/** The camera port bound over each real Cesium camera a test makes. */
|
||||
const cameraPorts = new WeakMap();
|
||||
|
||||
/**
|
||||
* Bind `viewer` the Cesium renderer's own camera port over its real camera,
|
||||
* with the camera's own `moveStart` and `moveEnd` so a test raises them, and
|
||||
* a frame port that counts render requests on the scene.
|
||||
*/
|
||||
function bindCameraPorts(viewer) {
|
||||
const { camera, scene } = viewer;
|
||||
const noEvent = { addEventListener: () => () => {} };
|
||||
const real = createCesiumCamera({
|
||||
scene: {
|
||||
postUpdate: noEvent,
|
||||
preUpdate: noEvent,
|
||||
get screenSpaceCameraController() {
|
||||
return scene.screenSpaceCameraController;
|
||||
},
|
||||
requestRender: () => scene.requestRender?.(),
|
||||
},
|
||||
camera,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}).port;
|
||||
const port = Object.create(real, {
|
||||
on: { value: (event, cb) => camera[event].addEventListener(cb) },
|
||||
});
|
||||
cameraPorts.set(camera, port);
|
||||
bindRenderer(viewer, {
|
||||
camera: port,
|
||||
get canvas() {
|
||||
return scene.canvas;
|
||||
},
|
||||
frame: {
|
||||
on: () => () => {},
|
||||
requestRender: () => scene.requestRender?.(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// The frame measures take a camera pose; these take the test's camera.
|
||||
const poseOf = (camera) => cameraPorts.get(camera).pose();
|
||||
const LOOKS = {
|
||||
lookUp: 'up',
|
||||
lookDown: 'down',
|
||||
lookLeft: 'left',
|
||||
lookRight: 'right',
|
||||
};
|
||||
const globeFrameShare = (camera, options) =>
|
||||
globeInView.globeFrameShare(poseOf(camera), options);
|
||||
const globeOutOfFrame = (camera, options) =>
|
||||
globeInView.globeOutOfFrame(poseOf(camera), options);
|
||||
const lookAngleWithinFrame = (camera, look, angle, options) =>
|
||||
globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options);
|
||||
const lookStepLosesGlobe = (camera, look, angle, options) =>
|
||||
globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options);
|
||||
|
||||
const phases = ['Scene', 'Controls', 'Data', 'Tools'];
|
||||
function fixture(overrides = {}) {
|
||||
@@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer',
|
||||
});
|
||||
|
||||
test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => {
|
||||
const { applicationViewerOptions } = await import('./viewer.js');
|
||||
const { StarrySky } = await import('../sky/starrySky.js');
|
||||
const { applicationViewerOptions } =
|
||||
await import('../render/cesium/applicationViewer.js');
|
||||
const { StarrySky } = await import('../render/cesium/starrySky.js');
|
||||
const creditContainer = {};
|
||||
const options = applicationViewerOptions(creditContainer);
|
||||
// CesiumWidget skips scene.sun and scene.moon when skyBox is false.
|
||||
@@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) {
|
||||
return { viewer, controller, container, handlers, relayed, createEvent };
|
||||
}
|
||||
|
||||
test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => {
|
||||
test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => {
|
||||
const original = [1, 2, 3];
|
||||
const f = pinchFixture({ zoomEventTypes: original });
|
||||
const dispose = installTrackpadPinchZoom(f.viewer, {
|
||||
const dispose = installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent: (_type, init) => f.createEvent(init),
|
||||
});
|
||||
assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original);
|
||||
assert.equal(f.controller.zoomEventTypes.length, 4);
|
||||
assert.equal(f.controller.zoomEventTypes, original);
|
||||
|
||||
const plain = f.createEvent({ deltaY: 2 });
|
||||
f.container.emit(plain);
|
||||
@@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs
|
||||
|
||||
test('trackpad pinch relays pixel deltas once with bounded amplification', () => {
|
||||
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
|
||||
installTrackpadPinchZoom(f.viewer, {
|
||||
installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent: (_type, init) => f.createEvent(init),
|
||||
});
|
||||
|
||||
@@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () =>
|
||||
|
||||
test('trackpad pinch falls back to the original event when relay construction fails', () => {
|
||||
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
|
||||
installTrackpadPinchZoom(f.viewer, {
|
||||
installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent() {
|
||||
throw new Error('unsupported');
|
||||
},
|
||||
@@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) {
|
||||
|
||||
test('free look follows camera height and is restored on dispose', () => {
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(f.controller.enableLook, true);
|
||||
|
||||
f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1);
|
||||
@@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => {
|
||||
test('drags that start on the stars orbit above the free-look height', () => {
|
||||
// Below Cesium's trackball height such a drag turns the camera in place.
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(
|
||||
f.controller.minimumTrackBallHeight,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
@@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
|
||||
const lower = freeLookFixture({ height: 500 });
|
||||
lower.controller.minimumTrackBallHeight = 500_000;
|
||||
const disposeLower = installFreeLookHeightLimit(lower.viewer);
|
||||
const disposeLower = installFreeLookHeightLimit(
|
||||
lower.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(
|
||||
lower.controller.minimumTrackBallHeight,
|
||||
500_000,
|
||||
@@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
assert.equal(lower.controller.minimumTrackBallHeight, 500_000);
|
||||
|
||||
const later = freeLookFixture({ height: 500 });
|
||||
const disposeLater = installFreeLookHeightLimit(later.viewer);
|
||||
const disposeLater = installFreeLookHeightLimit(
|
||||
later.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
later.controller.minimumTrackBallHeight = 2_000_000;
|
||||
disposeLater();
|
||||
assert.equal(
|
||||
@@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
|
||||
test('free look keeps a setting other code makes after it is installed', () => {
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
f.controller.enableLook = false;
|
||||
f.frame(10);
|
||||
assert.equal(f.controller.enableLook, false, 'turned off stays off');
|
||||
@@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => {
|
||||
|
||||
test('free look stays off when the viewer had it disabled', () => {
|
||||
const f = freeLookFixture({ enableLook: false, height: 500 });
|
||||
installFreeLookHeightLimit(f.viewer);
|
||||
installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS);
|
||||
f.frame(10);
|
||||
assert.equal(f.controller.enableLook, false);
|
||||
});
|
||||
@@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) {
|
||||
};
|
||||
const camera = new Cesium.Camera(scene);
|
||||
camera.frustum.aspectRatio = width / height;
|
||||
return { camera, scene, viewer: { camera, scene } };
|
||||
const viewer = { camera, scene };
|
||||
bindCameraPorts(viewer);
|
||||
return { camera, scene, viewer };
|
||||
}
|
||||
|
||||
function aim(
|
||||
@@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => {
|
||||
Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3),
|
||||
);
|
||||
assert.equal(globeOutOfFrame(camera), false);
|
||||
assert.equal(scene.renders, 1);
|
||||
// One render for the new view, one the recovery asks for itself.
|
||||
assert.equal(scene.renders, 2, 'the turned view is drawn');
|
||||
|
||||
// Looking up near the ground, then zoomed out past the limit.
|
||||
aim(camera, { alt: 3_834_000, pitch: 10 });
|
||||
@@ -602,7 +674,7 @@ function moveEndKeepsView(camera) {
|
||||
return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9);
|
||||
}
|
||||
|
||||
test('globe recovery leaves partial, low, locked and 2D views alone', () => {
|
||||
test('globe recovery leaves partial, low, locked and following views alone', () => {
|
||||
for (const view of partialGlobeViews) {
|
||||
const { camera, viewer } = realCamera();
|
||||
installGlobeInViewRecovery(viewer);
|
||||
@@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => {
|
||||
assert.equal(globeOutOfFrame(locked.camera), true);
|
||||
assert.ok(moveEndKeepsView(locked.camera), 'locked camera');
|
||||
|
||||
// Tracking an entity that has no position yet keeps an identity transform.
|
||||
// Following an entity that has no position yet keeps an identity transform.
|
||||
const tracked = realCamera();
|
||||
tracked.viewer.trackedEntity = { id: 'pending-fix' };
|
||||
const pending = entityFollowTarget(
|
||||
{ id: 'pending-fix' },
|
||||
{ position: () => null },
|
||||
);
|
||||
Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', {
|
||||
get: () => pending,
|
||||
});
|
||||
installGlobeInViewRecovery(tracked.viewer);
|
||||
aim(tracked.camera, reportedStuckView);
|
||||
assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera');
|
||||
|
||||
const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW });
|
||||
installGlobeInViewRecovery(flat.viewer);
|
||||
flat.scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
aim(flat.camera, reportedStuckView);
|
||||
flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
|
||||
assert.ok(moveEndKeepsView(flat.camera), 'Columbus view');
|
||||
});
|
||||
|
||||
test('the look limit from orbit tolerates grid noise and never reaches zero', () => {
|
||||
|
||||
Vendored
+28
-20
@@ -1,8 +1,11 @@
|
||||
import { catalogControlServices } from './catalog.js';
|
||||
import { StyleManager } from '../ui/composition.js';
|
||||
import { flyToAustin } from '../camera.js';
|
||||
import { installZoomOutGuard } from './zoomOutGuard.js';
|
||||
import { applyStartView, START_VIEW } from '../camera.js';
|
||||
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
|
||||
import { createViewSky } from '../viewSky.js';
|
||||
import { findGlobe } from '../render/rendererOf.js';
|
||||
import { useDisplayStore } from '../ui/stores/display.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -10,12 +13,13 @@ import { t } from '../i18n/index.js';
|
||||
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
|
||||
* whose address does not carry one. `localePicker: false` removes the language
|
||||
* picker, for a host that offers its own language choice (`switchLocale` from
|
||||
* the `./i18n` entry).
|
||||
* the `./i18n` entry). `startView` is where the camera starts (the whole
|
||||
* planet by default; a host may pass a city); a shared view flies from there.
|
||||
* `services.cockpitSubjects` adds the application's own first-person subjects
|
||||
* to the Cockpit (src/cockpitSubjectProviders.js).
|
||||
*/
|
||||
export function createApplicationControls({
|
||||
scene: { viewer, mapStackController, operations },
|
||||
scene: { viewer, mapStackController, operations, viewerDrawsEntity },
|
||||
loaderStatus,
|
||||
Controls = StyleManager,
|
||||
services,
|
||||
@@ -24,7 +28,10 @@ export function createApplicationControls({
|
||||
defer,
|
||||
initialShareCode = null,
|
||||
localePicker = true,
|
||||
startView = START_VIEW,
|
||||
}) {
|
||||
// Every boot starts from the same view, before share restoration flies on.
|
||||
applyStartView(viewer, startView);
|
||||
// Initialize the style manager (post-processing, HUD, locations, share links)
|
||||
const styleManager = new Controls(viewer, {
|
||||
services: {
|
||||
@@ -34,6 +41,8 @@ export function createApplicationControls({
|
||||
fetchRegionalBrief: (...args) =>
|
||||
operations.requests.regional.getBrief(...args),
|
||||
...catalogControlServices(catalog),
|
||||
// Whether an entity is one of the viewer's own; the scene answers it.
|
||||
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
|
||||
},
|
||||
requestServices: operations.requests,
|
||||
mapStackController,
|
||||
@@ -45,28 +54,27 @@ export function createApplicationControls({
|
||||
defer(() => styleManager.orbitController.stop());
|
||||
defer(() => styleManager.hud.destroy());
|
||||
defer(() => styleManager.dispose());
|
||||
defer(
|
||||
installZoomOutGuard(viewer, {
|
||||
subscribeCameraHandoff: (listener) =>
|
||||
styleManager.subscribeCameraHandoff?.(listener),
|
||||
}),
|
||||
);
|
||||
// The previous multi-canvas weather compositor remains disabled. Cockpit
|
||||
// clouds use a separate, capped low-resolution GPU pass that never attaches
|
||||
// Cesium fog or post-process stages and is fully stopped in map mode.
|
||||
const weatherEffects = null;
|
||||
const cockpitCloudEffects = initCockpitCloudEffects(viewer, {
|
||||
weatherService: operations.requests.weather,
|
||||
});
|
||||
// Where the renderer draws weather, it draws the cockpit's clouds too.
|
||||
const cockpitCloudEffects = findGlobe(viewer)?.weather
|
||||
? null
|
||||
: initCockpitCloudEffects(viewer, {
|
||||
weatherService: operations.requests.weather,
|
||||
});
|
||||
defer(() => cockpitCloudEffects?.destroy());
|
||||
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
|
||||
// chooses in the Display panel.
|
||||
const viewSky = createViewSky(viewer, {
|
||||
store: useDisplayStore(applicationPinia()),
|
||||
});
|
||||
defer(() => viewSky.destroy());
|
||||
|
||||
// If no share link state, do default fly-to Austin
|
||||
if (!styleManager.hasShareState) {
|
||||
loaderStatus.textContent = t('Flying to Austin, TX...');
|
||||
defer(flyToAustin(viewer));
|
||||
} else {
|
||||
loaderStatus.textContent = t('Restoring shared view...');
|
||||
}
|
||||
loaderStatus.textContent = styleManager.hasShareState
|
||||
? t('Restoring shared view...')
|
||||
: t('Loading');
|
||||
|
||||
return { styleManager, weatherEffects, cockpitCloudEffects };
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import test, { after, before } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import '../testSupport/stubMgrs.mjs';
|
||||
import { installVueDom } from '../testSupport/vueDom.mjs';
|
||||
import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
const { createApplicationControls } = await import('./controls.js');
|
||||
|
||||
@@ -13,35 +12,20 @@ before(() => {
|
||||
});
|
||||
after(() => uninstallDom());
|
||||
|
||||
test('application controls install the zoom-out guard and remove it on teardown', () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
const controller = { maximumZoomDistance: Infinity };
|
||||
const scene = {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
screenSpaceCameraController: controller,
|
||||
preRender: new Cesium.Event(),
|
||||
postUpdate: new Cesium.Event(),
|
||||
};
|
||||
const camera = {
|
||||
position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000),
|
||||
positionCartographic: { height: 1_000_000 },
|
||||
};
|
||||
const viewer = { scene, camera, canvas };
|
||||
const handoffs = new Set();
|
||||
test('the application controls start and stop', () => {
|
||||
class Controls {
|
||||
hasShareState = true;
|
||||
orbitController = { stop() {} };
|
||||
hud = { destroy() {} };
|
||||
dispose() {}
|
||||
subscribeCameraHandoff(listener) {
|
||||
handoffs.add(listener);
|
||||
return () => handoffs.delete(listener);
|
||||
}
|
||||
}
|
||||
const cleanups = [];
|
||||
createApplicationControls({
|
||||
scene: {
|
||||
viewer,
|
||||
viewer: bindFakeCesiumCamera({
|
||||
isDestroyed: () => false,
|
||||
camera: { setView() {} },
|
||||
}),
|
||||
mapStackController: {},
|
||||
operations: {
|
||||
surface: { controlServices: {} },
|
||||
@@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown'
|
||||
catalog: { get: (id) => ({ id }) },
|
||||
defer: (cleanup) => cleanups.push(cleanup),
|
||||
});
|
||||
|
||||
assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
|
||||
assert.equal(scene.preRender.numberOfListeners, 1);
|
||||
assert.equal(scene.postUpdate.numberOfListeners, 1);
|
||||
assert.equal(handoffs.size, 1);
|
||||
|
||||
for (const cleanup of cleanups.reverse()) cleanup();
|
||||
assert.equal(controller.maximumZoomDistance, Infinity);
|
||||
assert.equal(scene.preRender.numberOfListeners, 0);
|
||||
assert.equal(scene.postUpdate.numberOfListeners, 0);
|
||||
assert.equal(handoffs.size, 0);
|
||||
});
|
||||
+1
-1
@@ -15,7 +15,7 @@ export function createApplicationData({
|
||||
const dataManager = new LayerLifecycle(viewer, {
|
||||
allowQaRegistration,
|
||||
// A panel's host may report it hidden while it is on screen; its layers
|
||||
// keep polling (see keepPanelRendering in embed.js).
|
||||
// keep polling (see keepPanelRendering in app/panelRendering.js).
|
||||
visibilityTarget: panelAwareVisibility(document),
|
||||
getSourceAvailability: catalog?.getSourceAvailability,
|
||||
});
|
||||
|
||||
+24
-65
@@ -11,13 +11,14 @@
|
||||
* embedded or not.
|
||||
*/
|
||||
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
announceNavigationAuthority,
|
||||
watchCameraOwner,
|
||||
} from '../navigationPolicy.js';
|
||||
import { toRadians } from '../geo/index.js';
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js';
|
||||
import { cameraOf } from '../render/rendererOf.js';
|
||||
import {
|
||||
annotationsFromParams,
|
||||
createView,
|
||||
@@ -69,7 +70,8 @@ function isFreshPanelResult() {
|
||||
|
||||
/**
|
||||
* `doc`'s visibility for work that pauses in a hidden page. A panel's host
|
||||
* may report it hidden while it is on screen (see keepPanelRendering), so an
|
||||
* may report it hidden while it is on screen (see keepPanelRendering in
|
||||
* render/cesium/panelRendering.js), so an
|
||||
* inline panel always reads as visible.
|
||||
*/
|
||||
export function panelAwareVisibility(doc = globalThis.document) {
|
||||
@@ -89,52 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) {
|
||||
};
|
||||
}
|
||||
|
||||
// A panel keeps drawing at about this rate when its host stops animation
|
||||
// frames; see keepPanelRendering.
|
||||
const PANEL_FRAME_MS = 33;
|
||||
const MISSED_FRAMES_MS = 250;
|
||||
|
||||
/**
|
||||
* Keep the globe drawing in an inline panel. Some hosts report a panel on
|
||||
* screen as hidden, which stops the browser's animation frames and with them
|
||||
* Cesium's render loop; while frames stop arriving, draw from a timer.
|
||||
* Returns a function that stops it.
|
||||
*/
|
||||
export function keepPanelRendering(
|
||||
viewer,
|
||||
{ windowRef = globalThis.window, now = () => performance.now() } = {},
|
||||
) {
|
||||
let lastFrame = now();
|
||||
let frameRequest = null;
|
||||
const onFrame = () => {
|
||||
lastFrame = now();
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
};
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
// Cesium stops its render loop after a render error, and the timer stops
|
||||
// with it; Retry restarts both. The render failure notice logs the error
|
||||
// (src/ui/renderFailure.js).
|
||||
const timer = windowRef.setInterval(() => {
|
||||
if (
|
||||
viewer.useDefaultRenderLoop === false ||
|
||||
now() - lastFrame < MISSED_FRAMES_MS ||
|
||||
viewer.isDestroyed?.()
|
||||
)
|
||||
return;
|
||||
try {
|
||||
viewer.resize();
|
||||
viewer.render();
|
||||
} catch {
|
||||
// Raised as a render error by now (src/ui/renderFailure.js), which
|
||||
// stops this timer; thrown on, it would only reach the host page.
|
||||
}
|
||||
}, PANEL_FRAME_MS);
|
||||
return () => {
|
||||
windowRef.clearInterval(timer);
|
||||
windowRef.cancelAnimationFrame(frameRequest);
|
||||
};
|
||||
}
|
||||
|
||||
const delay = (ms, signal) =>
|
||||
new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms);
|
||||
@@ -152,21 +108,19 @@ const delay = (ms, signal) =>
|
||||
function flyTo(viewer, camera) {
|
||||
announceNavigationAuthority('embed-view');
|
||||
return new Promise((resolve) => {
|
||||
viewer.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(
|
||||
camera.lon,
|
||||
camera.lat,
|
||||
camera.altitude_m,
|
||||
),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(camera.heading_deg),
|
||||
pitch: Cesium.Math.toRadians(camera.pitch_deg),
|
||||
roll: 0,
|
||||
cameraOf(viewer).flyTo(
|
||||
{ lon: camera.lon, lat: camera.lat, height: camera.altitude_m },
|
||||
{
|
||||
orientation: {
|
||||
heading: toRadians(camera.heading_deg),
|
||||
pitch: toRadians(camera.pitch_deg),
|
||||
roll: 0,
|
||||
},
|
||||
durationS: FLIGHT_SECONDS,
|
||||
onComplete: () => resolve(true),
|
||||
onCancel: () => resolve(false),
|
||||
},
|
||||
duration: FLIGHT_SECONDS,
|
||||
complete: () => resolve(true),
|
||||
cancel: () => resolve(false),
|
||||
});
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -314,6 +268,9 @@ export async function applyView(
|
||||
/**
|
||||
* Install embed mode when the page asks for it, and draw any annotations the
|
||||
* opening link carries. Returns a function that removes the message handler.
|
||||
* `keepRendering({windowRef})` keeps the globe drawing in an inline panel
|
||||
* whose host stops animation frames, and returns a function that stops it;
|
||||
* the application scene gives it (`keepPanelRendering`).
|
||||
*/
|
||||
export function installViews({
|
||||
shell,
|
||||
@@ -321,6 +278,7 @@ export function installViews({
|
||||
dataManager,
|
||||
run,
|
||||
signal,
|
||||
keepRendering = null,
|
||||
terrain = null,
|
||||
location = globalThis.location,
|
||||
windowRef = globalThis.window,
|
||||
@@ -433,9 +391,10 @@ export function installViews({
|
||||
|
||||
windowRef.document.body.classList.add('ui-embed');
|
||||
shell.setCleanView?.(true);
|
||||
const stopRendering = isEmbeddedInline()
|
||||
? keepPanelRendering(viewer, { windowRef })
|
||||
: () => {};
|
||||
const stopRendering =
|
||||
isEmbeddedInline() && keepRendering
|
||||
? keepRendering({ windowRef })
|
||||
: () => {};
|
||||
// A framing page talks to the app across frames; an inline panel shares
|
||||
// the page with it and talks through the page's own window.
|
||||
const peer = isEmbeddedInline() ? windowRef : windowRef.parent;
|
||||
|
||||
+11
-57
@@ -1,10 +1,10 @@
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
applyView,
|
||||
installViews,
|
||||
isEmbedded,
|
||||
keepPanelRendering,
|
||||
panelAwareVisibility,
|
||||
} from './embed.js';
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
@@ -12,7 +12,7 @@ import { createView, viewToParams } from '../view/index.js';
|
||||
|
||||
const fakeViewer = () => {
|
||||
const flights = [];
|
||||
return {
|
||||
return bindFakeCesiumCamera({
|
||||
flights,
|
||||
camera: {
|
||||
flyTo(options) {
|
||||
@@ -20,7 +20,7 @@ const fakeViewer = () => {
|
||||
options.complete();
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
const fakeLayers = (enabled) => ({
|
||||
getAll: () =>
|
||||
@@ -329,6 +329,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
globalThis.GEV_EMBED_INLINE = true;
|
||||
try {
|
||||
assert.equal(isEmbedded({ search: '' }), true);
|
||||
const kept = [];
|
||||
const remove = installViews({
|
||||
shell: { initialRestorePromise: Promise.resolve() },
|
||||
viewer: fakeViewer(),
|
||||
@@ -336,7 +337,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
run: recorder().run,
|
||||
location: { search: '', hash: '' },
|
||||
windowRef,
|
||||
// The scene's panel rendering, kept on while the views are installed.
|
||||
keepRendering: (options) => {
|
||||
kept.push(options.windowRef === windowRef);
|
||||
return () => kept.push('stopped');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(kept, [true]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual(posted, [{ type: 'gev:ready' }]);
|
||||
const event = new Event('message');
|
||||
@@ -349,6 +356,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
assert.equal(posted[1].id, 7);
|
||||
assert.equal(posted[1].ok, true);
|
||||
remove();
|
||||
assert.deepEqual(kept, [true, 'stopped']);
|
||||
} finally {
|
||||
delete globalThis.GEV_EMBED_INLINE;
|
||||
}
|
||||
@@ -427,60 +435,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async
|
||||
]);
|
||||
});
|
||||
|
||||
test('a panel keeps drawing from a timer while animation frames stop', () => {
|
||||
let clock = 0;
|
||||
let tick = null;
|
||||
let frame = null;
|
||||
const windowRef = {
|
||||
requestAnimationFrame: (fn) => ((frame = fn), 1),
|
||||
cancelAnimationFrame: () => (frame = null),
|
||||
setInterval: (fn) => ((tick = fn), 1),
|
||||
clearInterval: () => (tick = null),
|
||||
};
|
||||
const drawn = [];
|
||||
const viewer = {
|
||||
resize: () => drawn.push('resize'),
|
||||
render: () => drawn.push('render'),
|
||||
};
|
||||
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
|
||||
// Frames arrive: the render loop draws, so the timer does nothing.
|
||||
clock = 100;
|
||||
frame();
|
||||
tick();
|
||||
assert.deepEqual(drawn, []);
|
||||
// Frames stop, as in a panel its host reports hidden: the timer draws.
|
||||
clock = 400;
|
||||
tick();
|
||||
assert.deepEqual(drawn, ['resize', 'render']);
|
||||
stop();
|
||||
assert.equal(tick, null);
|
||||
assert.equal(frame, null);
|
||||
});
|
||||
|
||||
test('a panel stops drawing while its render loop is stopped', () => {
|
||||
let tick = null;
|
||||
const windowRef = {
|
||||
requestAnimationFrame: () => 1,
|
||||
cancelAnimationFrame() {},
|
||||
setInterval: (fn) => ((tick = fn), 1),
|
||||
clearInterval() {},
|
||||
};
|
||||
const drawn = [];
|
||||
const viewer = { resize() {}, render: () => drawn.push('render') };
|
||||
let clock = 0;
|
||||
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
|
||||
// Cesium stops its render loop after a render error.
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
clock = 1000;
|
||||
tick();
|
||||
assert.deepEqual(drawn, []);
|
||||
// Retry restarts it, and the timer draws again.
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
tick();
|
||||
assert.deepEqual(drawn, ['render']);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => {
|
||||
const viewer = fakeViewer();
|
||||
const { calls, run } = recorder();
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* @module app/globeInViewRecovery
|
||||
* @description Turns the camera back to the planet when a move ends looking
|
||||
* away from it, through the renderer's camera and frame ports.
|
||||
*/
|
||||
import { PI_OVER_TWO } from '../geo/vector.js';
|
||||
import {
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
globeOutOfFrame,
|
||||
isFreeGlobeCamera,
|
||||
} from '../globeInView.js';
|
||||
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
|
||||
|
||||
/** Whether two vectors agree to `tolerance` in every component. */
|
||||
const within = (a, b, tolerance) =>
|
||||
Math.abs(a.x - b.x) <= tolerance &&
|
||||
Math.abs(a.y - b.y) <= tolerance &&
|
||||
Math.abs(a.z - b.z) <= tolerance;
|
||||
|
||||
// How often a moving camera is sampled to see whether it has come to rest, how
|
||||
// far a pose may drift between samples and still count as at rest, and how
|
||||
// long after the camera last moved the check gives up if the camera never
|
||||
// raises moveEnd.
|
||||
const SETTLE_SAMPLE_MS = 250;
|
||||
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
|
||||
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
|
||||
const SETTLE_GIVE_UP_MS = 5 * 60_000;
|
||||
|
||||
/**
|
||||
* Turn the camera back to the planet when a move ends above `minHeight` with
|
||||
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
|
||||
* one sample cell thick can count as none), and return the disposer. Views with
|
||||
* more surface, such as an oblique orbital shot, are left as they are. This
|
||||
* catches a saved or shared view that looked away, or any other move that ends
|
||||
* looking away from the planet.
|
||||
* Heading and position are kept. Following cameras, locked ones (a target's
|
||||
* frame), a camera flight in progress, a pointer held down on the canvas
|
||||
* (a drag held still), and any time `paused`
|
||||
* returns true (an authored scene playing) are left alone; a check they defer
|
||||
* runs once they end, however long they last.
|
||||
* `keyholeRadius`
|
||||
* returns the radius of the visible circle when a scope mask hides the rest of
|
||||
* the frame (see `globeFrameShare`), or 0; it is read at every check.
|
||||
*
|
||||
* The camera's `moveEnd` alone is not enough: the default renderer compares
|
||||
* the camera with the last frame's to the last rounding error, and at some of
|
||||
* these poses the camera drifts by a rounding error every frame, so it never
|
||||
* sees it stop.
|
||||
* So each `moveStart` also starts a check of its own that samples the pose
|
||||
* every 250 ms, with a tolerance for that drift, and once the pose has held
|
||||
* for half a second after moving runs the same recovery. It keeps watching
|
||||
* until the camera raises `moveEnd`, since under that drift it raises no new
|
||||
* `moveStart` for a later move, and gives up five minutes after the camera
|
||||
* last moved.
|
||||
* `setTimeout` and `clearTimeout` can be injected for tests.
|
||||
*/
|
||||
export function installGlobeInViewRecovery(
|
||||
viewer,
|
||||
{
|
||||
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
keyholeRadius = () => 0,
|
||||
paused = () => false,
|
||||
setTimeout: schedule = globalThis.setTimeout,
|
||||
clearTimeout: unschedule = globalThis.clearTimeout,
|
||||
} = {},
|
||||
) {
|
||||
const camera = findCamera(viewer);
|
||||
if (!camera) throw new TypeError('A viewer with a camera is required');
|
||||
|
||||
// A pointer held on the globe is a gesture in progress, even when it holds
|
||||
// still for half a second: the check waits until every pointer pressed on
|
||||
// it (each finger of a pinch) is released. A release the page never sees,
|
||||
// outside the window, is taken as given when the window loses focus, the
|
||||
// page is hidden, the canvas loses the pointer's capture, or the pointer
|
||||
// moves with no button down.
|
||||
const canvas = canvasOf(viewer);
|
||||
const releaseTarget = canvas?.ownerDocument ?? canvas;
|
||||
const releaseWindow = canvas?.ownerDocument?.defaultView;
|
||||
const heldPointers = new Set();
|
||||
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
|
||||
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
|
||||
const onPointerMove = (event) => {
|
||||
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
|
||||
};
|
||||
const releaseAll = () => heldPointers.clear();
|
||||
const onVisibilityChange = () => {
|
||||
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
|
||||
};
|
||||
const listeners = [
|
||||
[canvas, 'pointerdown', onPointerDown],
|
||||
[canvas, 'lostpointercapture', onPointerUp],
|
||||
[releaseTarget, 'pointerup', onPointerUp],
|
||||
[releaseTarget, 'pointercancel', onPointerUp],
|
||||
[releaseTarget, 'pointermove', onPointerMove],
|
||||
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
|
||||
[releaseWindow, 'blur', releaseAll],
|
||||
];
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.addEventListener?.(type, listener);
|
||||
|
||||
// Returns false while a flight, a paused scene or a held pointer defers the
|
||||
// check, so the caller can try again once it ends.
|
||||
const recover = () => {
|
||||
if (!isFreeGlobeCamera(viewer)) return true;
|
||||
if (camera.flying || paused() || heldPointers.size > 0) return false;
|
||||
const pose = camera.pose();
|
||||
if (
|
||||
!(pose.height > minHeight) ||
|
||||
!globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() })
|
||||
)
|
||||
return true;
|
||||
camera.setView({
|
||||
orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 },
|
||||
});
|
||||
findFrame(viewer)?.requestRender?.('globe-in-view');
|
||||
return true;
|
||||
};
|
||||
|
||||
let lastPosition = null;
|
||||
let lastDirection = null;
|
||||
const remember = () => {
|
||||
({ position: lastPosition, direction: lastDirection } = camera.pose());
|
||||
};
|
||||
let settleTimer = null;
|
||||
let settleElapsed = 0;
|
||||
let restingSamples = 0;
|
||||
let movedSinceCheck = false;
|
||||
const stopSettling = () => {
|
||||
if (settleTimer !== null) unschedule(settleTimer);
|
||||
settleTimer = null;
|
||||
};
|
||||
const sample = () => {
|
||||
settleTimer = null;
|
||||
settleElapsed += SETTLE_SAMPLE_MS;
|
||||
const now = camera.pose();
|
||||
const atRest =
|
||||
within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) &&
|
||||
within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE);
|
||||
restingSamples = atRest ? restingSamples + 1 : 0;
|
||||
if (!atRest) {
|
||||
movedSinceCheck = true;
|
||||
settleElapsed = 0;
|
||||
}
|
||||
// Two quiet samples in a row after a move: at rest for half a second, as
|
||||
// for moveEnd.
|
||||
if (restingSamples >= 2 && movedSinceCheck) {
|
||||
if (recover()) movedSinceCheck = false;
|
||||
// A flight or a playing scene bounds its own deferral.
|
||||
else settleElapsed = 0;
|
||||
}
|
||||
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
|
||||
remember();
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const startSettling = () => {
|
||||
stopSettling();
|
||||
settleElapsed = 0;
|
||||
restingSamples = 0;
|
||||
movedSinceCheck = true;
|
||||
remember();
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const removeMoveEnd = camera.on('moveEnd', () => {
|
||||
if (recover()) stopSettling();
|
||||
// Deferred: keep sampling so the check runs once the flight or scene ends.
|
||||
else if (settleTimer === null) startSettling();
|
||||
});
|
||||
const removeMoveStart = camera.on('moveStart', startSettling);
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
stopSettling();
|
||||
removeMoveEnd();
|
||||
removeMoveStart();
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.removeEventListener?.(type, listener);
|
||||
heldPointers.clear();
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire FAA special-use airspace into the application catalog. */
|
||||
export function createApplicationDroneAirspace(options) {
|
||||
@@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
@@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory:
|
||||
options.screenSpaceEventHandlerFactory ??
|
||||
((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)),
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire the S2 Underground GhostMaps layer into the application catalog. */
|
||||
export function createApplicationGhostMaps(options) {
|
||||
@@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) {
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
createFirePerimetersLayer,
|
||||
createInciwebIndexSource,
|
||||
@@ -6,7 +5,6 @@ import {
|
||||
} from '../../layers/perimeters/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
@@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) {
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { fleetModelServices } from './fleetModels.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { applyTrackedCameraFrame } from '../../data/trackedCamera.js';
|
||||
import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js';
|
||||
import {
|
||||
railFeedCredit,
|
||||
@@ -52,7 +51,6 @@ export function createApplicationRail({
|
||||
camera: {
|
||||
framing: WORLD_FOCUS_FRAMING.train,
|
||||
requestWorldFocus,
|
||||
applyTrackedCameraFrame,
|
||||
isCockpitActive: () =>
|
||||
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
|
||||
true,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
@@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) {
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
|
||||
@@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
|
||||
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
|
||||
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
|
||||
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as input from '../../data/inputOwnership.js';
|
||||
import * as scenePick from '../../data/scenePick.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
|
||||
@@ -37,6 +35,6 @@ export function createApplicationStreetLevel({
|
||||
}) {
|
||||
return createStreetLevelLayer({
|
||||
providers,
|
||||
services: { sprites, picking, input, scenePick, render },
|
||||
services: { picking, scenePick, render },
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
|
||||
import { overlayHost } from './overlayHost.js';
|
||||
/** Wire cable source geometry to the application overlay host. */
|
||||
export function createApplicationCables(options) {
|
||||
return createSubmarineCableLayer({
|
||||
overlayHost,
|
||||
screenSpaceEventHandlerFactory: (canvas) =>
|
||||
new Cesium.ScreenSpaceEventHandler(canvas),
|
||||
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
|
||||
...options,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
@@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
sprites,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
|
||||
import { governorRequestRender } from '../renderGovernor.js';
|
||||
import {
|
||||
clearSelectedEntityContextForLayer,
|
||||
getSelectedEntityContext,
|
||||
registerEntityContext,
|
||||
removeEntityContextsForLayer,
|
||||
selectEntityContext,
|
||||
@@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({
|
||||
setVisible: setOverlaySourceVisible,
|
||||
}),
|
||||
clearSelectedEntityContextForLayer,
|
||||
getSelectedEntityContext,
|
||||
registerEntityContext,
|
||||
removeEntityContextsForLayer,
|
||||
selectEntityContext,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MapStackController } from '../mapStackController.js';
|
||||
import '../render/cesium/mapEngine.js';
|
||||
import {
|
||||
installRenderGovernor,
|
||||
uninstallRenderGovernor,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
governorRequestRender,
|
||||
getRenderGovernorDiagnostics,
|
||||
} from '../renderGovernor.js';
|
||||
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
|
||||
|
||||
test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => {
|
||||
let resolveProvider;
|
||||
@@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests
|
||||
},
|
||||
},
|
||||
};
|
||||
installRenderGovernor(viewer);
|
||||
installRenderGovernor(framePortFor(viewer.scene));
|
||||
holdContinuousRender('fixture');
|
||||
uninstallRenderGovernor({});
|
||||
uninstallRenderGovernor(framePortFor({}));
|
||||
assert.equal(getRenderGovernorDiagnostics().installed, true);
|
||||
uninstallRenderGovernor(viewer);
|
||||
uninstallRenderGovernor(framePortFor(viewer.scene));
|
||||
const before = renders;
|
||||
governorRequestRender('late');
|
||||
assert.equal(renders, before);
|
||||
|
||||
Loaded 100 of 1119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user