mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
The renderer seam: clicks go to the newest tool, recession and display groups through the contract, drawing at parity with Cesium
- Clicks: when two tools want the globe's clicks, the newest takes them and the older is told and turns itself off; a click is decided when it arrives, and ambient selection fires only when no tool holds the pointer. The "map is busy" paths and their strings are removed. - Recession: the limb fade is shared (src/render/recession.js) and reaches icon and model sets through SetSpec.recede; tuning applies on the next frame. - Display panel groups are published through src/ui/displayGroups.js; the Weather group and src/viewWeather.js are removed. - Draw port: a set whose icons only move is moved in place, and models that did not change are not restyled each frame, so moving fleets cost what they did when drawn directly; an untinted, fully opaque model is drawn without a colour. - Conformance: input.lease.lost checks the new lease inside onLost and reports a throwing onLost; draw.sets.recede covers model sets. - QA scripts read the renderer host instead of internals the seam replaced.
This commit is contained in:
1 parent
a0d299523d
commit
0ab31d4fb8
130 files changed
+5438
-1674
No files matched your search
@@ -111,6 +111,11 @@ jobs:
|
||||
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
|
||||
|
||||
+6
-5
@@ -58,11 +58,12 @@
|
||||
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. Where the renderer lists it, the view shows the conditions observed
|
||||
under the camera, asked again after five minutes or 25 km of movement, and
|
||||
the Display panel's Weather group can turn live weather off and set
|
||||
clouds, fog, rain and snow by hand. The Cesium renderer does not draw
|
||||
weather, and shows no Weather group (samehkhamis).
|
||||
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).
|
||||
- An application can add its own groups of toggles, sliders and notes to the
|
||||
Display panel under Effects, with `publishDisplayGroup` from
|
||||
`./ui/display/groups` (samehkhamis).
|
||||
- The globe opens at planet level, the whole Earth in view, on every
|
||||
renderer, instead of flying in to Austin. A shared link still flies from
|
||||
there to its view. An application can start somewhere else, a city for
|
||||
|
||||
+10
-3
@@ -53,11 +53,17 @@ const HARNESSES = {
|
||||
],
|
||||
};
|
||||
|
||||
/** Runs the logic suite on `which`; `all` runs every check, listed or not. */
|
||||
async function runLogic(which = 'stub', { all = false } = {}) {
|
||||
/**
|
||||
* 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 report = await runConformance(harness, all ? {} : options);
|
||||
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
|
||||
@@ -73,6 +79,7 @@ async function runLogic(which = 'stub', { all = false } = {}) {
|
||||
failed: report.failed,
|
||||
skipped: report.skipped,
|
||||
failures: report.results.filter((r) => r.status === 'fail'),
|
||||
skips: report.results.filter((r) => r.status === 'skip'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+6
-4
@@ -133,10 +133,12 @@ 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)` 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. `suspendCamera(reason)` and `suppressStockClicks()` return their
|
||||
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
|
||||
|
||||
+19
-11
@@ -4766,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
|
||||
@@ -6118,8 +6122,9 @@ 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; 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
|
||||
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
|
||||
@@ -7685,7 +7690,7 @@ 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 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 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.
|
||||
- **The pointer, for an application's own 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.
|
||||
@@ -7697,7 +7702,7 @@ request viewbox and continues searching without that geographic preference.
|
||||
- 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 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.** `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.
|
||||
- **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`.
|
||||
@@ -8090,7 +8095,10 @@ plus the renderer itself. `PORTS` lists every member at run time, and
|
||||
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. See
|
||||
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
|
||||
|
||||
+84
-14
@@ -6,7 +6,7 @@ it meets the contract. 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 four modules:
|
||||
The package exports these modules:
|
||||
|
||||
| Export | What it is |
|
||||
| ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
@@ -15,10 +15,31 @@ The package exports four modules:
|
||||
| `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
|
||||
these exports 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 of its own (a camera controller over a renderer without one) can
|
||||
take 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.
|
||||
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
|
||||
|
||||
@@ -98,6 +119,23 @@ optional, so a renderer written before it still conforms:
|
||||
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;
|
||||
@@ -142,13 +180,10 @@ 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` keeps and clamps them alike for the renderer
|
||||
(`mergeWeather`). The app's `src/viewWeather.js` sets the conditions observed
|
||||
under the camera (the weather service, through
|
||||
`deriveWeatherEffectProfile`), asking again after five minutes or 25 km,
|
||||
and none from orbit; the Display panel's Weather group turns live off and
|
||||
sets clouds, fog, rain and snow by hand, and shows only on a renderer that
|
||||
lists `weather`. The Cesium port does not list it. The strengths say what
|
||||
`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
|
||||
@@ -205,7 +240,7 @@ 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 and receding icons.
|
||||
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
|
||||
@@ -218,7 +253,7 @@ 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`, or moving, receding,
|
||||
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
|
||||
@@ -336,9 +371,35 @@ The rules that hold everywhere:
|
||||
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.
|
||||
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`.
|
||||
@@ -586,8 +647,10 @@ renderer under test:
|
||||
|
||||
Optional members widen what is checked: `pointer` for synthetic input,
|
||||
`cameraInput` (the camera answers that input: the drag and wheel traces
|
||||
run), `scriptHeights`, `assets.model`, and `assets.missingModel` (a model
|
||||
url that fails to load, for the `loadFailed` check). `pixels: false` says
|
||||
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.
|
||||
@@ -661,6 +724,13 @@ The scenes load nothing from the network.
|
||||
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
|
||||
|
||||
@@ -54,6 +54,7 @@
|
||||
"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",
|
||||
@@ -165,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",
|
||||
@@ -332,6 +334,18 @@
|
||||
"./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"
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"src/render/cesium/heights.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconAtlas.js",
|
||||
"src/data/iconSet.js",
|
||||
@@ -804,6 +805,37 @@
|
||||
"modules": ["src/ui/displayControls.js"],
|
||||
"external": []
|
||||
},
|
||||
"display-groups": {
|
||||
"exports": ["./ui/display/groups"],
|
||||
"modules": [
|
||||
"src/ui/displayGroups.js",
|
||||
"src/ui/vueRuntime.js",
|
||||
"src/ui/stores/display.js",
|
||||
"src/ui/stores/owners.js",
|
||||
"src/i18n/locale.js",
|
||||
"src/i18n/locales/ar.json",
|
||||
"src/i18n/locales/de.json",
|
||||
"src/i18n/locales/es.json",
|
||||
"src/i18n/locales/fr.json",
|
||||
"src/i18n/locales/it.json",
|
||||
"src/i18n/locales/he.json",
|
||||
"src/i18n/locales/ja.json",
|
||||
"src/i18n/locales/sv.json",
|
||||
"src/i18n/locales/pt.json",
|
||||
"src/i18n/locales/ru.json",
|
||||
"src/i18n/locales/zh-CN.json",
|
||||
"src/i18n/locales/uk.json",
|
||||
"src/i18n/locales/zh-Hant.json",
|
||||
"src/i18n/index.js",
|
||||
"src/ui/i18n.js"
|
||||
],
|
||||
"external": ["vue", "pinia", "vue-i18n"]
|
||||
},
|
||||
"weather-effects": {
|
||||
"exports": ["./render/weather", "./weather/effects"],
|
||||
"modules": ["src/render/weather.js", "src/weatherEffectsMath.js"],
|
||||
"external": []
|
||||
},
|
||||
"visual-effects": {
|
||||
"exports": ["./ui/effects", "./ui/effects/bloom"],
|
||||
"modules": [
|
||||
@@ -1068,6 +1100,7 @@
|
||||
"src/ui/cockpitCamera.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/data/iconAtlas.js",
|
||||
@@ -1261,6 +1294,7 @@
|
||||
"src/renderGovernor.js",
|
||||
"src/data/bundledJson.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/geo/julian.js",
|
||||
@@ -1637,6 +1671,7 @@
|
||||
"src/data/followed.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/data/iconSet.js",
|
||||
@@ -1825,6 +1860,7 @@
|
||||
"src/render/cesium/setBlend.js",
|
||||
"src/geo/screenCluster.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
"src/render/recession.js",
|
||||
"src/geo/polyline.js",
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/motion/iconMotion.js",
|
||||
@@ -1971,6 +2007,7 @@
|
||||
"src/render/cesium/setBlend.js",
|
||||
"src/geo/screenCluster.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
"src/render/recession.js",
|
||||
"src/geo/polyline.js",
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/motion/iconMotion.js",
|
||||
@@ -2129,6 +2166,7 @@
|
||||
"src/layers/vessels/iconBook.js",
|
||||
"src/data/entityRecords.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
"src/data/iconSegment.js",
|
||||
@@ -2291,6 +2329,7 @@
|
||||
"src/data/iconSet.js",
|
||||
"src/data/iconAtlas.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/render/motion/iconMotion.js",
|
||||
"src/render/cesium/heights.js",
|
||||
"src/render/baseTilesets.js",
|
||||
@@ -2347,6 +2386,7 @@
|
||||
"src/render/cesium/imageryFrames.js",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/geo/julian.js",
|
||||
@@ -2511,6 +2551,7 @@
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
"src/render/recession.js",
|
||||
"src/geo/polyline.js",
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/motion/iconMotion.js",
|
||||
@@ -2607,6 +2648,7 @@
|
||||
"src/layers/satellites/tracking.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -2697,6 +2739,7 @@
|
||||
"src/layers/launches/index.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/geo/julian.js",
|
||||
@@ -2796,6 +2839,7 @@
|
||||
"src/geo/geodesic.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconAtlas.js",
|
||||
"src/data/motionModel.js",
|
||||
@@ -3023,6 +3067,7 @@
|
||||
"src/layers/traffic/viewport.js",
|
||||
"src/render/rendererOf.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
@@ -3212,6 +3257,7 @@
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
"src/render/recession.js",
|
||||
"src/geo/polyline.js",
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/motion/iconMotion.js",
|
||||
@@ -3303,6 +3349,7 @@
|
||||
"src/layers/streetLevel/index.js",
|
||||
"src/render/cesium/credits.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -3534,6 +3581,7 @@
|
||||
"src/data/followed.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -3736,6 +3784,7 @@
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -3977,6 +4026,7 @@
|
||||
"src/hudLayoutPolicy.js",
|
||||
"src/ui/radioPanelPlacement.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/data/iconSegment.js",
|
||||
"src/data/iconAtlas.js",
|
||||
@@ -4686,7 +4736,6 @@
|
||||
"src/ui/geoFileImport.js",
|
||||
"src/data/routeSteps.js",
|
||||
"src/layers/directions/index.js",
|
||||
"src/data/pointerOwnerNames.js",
|
||||
"src/layers/directions/source.js",
|
||||
"src/data/directions.js",
|
||||
"src/app/layers/directions.js",
|
||||
@@ -5313,7 +5362,6 @@
|
||||
"src/data/openVesselPhoto.js",
|
||||
"src/layers/vessels/photos.js",
|
||||
"src/viewSky.js",
|
||||
"src/viewWeather.js",
|
||||
"src/render/weather.js",
|
||||
"src/layers/flights/placed.js",
|
||||
"src/data/placementProvider.js",
|
||||
@@ -5354,6 +5402,7 @@
|
||||
"src/data/aircraftMotionRegime.js",
|
||||
"src/geo/julian.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/data/iconSegment.js",
|
||||
"src/data/iconAtlas.js",
|
||||
@@ -5800,7 +5849,6 @@
|
||||
"src/services/groundFloor.js",
|
||||
"src/data/routeSteps.js",
|
||||
"src/layers/directions/index.js",
|
||||
"src/data/pointerOwnerNames.js",
|
||||
"src/layers/directions/source.js",
|
||||
"src/services/terrainHeights.js",
|
||||
"src/data/terrainHeights.js",
|
||||
@@ -6194,6 +6242,7 @@
|
||||
"src/locations.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -6352,6 +6401,7 @@
|
||||
"src/ui/navigationController.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -6642,7 +6692,6 @@
|
||||
"src/render/rendererOf.js",
|
||||
"src/geo/vector.js",
|
||||
"src/render/color.js",
|
||||
"src/data/pointerOwnerNames.js",
|
||||
"src/layers/directions/source.js",
|
||||
"src/data/routeSteps.js",
|
||||
"src/i18n/index.js",
|
||||
@@ -6991,6 +7040,7 @@
|
||||
"src/celestialRing.js",
|
||||
"src/render/cesium/camera.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -7167,6 +7217,7 @@
|
||||
"src/geo/rectangle.js",
|
||||
"src/render/rendererOf.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/iconSet.js",
|
||||
"src/geo/horizon.js",
|
||||
@@ -7518,6 +7569,7 @@
|
||||
"src/input/dispatcher.js",
|
||||
"src/render/cesium/drawHit.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
"src/data/aircraftRecession.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/data/iconSet.js",
|
||||
@@ -7923,7 +7975,17 @@
|
||||
"./render/occlusion",
|
||||
"./render/camera/events",
|
||||
"./render/camera/followTransition",
|
||||
"./render/conformance"
|
||||
"./render/conformance",
|
||||
"./render/input/router",
|
||||
"./render/stub/camera",
|
||||
"./render/stub/viewRectangle",
|
||||
"./render/stub/harness",
|
||||
"./render/motion",
|
||||
"./render/vectorBase",
|
||||
"./render/iconSegment",
|
||||
"./render/recession",
|
||||
"./render/windStreamlines",
|
||||
"./geo/screenCluster"
|
||||
],
|
||||
"modules": [
|
||||
"src/render/contract/index.js",
|
||||
@@ -7966,7 +8028,13 @@
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/render/vectorBase/encode.js",
|
||||
"src/render/weather.js"
|
||||
"src/render/weather.js",
|
||||
"src/render/stub/harness.js",
|
||||
"src/data/iconSegment.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/recession.js"
|
||||
],
|
||||
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
+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')) {
|
||||
|
||||
@@ -176,7 +176,8 @@ try {
|
||||
kind: 'pin',
|
||||
point: [+i.pos.lon.toFixed(6), +i.pos.lat.toFixed(6)],
|
||||
scale: i.scale ?? 1,
|
||||
heading: Math.round(i.course ?? 0),
|
||||
// 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'),
|
||||
})),
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -420,11 +420,13 @@ 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 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; !drawn && i < scene.primitives.length; i++) {
|
||||
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++)
|
||||
|
||||
@@ -169,7 +169,7 @@ try {
|
||||
result.bloom.intensityPct === 98 &&
|
||||
snapshot.bloom.intensity === 98 &&
|
||||
manager._visualEffects.bloomIntensity === 98 &&
|
||||
manager.viewer.scene.postProcessStages.bloom.enabled
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.enabled
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -184,7 +184,7 @@ try {
|
||||
manager.getVisualState().sharpen.intensity === 61 &&
|
||||
manager._visualEffects.sharpenIntensity === 0.61 &&
|
||||
Math.abs(
|
||||
manager.viewer.scene.postProcessStages.getStageByName(
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.getStageByName(
|
||||
'effects_sharpen',
|
||||
).uniforms.amount - 1.32,
|
||||
) < 1e-9
|
||||
@@ -203,7 +203,7 @@ try {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
const effects = manager._visualEffects;
|
||||
manager.setStyle('retro');
|
||||
const collection = manager.viewer.scene.postProcessStages;
|
||||
const collection = window.__godsEyeView.viewer.scene.postProcessStages;
|
||||
const owned = Object.keys(effects.stages).map((name) =>
|
||||
collection.getStageByName(`effects_style_${name}`),
|
||||
);
|
||||
|
||||
@@ -150,7 +150,9 @@ try {
|
||||
manager._bloomSlider.focus();
|
||||
return {
|
||||
value: Number(manager._bloomSlider.value),
|
||||
contrast: manager.viewer.scene.postProcessStages.bloom.uniforms.contrast,
|
||||
contrast:
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast,
|
||||
};
|
||||
});
|
||||
await page.keyboard.press('ArrowRight');
|
||||
@@ -160,8 +162,8 @@ try {
|
||||
const manager = window.__godsEyeView.styleManager;
|
||||
return (
|
||||
Number(manager._bloomSlider.value) > before.value &&
|
||||
manager.viewer.scene.postProcessStages.bloom.uniforms.contrast <
|
||||
before.contrast
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast < before.contrast
|
||||
);
|
||||
}, displayBefore),
|
||||
);
|
||||
@@ -269,14 +271,15 @@ try {
|
||||
manager._displayBindings._detachDisplayControls();
|
||||
const before = manager.bloomEnabled;
|
||||
const contrast =
|
||||
manager.viewer.scene.postProcessStages.bloom.uniforms.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.viewer.scene.postProcessStages.bloom.uniforms.contrast ===
|
||||
contrast
|
||||
window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms
|
||||
.contrast === contrast
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
+12
-15
@@ -15,7 +15,8 @@
|
||||
* (`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 suppressed for the
|
||||
@@ -37,7 +38,6 @@ import {
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
|
||||
import {
|
||||
DRAW_SHAPES,
|
||||
MAX_VERTICES,
|
||||
@@ -59,7 +59,7 @@ 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 {
|
||||
@@ -407,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();
|
||||
|
||||
@@ -296,27 +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();
|
||||
}
|
||||
|
||||
Vendored
-8
@@ -2,7 +2,6 @@ import { catalogControlServices } from './catalog.js';
|
||||
import { StyleManager } from '../ui/composition.js';
|
||||
import { applyStartView, START_VIEW } from '../camera.js';
|
||||
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
|
||||
import { createViewWeather } from '../viewWeather.js';
|
||||
import { createViewSky } from '../viewSky.js';
|
||||
import { findGlobe } from '../render/rendererOf.js';
|
||||
import { useDisplayStore } from '../ui/stores/display.js';
|
||||
@@ -66,13 +65,6 @@ export function createApplicationControls({
|
||||
weatherService: operations.requests.weather,
|
||||
});
|
||||
defer(() => cockpitCloudEffects?.destroy());
|
||||
// Clouds, fog, rain and snow on a renderer that draws them: the conditions
|
||||
// under the camera, or what the user sets in the Display panel.
|
||||
const viewWeather = createViewWeather(viewer, {
|
||||
weatherService: operations.requests.weather,
|
||||
store: useDisplayStore(applicationPinia()),
|
||||
});
|
||||
defer(() => viewWeather.destroy());
|
||||
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
|
||||
// chooses in the Display panel.
|
||||
const viewSky = createViewSky(viewer, {
|
||||
|
||||
+3
-2
@@ -313,8 +313,9 @@ export function createApplicationTools({
|
||||
terrain: operations.requests.terrain,
|
||||
}),
|
||||
);
|
||||
// An application's own tool takes the pointer as Draw does, and its own
|
||||
// click handlers yield while a tool holds it, as the layers' do
|
||||
// An application's own tool takes the pointer as Draw does (the newest
|
||||
// claim takes over; `claim(owner, {onLost})` tells the tool it replaces),
|
||||
// and its own click handlers yield while a tool holds it, as the layers' do
|
||||
// (data/inputOwnership.js).
|
||||
return {
|
||||
sceneDirector,
|
||||
|
||||
+113
-11
@@ -32,6 +32,8 @@ import {
|
||||
TRACKED_ICON_PX,
|
||||
} from './aircraftIcons.js';
|
||||
import { cockpitContactDotImage } from './cockpitContactDot.js';
|
||||
import { aircraftRecedeSpec } from './aircraftRecession.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
|
||||
|
||||
/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */
|
||||
const COCKPIT_DOT_PX = 16;
|
||||
@@ -97,6 +99,14 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
const book = createIconBook(null, { capabilities });
|
||||
const pending = new Map();
|
||||
const removed = new Set();
|
||||
// Ids not drawn whatever their item says: following the clock, the time
|
||||
// drawn is before the contact was there (`setUnseen`).
|
||||
const unseen = new Set();
|
||||
/** The item as the draw set takes it: hidden while unseen. */
|
||||
const drawnItem = (item) =>
|
||||
unseen.has(item.id) && item.show !== false
|
||||
? { ...item, show: false }
|
||||
: item;
|
||||
// The ids the draw set holds.
|
||||
const sent = new Set();
|
||||
let queued = false;
|
||||
@@ -157,7 +167,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
return p && result ? copyInto(p, result) : p;
|
||||
},
|
||||
course: (id, t) => book.course(id, t),
|
||||
shown: (id) => book.item(id)?.show !== false,
|
||||
shown: (id) => book.item(id)?.show !== false && !unseen.has(id),
|
||||
focus: (id) => book.focus(id),
|
||||
alpha: (id) => book.item(id)?.alpha ?? 1,
|
||||
scale: (id) => book.item(id)?.scale ?? 1,
|
||||
@@ -165,7 +175,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
put(item, options) {
|
||||
book.put(item, options);
|
||||
removed.delete(item.id);
|
||||
pending.set(item.id, item);
|
||||
pending.set(item.id, drawnItem(item));
|
||||
schedule();
|
||||
},
|
||||
/**
|
||||
@@ -190,10 +200,25 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
return true;
|
||||
},
|
||||
setShown: (id, value) => icons.update(id, { show: value !== false }),
|
||||
/**
|
||||
* Keep an id from being drawn (true) whatever its item's `show` says, or
|
||||
* draw it as its item says again (false).
|
||||
*/
|
||||
setUnseen(id, value) {
|
||||
const item = book.item(id);
|
||||
if (!item || unseen.has(id) === Boolean(value)) return;
|
||||
if (value) unseen.add(id);
|
||||
else unseen.delete(id);
|
||||
pending.set(id, drawnItem(item));
|
||||
schedule();
|
||||
},
|
||||
/** Whether an id is kept from being drawn (`setUnseen`). */
|
||||
unseen: (id) => unseen.has(id),
|
||||
setFocus: (id, factor) => icons.update(id, { focus: factor }),
|
||||
remove(id) {
|
||||
if (!book.has(id)) return;
|
||||
book.remove(id);
|
||||
unseen.delete(id);
|
||||
pending.delete(id);
|
||||
if (sent.has(id)) {
|
||||
removed.add(id);
|
||||
@@ -202,6 +227,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
},
|
||||
clear() {
|
||||
for (const id of book.ids()) book.remove(id);
|
||||
unseen.clear();
|
||||
pending.clear();
|
||||
removed.clear();
|
||||
sent.clear();
|
||||
@@ -211,6 +237,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
|
||||
flush,
|
||||
dispose() {
|
||||
for (const id of book.ids()) book.remove(id);
|
||||
unseen.clear();
|
||||
pending.clear();
|
||||
removed.clear();
|
||||
sent.clear();
|
||||
@@ -438,6 +465,16 @@ export function createAircraftIcons({
|
||||
let liveSet = null;
|
||||
let sceneClock = false;
|
||||
let sentDelayMs = NaN;
|
||||
// The `recede` the set was last sent.
|
||||
let sentRecede = null;
|
||||
/**
|
||||
* From when (display ms) each planned row's motion holds: a row whose
|
||||
* motion starts after the time drawn is planned again when the time moves
|
||||
* back before it (`_replanExpired`).
|
||||
*/
|
||||
const planFrom = new Map();
|
||||
/** The display time the rows were last checked against. */
|
||||
let replannedAt = -Infinity;
|
||||
|
||||
/** The motion clock for whether the layer follows the world clock. */
|
||||
const motionClock = (scene) =>
|
||||
@@ -464,15 +501,27 @@ export function createAircraftIcons({
|
||||
liveSet.setOptions({ motionClock: motionClock(scene) });
|
||||
}
|
||||
|
||||
/** The set recedes by the aircraft tuning: sent again when it changes. */
|
||||
function _syncRecede() {
|
||||
if (!liveSet) return;
|
||||
const recede = aircraftRecedeSpec();
|
||||
if (recede === sentRecede) return;
|
||||
sentRecede = recede;
|
||||
liveSet.setOptions({ recede });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the draw set for one layer lifetime, drawn over depth and culled
|
||||
* at the horizon on the delayed live clock, stacked by the sprite order.
|
||||
* Create the draw set for one layer lifetime, drawn over depth, culled at
|
||||
* the horizon and receding toward the limb on the delayed live clock,
|
||||
* stacked by the sprite order.
|
||||
* @returns {string} The set's id.
|
||||
*/
|
||||
function _createIcons(viewer) {
|
||||
sentRecede = aircraftRecedeSpec();
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `${layerId}-icons:${++instances}`,
|
||||
horizonCull: true,
|
||||
recede: sentRecede,
|
||||
motionClock: motionClock(followsClock()),
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.(layerId) ?? 0,
|
||||
});
|
||||
@@ -494,6 +543,8 @@ export function createAircraftIcons({
|
||||
state._icons?.dispose();
|
||||
state._icons = null;
|
||||
liveSet = null;
|
||||
planFrom.clear();
|
||||
replannedAt = -Infinity;
|
||||
}
|
||||
|
||||
/** The near-image switch in CSS px for the scene's pixel ratio. */
|
||||
@@ -553,11 +604,16 @@ export function createAircraftIcons({
|
||||
* oldest fix, or the coast arc past the newest. The displayed nose glides
|
||||
* from where it is onto the new course at the fleet's slew cap; a hovering
|
||||
* contact keeps its nose. The item expires when the regime would change.
|
||||
* Following the clock, a contact not there yet at the time drawn
|
||||
* (`regime.unseen`) is not drawn until its warm-up begins.
|
||||
* @param {string} icao24
|
||||
* @param {{fromCourseDeg?: number|null}} [options] Nose to glide from when
|
||||
* the row's own motion is not what was on screen (tracking handoff).
|
||||
* @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options]
|
||||
* `fromCourseDeg`: nose to glide from when the row's own motion is not
|
||||
* what was on screen (tracking handoff). `rewound`: the time drawn moved
|
||||
* back before the row's motion; it is drawn where it was then, with no
|
||||
* easing from where it is drawn now.
|
||||
*/
|
||||
function _planIcon(icao24, { fromCourseDeg } = {}) {
|
||||
function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) {
|
||||
const icons = state._icons;
|
||||
if (!icons?.has(icao24) || holdsPlan(icao24)) return;
|
||||
const history = state._positionHistory.get(icao24);
|
||||
@@ -575,11 +631,31 @@ export function createAircraftIcons({
|
||||
if (_planPlaced(icao24, info, history, t)) return;
|
||||
|
||||
const regime = parts.motion._motionRegime(history, info, renderTime);
|
||||
if (regime.unseen) {
|
||||
// Held at its first fix, not drawn, until its warm-up begins.
|
||||
const course = regime.heading;
|
||||
icons.setUnseen(icao24, true);
|
||||
icons.update(
|
||||
icao24,
|
||||
{
|
||||
pos: clone(regime.fix.position),
|
||||
course,
|
||||
motion: { kind: 'hold', courseDeg: course },
|
||||
courseGlide: undefined,
|
||||
},
|
||||
{ expiresAt: fixMs(regime.fix) - TIMELINE_UNSEEN_MS },
|
||||
);
|
||||
planFrom.set(icao24, -Infinity);
|
||||
return;
|
||||
}
|
||||
icons.setUnseen(icao24, false);
|
||||
let speed;
|
||||
let motion;
|
||||
let pos;
|
||||
let course;
|
||||
let expiresAt = Infinity;
|
||||
// From when the motion holds: before it, the time drawn has moved back.
|
||||
let validFrom = t;
|
||||
if (regime.kind === 'between' && regime.piece) {
|
||||
// Along the curve between the two reports, a piece at a time.
|
||||
const segment = regime.piece.segment;
|
||||
@@ -588,6 +664,7 @@ export function createAircraftIcons({
|
||||
pos = clone(segment.fix);
|
||||
course = motionCourse(motion, undefined, t);
|
||||
expiresAt = regime.piece.t1;
|
||||
validFrom = regime.piece.t0;
|
||||
} else if (regime.kind === 'between') {
|
||||
const { a, b, span, trackFrom, trackTo, chordCourse } = regime;
|
||||
speed = regime.speed;
|
||||
@@ -609,10 +686,19 @@ export function createAircraftIcons({
|
||||
motion = { kind: 'hold', courseDeg: course };
|
||||
}
|
||||
expiresAt = fixMs(b);
|
||||
validFrom = fixMs(a);
|
||||
} else {
|
||||
const { fix, heading } = regime;
|
||||
speed = regime.speed;
|
||||
const t0 = fixMs(fix);
|
||||
// A warm-up runs back to its start (a contact following the clock on
|
||||
// its own fixes is unseen before that); a coast holds from its fix.
|
||||
validFrom =
|
||||
regime.maxDt === 0 && t0 > t
|
||||
? history[0].timeline === true
|
||||
? t0 - TIMELINE_UNSEEN_MS
|
||||
: -Infinity
|
||||
: t0;
|
||||
pos = clone(fix.position);
|
||||
course = heading;
|
||||
motion =
|
||||
@@ -643,6 +729,7 @@ export function createAircraftIcons({
|
||||
motion = floored.motion;
|
||||
pos = floored.pos;
|
||||
course = floored.course;
|
||||
validFrom = t;
|
||||
}
|
||||
expiresAt = Math.min(expiresAt, floored.expiresAt);
|
||||
}
|
||||
@@ -656,6 +743,7 @@ export function createAircraftIcons({
|
||||
// whose motion ran out long ago, is simply drawn where it is now).
|
||||
if (
|
||||
fromCourseDeg == null &&
|
||||
!rewound &&
|
||||
icons.shown(icao24) &&
|
||||
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
|
||||
) {
|
||||
@@ -680,6 +768,7 @@ export function createAircraftIcons({
|
||||
pos = clone(drawn);
|
||||
course = motionCourse(motion, undefined, t);
|
||||
expiresAt = end;
|
||||
validFrom = t;
|
||||
}
|
||||
}
|
||||
// Below hover speed the nose holds what is on screen (or, for a new row,
|
||||
@@ -703,6 +792,7 @@ export function createAircraftIcons({
|
||||
};
|
||||
}
|
||||
icons.update(icao24, { pos, course, motion, courseGlide }, { expiresAt });
|
||||
planFrom.set(icao24, validFrom);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -735,16 +825,27 @@ export function createAircraftIcons({
|
||||
courseSlopeDeg: norm180(end.courseDeg - course),
|
||||
}
|
||||
: { kind: 'hold', courseDeg: course };
|
||||
state._icons.setUnseen(icao24, false);
|
||||
state._icons.update(
|
||||
icao24,
|
||||
{ pos: clone(from), course, motion, courseGlide: undefined },
|
||||
{ expiresAt: t1 },
|
||||
);
|
||||
planFrom.set(icao24, t);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Re-plan every row whose regime ended by `t` (epoch ms). */
|
||||
/**
|
||||
* Re-plan every row whose regime ended by `t` (epoch ms), and, following
|
||||
* the clock, every row whose motion starts after `t` once the time drawn
|
||||
* moved back (a seek, or the clock run backward): it is drawn where it was
|
||||
* then, as it is when the time moves on.
|
||||
*/
|
||||
function _replanExpired(t) {
|
||||
if (followsClock() && t < replannedAt)
|
||||
for (const [icao24, from] of planFrom)
|
||||
if (from > t) _planIcon(icao24, { rewound: true });
|
||||
replannedAt = t;
|
||||
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
|
||||
}
|
||||
|
||||
@@ -889,6 +990,7 @@ export function createAircraftIcons({
|
||||
/** Drop a contact and everything the layer keeps for it. */
|
||||
function _forgetContact(icao24) {
|
||||
state._icons?.remove(icao24);
|
||||
planFrom.delete(icao24);
|
||||
parts.rendering._releaseModel(icao24);
|
||||
state.records.forget(icao24);
|
||||
// The host-supplied placement, if any, forgets it as well.
|
||||
@@ -907,6 +1009,7 @@ export function createAircraftIcons({
|
||||
return {
|
||||
_displayMs,
|
||||
_syncMotionClock,
|
||||
_syncRecede,
|
||||
_createIcons,
|
||||
_disposeIcons,
|
||||
_syncImageSwitch,
|
||||
@@ -930,8 +1033,8 @@ export function createAircraftIcons({
|
||||
|
||||
/**
|
||||
* A contact's icon item before it is styled or planned: held at the origin
|
||||
* (as a fresh row of the icon set was), always drawn over depth, receding
|
||||
* toward the limb, picked as `{layer, id}`. Its image comes with its style
|
||||
* (as a fresh row of the icon set was), always drawn over depth (receding
|
||||
* toward the limb, as its set does), picked as `{layer, id}`. Its image comes with its style
|
||||
* (`_applyIconPresentation`), before the item is first written.
|
||||
*/
|
||||
function baseContactItem(layerId, icao24, show) {
|
||||
@@ -942,7 +1045,6 @@ function baseContactItem(layerId, icao24, show) {
|
||||
course: 0,
|
||||
size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX],
|
||||
rotationMode: 'course',
|
||||
recede: true,
|
||||
disableDepthTest: Infinity,
|
||||
focus: 1,
|
||||
show,
|
||||
|
||||
@@ -787,6 +787,9 @@ export function createAircraftModels({
|
||||
// clock. (The tracked trail moves on in its own pass before each frame.)
|
||||
if (state._viewer) parts.tracking._staleCueTick?.();
|
||||
try {
|
||||
// Every frame too: the icons recede by the tuning as it is now, so a
|
||||
// change shows on the next frame, shown or not.
|
||||
parts.icons._syncRecede?.();
|
||||
_fleetPass();
|
||||
} finally {
|
||||
// The models first, then the icons they take over from, so a pass
|
||||
@@ -921,9 +924,13 @@ export function createAircraftModels({
|
||||
if (icao24 === state._trackedIcao) continue;
|
||||
if (!icons.has(icao24)) continue;
|
||||
const position = icons.position(icao24, t);
|
||||
if (!parts.icons._aboveHorizon(position, occluder)) {
|
||||
if (
|
||||
icons.unseen?.(icao24) ||
|
||||
!parts.icons._aboveHorizon(position, occluder)
|
||||
) {
|
||||
// A model that crossed the limb would keep drawing through the
|
||||
// hidden globe; the icon's own cull is on the GPU.
|
||||
// hidden globe; the icon's own cull is on the GPU. A contact not
|
||||
// there yet at the time drawn is hidden as one beyond it.
|
||||
const hidden = state._models.get(icao24);
|
||||
if (hidden?.show) {
|
||||
showModel(hidden, false);
|
||||
|
||||
@@ -84,6 +84,9 @@ function fleetFixture(positions) {
|
||||
},
|
||||
});
|
||||
const shown = new Map([...positions.keys()].map((id) => [id, true]));
|
||||
let alphaOf = 1;
|
||||
let focusOf = 1;
|
||||
const unseenIds = new Set();
|
||||
const icons = {
|
||||
show: true,
|
||||
setId: 'flights-icons:1',
|
||||
@@ -91,9 +94,10 @@ function fleetFixture(positions) {
|
||||
has: (id) => positions.has(id),
|
||||
position: (id) => positions.get(id),
|
||||
course: () => 90,
|
||||
alpha: () => 1,
|
||||
focus: () => 1,
|
||||
alpha: () => alphaOf,
|
||||
focus: () => focusOf,
|
||||
setShown: (id, value) => shown.set(id, value),
|
||||
unseen: (id) => unseenIds.has(id),
|
||||
flush() {},
|
||||
};
|
||||
const state = {
|
||||
@@ -116,6 +120,7 @@ function fleetFixture(positions) {
|
||||
},
|
||||
};
|
||||
let now = 1_000_000;
|
||||
let iconRecedeSyncs = 0;
|
||||
const parts = {
|
||||
icons: {
|
||||
_displayMs: () => now,
|
||||
@@ -124,6 +129,9 @@ function fleetFixture(positions) {
|
||||
_focusIcons() {},
|
||||
_occluder: () => null,
|
||||
_aboveHorizon: () => true,
|
||||
_syncRecede() {
|
||||
iconRecedeSyncs += 1;
|
||||
},
|
||||
},
|
||||
motion: { _displayTimeAt: () => null },
|
||||
tracking: {
|
||||
@@ -157,6 +165,18 @@ function fleetFixture(positions) {
|
||||
removes,
|
||||
shown,
|
||||
failNextUpsert: () => (failNextUpsert = true),
|
||||
/** How often the icons were told to recede by the tuning as it is now. */
|
||||
iconRecedeSyncs: () => iconRecedeSyncs,
|
||||
/** Mark a contact as not there yet at the time drawn, or there again. */
|
||||
setUnseen(id, value) {
|
||||
if (value) unseenIds.add(id);
|
||||
else unseenIds.delete(id);
|
||||
},
|
||||
/** The icons' alpha and focus the fleet models take. */
|
||||
look(alpha, focus) {
|
||||
alphaOf = alpha;
|
||||
focusOf = focus;
|
||||
},
|
||||
/** One fleet tick, past the tick interval. */
|
||||
tick() {
|
||||
now += 1000;
|
||||
@@ -296,3 +316,76 @@ test('a fleet model whose load failed is loaded again after a wait, not before',
|
||||
Date.now = realNow;
|
||||
}
|
||||
});
|
||||
|
||||
test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => {
|
||||
const {
|
||||
aircraftTreatmentAlpha,
|
||||
setAircraftRecessionParams,
|
||||
resetAircraftRecessionParams,
|
||||
} = await import('./aircraftRecession.js');
|
||||
const position = near(1);
|
||||
const f = fleetFixture(new Map([['a1', position]]));
|
||||
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
|
||||
const eye = fromDegrees(-97.71, 30.21, 30_000);
|
||||
const expected = (focusFactor) =>
|
||||
aircraftTreatmentAlpha({
|
||||
baseAlpha: 0.8,
|
||||
focusFactor,
|
||||
cameraDistanceM: Math.hypot(
|
||||
eye.x - position.x,
|
||||
eye.y - position.y,
|
||||
eye.z - position.z,
|
||||
),
|
||||
cameraHeightM: 30_000,
|
||||
});
|
||||
try {
|
||||
// Recede from the eye on, so the haze is not 1 here.
|
||||
setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 });
|
||||
f.look(0.8, 0.5);
|
||||
f.tick();
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
f.tick();
|
||||
const item = f.fleet().items.get('a1');
|
||||
assert.equal(item.tint[3], expected(0.5), 'the tint carries it all');
|
||||
assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose');
|
||||
// A frame inside the fleet interval writes nothing, whatever changed.
|
||||
f.look(0.8, 0.25);
|
||||
f.models._fleetTick();
|
||||
assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]);
|
||||
f.tick();
|
||||
assert.equal(
|
||||
f.fleet().items.get('a1').tint[3],
|
||||
expected(0.25),
|
||||
'the next tick takes it',
|
||||
);
|
||||
} finally {
|
||||
resetAircraftRecessionParams();
|
||||
}
|
||||
f.state._irBoost = true;
|
||||
f.models._reloadModelsForIrBoost();
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength');
|
||||
});
|
||||
|
||||
test('a tuning change reaches the icons on the next frame, icons shown or not', async () => {
|
||||
const f = fleetFixture(new Map([['a1', near(1)]]));
|
||||
f.state._icons.show = false;
|
||||
const before = f.iconRecedeSyncs();
|
||||
f.models._fleetTick();
|
||||
assert.ok(f.iconRecedeSyncs() > before, 'the icons are told');
|
||||
});
|
||||
|
||||
test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => {
|
||||
const f = fleetFixture(new Map([['a1', near(1)]]));
|
||||
f.tick();
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there');
|
||||
f.setUnseen('a1', true);
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen');
|
||||
f.setUnseen('a1', false);
|
||||
f.tick();
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '../geo/julian.js';
|
||||
import { clone, distance } from '../geo/vector.js';
|
||||
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
|
||||
import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js';
|
||||
import {
|
||||
COAST_MAX_SPEED_MPS,
|
||||
courseBetweenCartesians,
|
||||
@@ -136,6 +137,7 @@ export function createMotionRegime() {
|
||||
turnRateDps: 0,
|
||||
minDt: 0,
|
||||
maxDt: 0,
|
||||
unseen: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -164,7 +166,9 @@ export function createMotionRegime() {
|
||||
* five minutes past it, then stops (SIGNAL LOST). A contact last heard on
|
||||
* or near the ground holds there instead (`staleHoldsForFix`, decided once
|
||||
* per report), and a chain of synthetic fixes never coasts further than
|
||||
* the real report they were built from would.
|
||||
* the real report they were built from would. Following the clock, a
|
||||
* warm-up well before a contact's own first fix is `unseen`: it was not
|
||||
* there yet, and is not drawn (`historyUnseenAt`).
|
||||
*
|
||||
* @param {Array<object>} history Non-empty, oldest first.
|
||||
* @param {object|undefined} info The contact's record.
|
||||
@@ -186,13 +190,24 @@ export function aircraftMotionRegime(
|
||||
// contact is drawn report to report, as its trail is.
|
||||
let report = history.length - 1;
|
||||
while (report >= 0 && isSyntheticFix(history[report])) report--;
|
||||
// The pairs are read back from the fix after the first one at or after
|
||||
// the render time (so a fix at exactly that time takes the later pair, as
|
||||
// it always did; past any superseded synthetic fix there), found by
|
||||
// halving, and stop at the first pair wholly before it: a contact
|
||||
// following the clock keeps a long history.
|
||||
let start = Math.min(
|
||||
historyBracketIndex(history, renderTime) + 1,
|
||||
history.length - 1,
|
||||
);
|
||||
while (start < report && isSyntheticFix(history[start])) start++;
|
||||
let b = null;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
for (let i = start; i >= 0; i--) {
|
||||
const a = history[i];
|
||||
if (i < report && isSyntheticFix(a)) continue;
|
||||
const pairB = b;
|
||||
b = a;
|
||||
if (!pairB) continue;
|
||||
if (julianLessThan(pairB.time, renderTime)) break;
|
||||
if (
|
||||
!julianLessThanOrEquals(a.time, renderTime) ||
|
||||
!julianLessThanOrEquals(renderTime, pairB.time)
|
||||
@@ -219,6 +234,7 @@ export function aircraftMotionRegime(
|
||||
result.chordCourse =
|
||||
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
|
||||
result.blend = blend;
|
||||
result.unseen = false;
|
||||
return result;
|
||||
}
|
||||
const newest = history[history.length - 1];
|
||||
@@ -226,6 +242,7 @@ export function aircraftMotionRegime(
|
||||
result.kind = 'fix';
|
||||
result.piece = null;
|
||||
result.fix = warming ? history[0] : newest;
|
||||
result.unseen = warming && historyUnseenAt(history, renderTime);
|
||||
result.speed = fixSpeedMps(result.fix, info, fields);
|
||||
result.heading = fixTrackDeg(result.fix, info, fields);
|
||||
// Past the newest report it flies straight on along its course: a turn
|
||||
|
||||
+46
-100
@@ -1,29 +1,33 @@
|
||||
/**
|
||||
* Limb-relative recession for distant aircraft: the factors icon sets apply in
|
||||
* their shader (ICON_RECEDES) and models apply through their colour alpha.
|
||||
* Limb-relative recession for distant aircraft: the tuning the aircraft icon
|
||||
* and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha
|
||||
* those sets draw with, for evidence and checks.
|
||||
*
|
||||
* It multiplies an icon's ordinary scale, which composes with its locked
|
||||
* NearFarScalar. It never edits that scalar, culls a contact, or allows alpha
|
||||
* to reach zero.
|
||||
* to reach zero. The maths is the Cesium-free `render/recession.js`,
|
||||
* which the sets drawing aircraft recede by (`SetSpec.recede`).
|
||||
*/
|
||||
import {
|
||||
RECEDE_DEFAULTS,
|
||||
limbDistanceM,
|
||||
recedeFactors,
|
||||
recedeFrame,
|
||||
recedeParams,
|
||||
recededAlpha,
|
||||
} from '../render/recession.js';
|
||||
|
||||
export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
|
||||
startLimbRatio: 0.5,
|
||||
scaleFloor: 0.45,
|
||||
alphaFloor: 0.35,
|
||||
combinedAlphaFloor: 0.2,
|
||||
globeViewBlendStartM: 3_500_000,
|
||||
globeViewBlendEndM: 4_500_000,
|
||||
earthRadiusM: 6_378_137,
|
||||
...RECEDE_DEFAULTS,
|
||||
writeEpsilon: 0.005,
|
||||
});
|
||||
|
||||
let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
|
||||
const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
const _scratchFrame = { active: false, limbM: 1, strength: 0 };
|
||||
// The tuning `_recede` was made from, and the set option made from it.
|
||||
let _recedeFor = null;
|
||||
let _recede = null;
|
||||
|
||||
function resolvedParams(overrides) {
|
||||
if (!overrides || overrides === _params) return _params;
|
||||
@@ -36,47 +40,12 @@ function aircraftRecessionFactorsResolved(
|
||||
tuning,
|
||||
result,
|
||||
) {
|
||||
if (
|
||||
!Number.isFinite(cameraDistanceM) ||
|
||||
cameraDistanceM < 0 ||
|
||||
!Number.isFinite(cameraHeightM) ||
|
||||
cameraHeightM <= 0 ||
|
||||
cameraHeightM >= tuning.globeViewBlendEndM
|
||||
) {
|
||||
result.scale = 1;
|
||||
result.alpha = 1;
|
||||
result.limbRatio = null;
|
||||
return result;
|
||||
}
|
||||
const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM);
|
||||
if (!Number.isFinite(limbDistance) || limbDistance <= 0) {
|
||||
result.scale = 1;
|
||||
result.alpha = 1;
|
||||
result.limbRatio = null;
|
||||
return result;
|
||||
}
|
||||
const limbRatio = cameraDistanceM / limbDistance;
|
||||
if (limbRatio <= tuning.startLimbRatio) {
|
||||
result.scale = 1;
|
||||
result.alpha = 1;
|
||||
result.limbRatio = limbRatio;
|
||||
return result;
|
||||
}
|
||||
|
||||
const rawT =
|
||||
(limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
|
||||
const t = clamp(rawT, 0, 1);
|
||||
const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges
|
||||
const globeRawT =
|
||||
(cameraHeightM - tuning.globeViewBlendStartM) /
|
||||
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
|
||||
const globeT = clamp(globeRawT, 0, 1);
|
||||
const globeEase = globeT * globeT * (3 - 2 * globeT);
|
||||
const strength = 1 - globeEase;
|
||||
result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength;
|
||||
result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength;
|
||||
result.limbRatio = limbRatio;
|
||||
return result;
|
||||
return recedeFactors(
|
||||
cameraDistanceM,
|
||||
recedeFrame(cameraHeightM, tuning, _scratchFrame),
|
||||
tuning,
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,45 +54,34 @@ function aircraftRecessionFactorsResolved(
|
||||
* @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS}
|
||||
*/
|
||||
export function setAircraftRecessionParams(patch = {}) {
|
||||
const next = { ..._params };
|
||||
if (Number.isFinite(patch.startLimbRatio)) {
|
||||
next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99);
|
||||
}
|
||||
if (Number.isFinite(patch.scaleFloor))
|
||||
next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
|
||||
if (Number.isFinite(patch.alphaFloor))
|
||||
next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
|
||||
if (Number.isFinite(patch.combinedAlphaFloor)) {
|
||||
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
|
||||
}
|
||||
if (Number.isFinite(patch.globeViewBlendStartM)) {
|
||||
next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM);
|
||||
}
|
||||
if (Number.isFinite(patch.globeViewBlendEndM)) {
|
||||
next.globeViewBlendEndM = Math.max(
|
||||
next.globeViewBlendStartM + 1,
|
||||
patch.globeViewBlendEndM,
|
||||
);
|
||||
}
|
||||
// Backward-compatible evidence override: the former hard threshold now
|
||||
// names the identity end of the blend band.
|
||||
if (Number.isFinite(patch.globeViewHeightM)) {
|
||||
next.globeViewBlendEndM = Math.max(
|
||||
next.globeViewBlendStartM + 1,
|
||||
patch.globeViewHeightM,
|
||||
);
|
||||
}
|
||||
if (next.globeViewBlendStartM >= next.globeViewBlendEndM) {
|
||||
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
|
||||
}
|
||||
if (Number.isFinite(patch.earthRadiusM))
|
||||
next.earthRadiusM = Math.max(1, patch.earthRadiusM);
|
||||
const given = Number.isFinite(patch.globeViewHeightM)
|
||||
? { ...patch, globeViewBlendEndM: patch.globeViewHeightM }
|
||||
: patch;
|
||||
const next = {
|
||||
...recedeParams(given, _params),
|
||||
writeEpsilon: _params.writeEpsilon,
|
||||
};
|
||||
if (Number.isFinite(patch.writeEpsilon))
|
||||
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
|
||||
_params = next;
|
||||
return { ..._params };
|
||||
}
|
||||
|
||||
/**
|
||||
* The tuning as the `recede` of the sets that draw aircraft: the same
|
||||
* object until the tuning changes.
|
||||
* @returns {import('../render/contract/index').RecedeSpec}
|
||||
*/
|
||||
export function aircraftRecedeSpec() {
|
||||
if (_recedeFor !== _params) {
|
||||
_recedeFor = _params;
|
||||
_recede = Object.freeze(recedeParams(_params));
|
||||
}
|
||||
return _recede;
|
||||
}
|
||||
|
||||
/** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */
|
||||
export function getAircraftRecessionParams() {
|
||||
return _params;
|
||||
@@ -142,13 +100,7 @@ export function resetAircraftRecessionParams() {
|
||||
* @param {number} [earthRadiusM]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function cameraLimbDistanceM(
|
||||
cameraHeightM,
|
||||
earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM,
|
||||
) {
|
||||
if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN;
|
||||
return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM));
|
||||
}
|
||||
export const cameraLimbDistanceM = limbDistanceM;
|
||||
|
||||
/**
|
||||
* Pure recession factors for one aircraft.
|
||||
@@ -196,13 +148,7 @@ export function aircraftTreatmentAlpha({
|
||||
tuning,
|
||||
_scratchFactors,
|
||||
);
|
||||
return (
|
||||
baseAlpha *
|
||||
Math.max(
|
||||
tuning.combinedAlphaFloor,
|
||||
clamp(focusFactor, 0, 1) * factors.alpha,
|
||||
)
|
||||
);
|
||||
return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -97,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes'
|
||||
assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1);
|
||||
assert.equal(model.color.green,1);
|
||||
});
|
||||
|
||||
test('the aircraft sets recede by the tuning: one object until it changes', async () => {
|
||||
const {
|
||||
aircraftRecedeSpec,
|
||||
setAircraftRecessionParams,
|
||||
resetAircraftRecessionParams,
|
||||
} = await import('./aircraftRecession.js');
|
||||
const { RECEDE_DEFAULTS } = await import('../render/recession.js');
|
||||
resetAircraftRecessionParams();
|
||||
const first = aircraftRecedeSpec();
|
||||
assert.deepEqual(first, { ...RECEDE_DEFAULTS });
|
||||
assert.equal(aircraftRecedeSpec(), first);
|
||||
setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 });
|
||||
const tuned = aircraftRecedeSpec();
|
||||
assert.notEqual(tuned, first);
|
||||
assert.equal(tuned.scaleFloor, 0.6);
|
||||
assert.equal(tuned.globeViewBlendEndM, 4_000_000);
|
||||
assert.equal('writeEpsilon' in tuned, false);
|
||||
resetAircraftRecessionParams();
|
||||
assert.deepEqual(aircraftRecedeSpec(), first);
|
||||
});
|
||||
@@ -124,7 +124,7 @@ export function depthToViewDistance(depth, near, far, logDepth) {
|
||||
if (logDepth)
|
||||
return near + Math.pow(2, depth * Math.log2(far - near + 1)) - 1;
|
||||
// Standard depth needs a near plane in front of the eye; log depth does not
|
||||
// (as WebGL log depth writes it, with none).
|
||||
// (it can be written with none, as log2(1 + d) / log2(far + 1)).
|
||||
if (!(near > 0)) return Number.NaN;
|
||||
return (near * far) / (far - depth * (far - near));
|
||||
}
|
||||
|
||||
@@ -114,8 +114,7 @@ test('the ends of the depth range, and a bad range, mean nothing was drawn', ()
|
||||
assert.ok(Number.isNaN(depthToViewDistance(0.5, 0, 100, false)));
|
||||
});
|
||||
|
||||
test('log depth with no near plane decodes as it is written with none', () => {
|
||||
// Written as log2(1 + d) / log2(far + 1).
|
||||
test('log depth with no near plane decodes as log2(1 + d) / log2(far + 1)', () => {
|
||||
const depth = Math.log2(1 + 400) / Math.log2(100_000 + 1);
|
||||
assert.ok(
|
||||
Math.abs(depthToViewDistance(depth, 0, 100_000, true) - 400) < 1e-6,
|
||||
|
||||
@@ -45,7 +45,6 @@ export {
|
||||
DIRECTIONS_MODES,
|
||||
DIRECTIONS_POINTER_OWNER,
|
||||
DIRECTIONS_ROUTE_COLOR,
|
||||
POINTER_TOOL_EXITS,
|
||||
STEP_ANCHOR_DEADLINE_MS,
|
||||
STEP_ANCHOR_FAST_ATTEMPTS,
|
||||
STEP_ANCHOR_RETRY_MS,
|
||||
@@ -60,7 +59,6 @@ export {
|
||||
directionsStepList,
|
||||
normalizeDirectionsParams,
|
||||
normalizeRoutePayload,
|
||||
pointerBlockedMessage,
|
||||
stepAnchorDelayMs,
|
||||
stepIndexAtDistance,
|
||||
stepMarkerHeightM,
|
||||
|
||||
+33
-101
@@ -21,8 +21,6 @@ import {
|
||||
stepIndexAtDistance,
|
||||
stepMarkerHeightM,
|
||||
stepMarkerIndices,
|
||||
pointerBlockedMessage,
|
||||
POINTER_TOOL_EXITS,
|
||||
STEP_ANCHOR_DEADLINE_MS,
|
||||
STEP_ANCHOR_RETRY_MS,
|
||||
STEP_ANCHOR_SLOW_RETRY_MS,
|
||||
@@ -440,12 +438,6 @@ test('the FLY chip reports a flight in progress', () => {
|
||||
assert.equal(flying.active, true);
|
||||
});
|
||||
|
||||
test('a blocked pointer is reported instead of silently doing nothing', () => {
|
||||
const blocked = directionsStats({ ...idle, pointerBlocked: true });
|
||||
assert.match(blocked.error, /Another map tool is using clicks/);
|
||||
assert.equal(blocked.count, 0);
|
||||
});
|
||||
|
||||
test('a step selection can be requested and cleared through params', () => {
|
||||
assert.deepEqual(normalizeDirectionsParams({ step: 3 }), { step: 3 });
|
||||
assert.deepEqual(normalizeDirectionsParams({ step: 0 }), { step: 0 });
|
||||
@@ -517,37 +509,40 @@ test('placing an endpoint takes the pointer, and every exit path gives it back',
|
||||
assert.equal(isPointerFree(), true, 'destroy releases');
|
||||
});
|
||||
|
||||
test('arming is refused, and said so, while another tool holds the pointer', (t) => {
|
||||
test('arming takes the pointer from another tool, which is told', (t) => {
|
||||
ownershipFixture(t);
|
||||
|
||||
const releaseDraw = claimAs('draw');
|
||||
assert.equal(
|
||||
directionsLayer.setParams({ arm: 'a' }),
|
||||
true,
|
||||
'the write is accepted',
|
||||
);
|
||||
assert.equal(
|
||||
pointerOwner(),
|
||||
'draw',
|
||||
"the other tool's claim is never stolen",
|
||||
);
|
||||
let lost = 0;
|
||||
claimPointer('draw', { onLost: () => (lost += 1) });
|
||||
assert.equal(directionsLayer.setParams({ arm: 'a' }), true);
|
||||
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'the newest wins');
|
||||
assert.equal(lost, 1, 'the other tool is told once');
|
||||
const chips = directionsLayer.getRowControls().chips;
|
||||
assert.equal(
|
||||
chips.find((chip) => chip.id === 'set-a').active,
|
||||
false,
|
||||
'nothing is armed',
|
||||
);
|
||||
assert.match(
|
||||
directionsLayer.getStats().error,
|
||||
/Another map tool is using clicks/,
|
||||
'the row says why the click did nothing',
|
||||
);
|
||||
assert.equal(chips.find((chip) => chip.id === 'set-a').active, true);
|
||||
assert.equal(directionsLayer.getStats().error, null);
|
||||
});
|
||||
|
||||
// Once the other tool lets go, arming works and the complaint clears.
|
||||
test('a newer tool taking the pointer disarms, as Escape would', (t) => {
|
||||
ownershipFixture(t);
|
||||
let told = 0;
|
||||
directionsLayer.setRowControlsListener(() => (told += 1));
|
||||
t.after(() => directionsLayer.setRowControlsListener(null));
|
||||
directionsLayer.setParams({ arm: 'b' });
|
||||
told = 0;
|
||||
const releaseDraw = claimAs('draw');
|
||||
const chips = directionsLayer.getRowControls().chips;
|
||||
assert.equal(chips.find((chip) => chip.id === 'set-b').active, false);
|
||||
assert.ok(told > 0, 'the row hears it');
|
||||
assert.equal(
|
||||
directionsLayer.getStats().error,
|
||||
null,
|
||||
'nothing to complain of',
|
||||
);
|
||||
// Its own later release frees nothing of the newer tool's.
|
||||
directionsLayer.setParams({ arm: null });
|
||||
assert.equal(pointerOwner(), 'draw');
|
||||
assert.equal(releaseDraw(), true);
|
||||
directionsLayer.setParams({ arm: 'a' });
|
||||
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
|
||||
assert.equal(directionsLayer.getStats().error, null);
|
||||
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'it arms again');
|
||||
});
|
||||
|
||||
test('a release names this layer, so it cannot free a successor tool claim', (t) => {
|
||||
@@ -567,11 +562,10 @@ test('a release names this layer, so it cannot free a successor tool claim', (t)
|
||||
|
||||
test('the pointer claim outlives the click that consumed it', async (t) => {
|
||||
ownershipFixture(t);
|
||||
// Every layer binds its own handler to the same canvas and they all run
|
||||
// inside ONE browser event. Releasing the claim the moment the endpoint is
|
||||
// placed hands the rest of that same click to every ambient handler
|
||||
// registered after this one — which is how placing A on top of a bikeshare
|
||||
// station also deselected the station.
|
||||
// The renderer's click comes from the pointer's up, and the browser's own
|
||||
// `click` on the canvas follows inside ONE input event; DOM listeners there
|
||||
// ask `isPointerFree()` then. Releasing the claim the moment the endpoint is
|
||||
// placed hands the rest of that same click to them.
|
||||
directionsLayer.setParams({ arm: 'a' });
|
||||
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
|
||||
|
||||
@@ -727,68 +721,6 @@ test('a stale lease cannot free the claim a later arming holds', async (t) => {
|
||||
);
|
||||
});
|
||||
|
||||
test('a refused arming names the tool holding the pointer and how to leave it', () => {
|
||||
// Owner field test: he pressed SET A while Draw was open, nothing happened,
|
||||
// and he concluded Directions was broken. Silence was the bug.
|
||||
assert.equal(
|
||||
pointerBlockedMessage('draw', 'a'),
|
||||
'Draw is active — press Escape twice to leave Draw, then set A',
|
||||
);
|
||||
assert.equal(
|
||||
pointerBlockedMessage('draw', 'b'),
|
||||
'Draw is active — press Escape twice to leave Draw, then set B',
|
||||
);
|
||||
// A tool nobody has written an exit for still gets a usable sentence.
|
||||
assert.equal(
|
||||
pointerBlockedMessage('measure', 'a'),
|
||||
'measure is active — turn measure off, then set A',
|
||||
);
|
||||
// A registered owner without an exit is named by its tool, not its id.
|
||||
assert.equal(
|
||||
pointerBlockedMessage('recent-imagery-box', 'a'),
|
||||
'Recent imagery is active — turn Recent imagery off, then set A',
|
||||
);
|
||||
// Nothing to say when nothing is in the way, or when we are the holder.
|
||||
assert.equal(pointerBlockedMessage(null, 'a'), null);
|
||||
assert.equal(pointerBlockedMessage('', 'a'), null);
|
||||
assert.equal(pointerBlockedMessage(' ', 'a'), null);
|
||||
assert.equal(pointerBlockedMessage(DIRECTIONS_POINTER_OWNER, 'a'), null);
|
||||
// Every exit the table knows names its tool and says how to leave it.
|
||||
for (const [id, exit] of Object.entries(POINTER_TOOL_EXITS)) {
|
||||
assert.match(
|
||||
pointerBlockedMessage(id, 'a'),
|
||||
new RegExp(`^${exit.name} is active — `),
|
||||
);
|
||||
assert.match(pointerBlockedMessage(id, 'a'), /, then set A$/);
|
||||
}
|
||||
});
|
||||
|
||||
test('the refusal reaches the app toast, and a successful arming says nothing', (t) => {
|
||||
ownershipFixture(t);
|
||||
const toasts = [];
|
||||
directionsLayer.attachShellServices({
|
||||
showToast: (text) => toasts.push(text),
|
||||
});
|
||||
t.after(() => directionsLayer.attachShellServices(null));
|
||||
|
||||
const releaseDraw = claimAs('draw');
|
||||
directionsLayer.setParams({ arm: 'a' });
|
||||
assert.deepEqual(toasts, [
|
||||
'Draw is active — press Escape twice to leave Draw, then set A',
|
||||
]);
|
||||
// The row status the operator can also read is still set.
|
||||
assert.match(
|
||||
directionsLayer.getStats().error,
|
||||
/Another map tool is using clicks/,
|
||||
);
|
||||
|
||||
// Once Draw lets go, arming works and says nothing at all.
|
||||
releaseDraw();
|
||||
directionsLayer.setParams({ arm: 'a' });
|
||||
assert.equal(toasts.length, 1, 'a successful arming is silent');
|
||||
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
|
||||
});
|
||||
|
||||
test('maneuvers are phrased on the page, in English word for word as the proxy does', () => {
|
||||
const types = [
|
||||
'depart',
|
||||
|
||||
@@ -69,6 +69,15 @@ function inView(pose, point) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Two colours as `fleetColor` gives them, alike (arrays element by element). */
|
||||
function sameColor(a, b) {
|
||||
if (a === b) return true;
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
||||
return false;
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
let instances = 0;
|
||||
|
||||
/**
|
||||
@@ -221,9 +230,8 @@ export function createFleetModelLayer({
|
||||
return fromDegrees(at.lon, at.lat, at.height + lift);
|
||||
}
|
||||
|
||||
/** The draw item for an admitted model, as the set draws it. */
|
||||
function itemOf(id, record, item, show, boost) {
|
||||
const at = placement(item);
|
||||
/** The draw item for an admitted model, as the set draws it, at `at`. */
|
||||
function itemOf(id, record, item, show, boost, at = placement(item)) {
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
return {
|
||||
id,
|
||||
@@ -257,16 +265,43 @@ export function createFleetModelLayer({
|
||||
};
|
||||
}
|
||||
|
||||
/** The item to write for a record, or null when nothing it draws changed. */
|
||||
/**
|
||||
* The item to write for a record, or null when nothing it draws changed:
|
||||
* what it was last written with is compared value by value, and the item
|
||||
* is built only when something did (a fleet passes every model each
|
||||
* frame, and most of what it draws stays).
|
||||
*/
|
||||
function changed(id, record, item, show, boost) {
|
||||
const next = itemOf(id, record, item, show, boost);
|
||||
const p = next.pos;
|
||||
const mask = next.maskColor ? String(next.maskColor) : '';
|
||||
const key = `${p.x},${p.y},${p.z}|${next.orientation.heading}|${item.spec.key}|${mask}|${boost}|${show}`;
|
||||
if (key === record.sent && next.meta === record.meta) return null;
|
||||
record.sent = key;
|
||||
record.meta = next.meta;
|
||||
return next;
|
||||
const at = placement(item);
|
||||
const heading = item.headingDeg || 0;
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
const meta = item.pickId ?? id;
|
||||
const sent = record.sent;
|
||||
if (
|
||||
sent !== null &&
|
||||
sent.x === at.x &&
|
||||
sent.y === at.y &&
|
||||
sent.z === at.z &&
|
||||
sent.heading === heading &&
|
||||
sent.specKey === item.spec.key &&
|
||||
sameColor(sent.mask, mask) &&
|
||||
sent.boost === boost &&
|
||||
sent.show === show &&
|
||||
sent.meta === meta
|
||||
)
|
||||
return null;
|
||||
const next = (record.sent ??= {});
|
||||
next.x = at.x;
|
||||
next.y = at.y;
|
||||
next.z = at.z;
|
||||
next.heading = heading;
|
||||
next.specKey = item.spec.key;
|
||||
// A colour array is kept as a copy: the layer may change its own.
|
||||
next.mask = Array.isArray(mask) ? [...mask] : mask;
|
||||
next.boost = boost;
|
||||
next.show = show;
|
||||
next.meta = meta;
|
||||
return itemOf(id, record, item, show, boost, at);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -327,6 +327,45 @@ test('a model stands on the floor its icon is lifted above', () => {
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a model that did not change is not written, nor built anew to find that out', () => {
|
||||
const { layer, frame } = readyLayer({ display: { models3d: true } });
|
||||
const tram = transitModelSpec(set, { mode: 'tram' });
|
||||
// Reads of what only the draw item takes (its scales): a model whose item
|
||||
// is built again reads them.
|
||||
let shapeReads = 0;
|
||||
const spec = new Proxy(tram, {
|
||||
get(target, key) {
|
||||
if (key === 'scale' || key === 'scaleXYZ') shapeReads += 1;
|
||||
return target[key];
|
||||
},
|
||||
});
|
||||
const tint = [1, 0, 0, 1];
|
||||
const item = itemAt(10, spec, { pickId: 't', tint });
|
||||
const items = new Map([['t', item]]);
|
||||
const models = frame(items, 0);
|
||||
const writes = models.writes;
|
||||
shapeReads = 0;
|
||||
for (let at = 2; at < 6; at++) layer.frame(items, at);
|
||||
assert.equal(models.writes, writes, 'nothing written');
|
||||
assert.equal(shapeReads, 0, 'no draw item built');
|
||||
|
||||
// A move, a turn and a route colour the layer changes in its own array
|
||||
// are each written.
|
||||
item.position = add(item.position, { x: 1, y: 0, z: 0 });
|
||||
layer.frame(items, 6);
|
||||
assert.equal(models.writes, writes + 1, 'a move is written');
|
||||
item.headingDeg += 10;
|
||||
layer.frame(items, 7);
|
||||
assert.equal(models.writes, writes + 2, 'a turn is written');
|
||||
tint[2] = 1;
|
||||
layer.frame(items, 8);
|
||||
assert.equal(models.writes, writes + 3, 'a colour changed in place');
|
||||
assert.deepEqual(models.items.get('t').maskColor, [1, 0, 1, 1]);
|
||||
layer.frame(items, 9);
|
||||
assert.equal(models.writes, writes + 3, 'and then nothing');
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('under NVG/FLIR models draw unlit white, and lit again on exit, without loading again', () => {
|
||||
const display = { models3d: true, irBoost: false };
|
||||
const { layer, frame } = readyLayer({ display });
|
||||
|
||||
Vendored
+84
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Icon motion segments packed for the GPU (`iconSegment.js`): one row per
|
||||
* icon, read by `ICON_SEGMENT_GLSL` as `iconPosition` draws it.
|
||||
*/
|
||||
import type { Ecef } from '../render/contract/index';
|
||||
|
||||
/** Floats per packed row. */
|
||||
export const SEGMENT_STRIDE: number;
|
||||
export const SEGMENT_HOLD: number;
|
||||
export const SEGMENT_LERP: number;
|
||||
export const SEGMENT_ARC: number;
|
||||
/** GLSL that evaluates a packed row. */
|
||||
export const ICON_SEGMENT_GLSL: string;
|
||||
|
||||
/** Stay at `position` facing `courseDeg`. */
|
||||
export function writeHoldSegment(
|
||||
out: Float32Array,
|
||||
row: number,
|
||||
position: Ecef,
|
||||
courseDeg: number,
|
||||
): void;
|
||||
export function writeLerpSegment(
|
||||
out: Float32Array,
|
||||
row: number,
|
||||
segment: {
|
||||
from: Ecef;
|
||||
to: Ecef;
|
||||
t0: number;
|
||||
t1: number;
|
||||
course0Deg: number;
|
||||
courseSlopeDeg: number;
|
||||
},
|
||||
): void;
|
||||
export function writeArcSegment(
|
||||
out: Float32Array,
|
||||
row: number,
|
||||
segment: {
|
||||
fix: Ecef;
|
||||
t0: number;
|
||||
minDt: number;
|
||||
maxDt: number;
|
||||
speedMps: number;
|
||||
trackDeg: number;
|
||||
turnRateDps: number;
|
||||
climbMps?: number;
|
||||
},
|
||||
): void;
|
||||
/**
|
||||
* Glide row `row`'s drawn course from `fromCourseDeg` onto its segment's,
|
||||
* at most `rateDps` from `t0` (seconds, as its times were packed).
|
||||
*/
|
||||
export function writeCourseGlide(
|
||||
out: Float32Array,
|
||||
row: number,
|
||||
fromCourseDeg: number,
|
||||
t0: number,
|
||||
rateDps: number,
|
||||
offsetDeg?: number,
|
||||
): void;
|
||||
/** Move a row's stored times by `deltaSec`. */
|
||||
export function shiftSegmentTimes(
|
||||
out: Float32Array,
|
||||
row: number,
|
||||
deltaSec: number,
|
||||
): void;
|
||||
/** The displayed course at `tau`, degrees clockwise from north. */
|
||||
export function segmentCourse(
|
||||
seg: Float32Array,
|
||||
row: number,
|
||||
tau: number,
|
||||
): number;
|
||||
/** The course the row glides toward at `tau`. */
|
||||
export function segmentTargetCourse(
|
||||
seg: Float32Array,
|
||||
row: number,
|
||||
tau: number,
|
||||
): number;
|
||||
/** Where the row is at `tau`, ECEF, into `result`. */
|
||||
export function segmentPosition(
|
||||
seg: Float32Array,
|
||||
row: number,
|
||||
tau: number,
|
||||
result?: Ecef,
|
||||
): Ecef;
|
||||
+114
-20
@@ -10,21 +10,32 @@
|
||||
*
|
||||
* So there is one claim, held by at most one owner at a time:
|
||||
*
|
||||
* - A TOOL that needs the pointer calls `claimPointer('draw')` when it turns on
|
||||
* and gets back a LEASE — an opaque token. It releases with
|
||||
* - A TOOL that needs the pointer calls `claimPointer('draw', {onLost})` when
|
||||
* it turns on and gets back a LEASE — an opaque token. It releases with
|
||||
* `releasePointer(lease)` when it turns off. It does not consult anyone;
|
||||
* holding the claim is what makes it the owner.
|
||||
* - An AMBIENT SELECTION HANDLER — anything that picks an entity because the
|
||||
* user clicked — is not called while `isPointerFree()` is false: the input
|
||||
* dispatcher skips it. It never claims.
|
||||
*
|
||||
* Claims do not stack and are never stolen: while one owner holds the pointer,
|
||||
* a second `claimPointer` returns null rather than displacing it — and so does
|
||||
* a second claim under the SAME name, because two live instances of one tool
|
||||
* (an old one mid-teardown, its replacement already running) are two owners,
|
||||
* not one. The lease is what tells them apart: releasing takes the token that
|
||||
* was issued, so a superseded instance calling `releasePointer` with its own
|
||||
* stale lease frees nothing and its successor keeps the pointer.
|
||||
* The newest claim takes over, as a claim on the renderer's input port does
|
||||
* (`src/render/contract/input.d.ts`): a second `claimPointer` ends the lease
|
||||
* out, and its holder's `onLost` is called once, after the new lease holds the
|
||||
* pointer, so that tool turns itself off as if the person had turned it off.
|
||||
* That holds for a second claim under the SAME name too: an old instance
|
||||
* mid-teardown and its replacement already running are two owners, and the
|
||||
* replacement wins. The lease is what tells them apart: releasing takes the
|
||||
* token that was issued, so a superseded instance calling `releasePointer`
|
||||
* with its own stale lease frees nothing and its successor keeps the pointer.
|
||||
*
|
||||
* Each scene's input dispatcher bridges its renderer's input port here
|
||||
* (`bridgePointer`): while a tool holds the pointer the port holds a lease
|
||||
* for it, so the port is not free, and a claim made on the port itself
|
||||
* takes over from the tool here like any newer claim. While such a claim is
|
||||
* out the pointer is not free. The bridge's lease takes no press (its `grab`
|
||||
* refuses each one): the dispatcher decides who hears each event when it
|
||||
* arrives, and the renderer's own select and double-click follow run unless
|
||||
* a tool holds them off (`suppressStockClicks`).
|
||||
*
|
||||
* Ownership is page-scoped, like the layers and handlers it arbitrates.
|
||||
*/
|
||||
@@ -34,19 +45,93 @@
|
||||
/** @type {PointerLease|null} */
|
||||
let currentLease = null;
|
||||
let nextLeaseId = 1;
|
||||
/** @type {WeakMap<PointerLease, () => void>} each lease's `onLost` */
|
||||
const lostHandlers = new WeakMap();
|
||||
/** @type {Set<{claimed: (lease: PointerLease|null) => void, isFree: () => boolean}>} */
|
||||
const bridges = new Set();
|
||||
|
||||
/**
|
||||
* Take the pointer for `owner`.
|
||||
* Take the pointer for `owner`. The newest claim takes over: the lease out
|
||||
* ends, and its `onLost` is called once, after this one holds the pointer.
|
||||
* @param {string} owner Stable identifier for the claiming tool, e.g. 'draw'.
|
||||
* @returns {PointerLease|null} The lease to release with, or null if the
|
||||
* pointer is already held — including by another instance of the same tool.
|
||||
* @param {{onLost?: () => void}} [options] `onLost`: called once when a newer
|
||||
* claim, here or on a bridged port, ends this lease; never when it is
|
||||
* released. A tool turns itself off in it.
|
||||
* @returns {PointerLease|null} The lease to release with, or null for an
|
||||
* owner with no name.
|
||||
*/
|
||||
export function claimPointer(owner) {
|
||||
export function claimPointer(owner, { onLost } = {}) {
|
||||
const name = normalizeOwner(owner);
|
||||
if (!name) return null;
|
||||
if (currentLease !== null) return null;
|
||||
currentLease = Object.freeze({ owner: name, id: nextLeaseId++ });
|
||||
return currentLease;
|
||||
const previous = currentLease;
|
||||
const lease = Object.freeze({ owner: name, id: nextLeaseId++ });
|
||||
currentLease = lease;
|
||||
if (typeof onLost === 'function') lostHandlers.set(lease, onLost);
|
||||
announce();
|
||||
if (previous) tellLost(previous);
|
||||
return lease;
|
||||
}
|
||||
|
||||
/** Each bridged port hears who holds the pointer now. */
|
||||
function announce() {
|
||||
for (const bridge of [...bridges]) bridge.claimed(currentLease);
|
||||
}
|
||||
|
||||
/** Tell the holder of an ended `lease`, once. */
|
||||
function tellLost(lease) {
|
||||
const onLost = lostHandlers.get(lease);
|
||||
lostHandlers.delete(lease);
|
||||
if (!onLost) return;
|
||||
try {
|
||||
onLost();
|
||||
} catch (error) {
|
||||
console.error('Pointer owner failed to let go', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold a lease on a renderer's input port for as long as a tool holds the
|
||||
* pointer here, made afresh for each claim. A claim made on the port by
|
||||
* anyone else ends the tool's lease here, and its holder is told; while that
|
||||
* claim is out, `isPointerFree()` is false.
|
||||
* @param {import('../render/contract/input').InputPort} port
|
||||
* @returns {{lease: () => import('../render/contract/input').Lease|null, off: () => void}}
|
||||
* `lease` is the port lease standing for the tool's, null while no tool
|
||||
* here holds the pointer; `off` gives it back and stops bridging.
|
||||
*/
|
||||
export function bridgePointer(port) {
|
||||
let held = null;
|
||||
const bridge = {
|
||||
claimed(lease) {
|
||||
held?.release();
|
||||
held = null;
|
||||
if (!lease) return;
|
||||
held = port.claimPointer(lease.owner, {
|
||||
// Every press goes on to the port's other listeners; the dispatcher
|
||||
// decides who hears it when it arrives.
|
||||
grab: () => false,
|
||||
// A claim on the port that is not this bridge's.
|
||||
onLost: () => {
|
||||
held = null;
|
||||
if (currentLease !== lease) return;
|
||||
currentLease = null;
|
||||
announce();
|
||||
tellLost(lease);
|
||||
},
|
||||
});
|
||||
},
|
||||
isFree: () => port.isPointerFree(),
|
||||
};
|
||||
bridges.add(bridge);
|
||||
bridge.claimed(currentLease);
|
||||
return {
|
||||
lease: () => (held?.current ? held : null),
|
||||
off() {
|
||||
if (!bridges.delete(bridge)) return;
|
||||
held?.release();
|
||||
held = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,7 +142,9 @@ export function claimPointer(owner) {
|
||||
*/
|
||||
export function releasePointer(lease) {
|
||||
if (!currentLease || !lease || lease.id !== currentLease.id) return false;
|
||||
lostHandlers.delete(currentLease);
|
||||
currentLease = null;
|
||||
announce();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -66,9 +153,14 @@ export function pointerOwner() {
|
||||
return currentLease ? currentLease.owner : null;
|
||||
}
|
||||
|
||||
/** @returns {boolean} True when no tool holds the pointer. */
|
||||
/**
|
||||
* @returns {boolean} True when no tool holds the pointer, here or through a
|
||||
* claim on a bridged port.
|
||||
*/
|
||||
export function isPointerFree() {
|
||||
return currentLease === null;
|
||||
if (currentLease !== null) return false;
|
||||
for (const bridge of bridges) if (!bridge.isFree()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,13 +181,15 @@ export function isLeaseCurrent(lease) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop any claim. For tests and for application teardown, which cannot rely on
|
||||
* a half-disposed tool to release its own lease.
|
||||
* Drop any claim, telling no one. For tests and for application teardown,
|
||||
* which cannot rely on a half-disposed tool to release its own lease.
|
||||
* @returns {string|null} The owner that was holding it, if any.
|
||||
*/
|
||||
export function resetPointerOwnership() {
|
||||
const previous = pointerOwner();
|
||||
if (currentLease) lostHandlers.delete(currentLease);
|
||||
currentLease = null;
|
||||
announce();
|
||||
return previous;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
pointerOwner,
|
||||
releasePointer,
|
||||
resetPointerOwnership,
|
||||
bridgePointer,
|
||||
} from './inputOwnership.js';
|
||||
import { createInputRouter } from '../render/input/router.js';
|
||||
|
||||
const ROOT = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
@@ -35,22 +37,61 @@ test('the pointer starts free and a claim hands back a lease', () => {
|
||||
assert.equal(isLeaseCurrent(lease), true);
|
||||
});
|
||||
|
||||
test('a claim is never stolen — not even by the same tool name', () => {
|
||||
const first = claimPointer('draw');
|
||||
assert.ok(first);
|
||||
test('the newest claim takes over and the holder it replaces is told, once', () => {
|
||||
const told = [];
|
||||
const first = claimPointer('draw', { onLost: () => told.push('draw') });
|
||||
const second = claimPointer('directions', {
|
||||
onLost: () => told.push('directions'),
|
||||
});
|
||||
assert.ok(second, 'a second claim is not refused');
|
||||
assert.deepEqual(told, ['draw']);
|
||||
assert.equal(pointerOwner(), 'directions');
|
||||
assert.equal(isLeaseCurrent(first), false);
|
||||
assert.equal(isLeaseCurrent(second), true);
|
||||
assert.equal(
|
||||
releasePointer(first),
|
||||
false,
|
||||
'the old late release frees nothing',
|
||||
);
|
||||
assert.equal(pointerOwner(), 'directions');
|
||||
assert.deepEqual(told, ['draw'], 'told once');
|
||||
assert.equal(releasePointer(second), true);
|
||||
assert.deepEqual(told, ['draw'], 'a holder that lets go is not told');
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
claimPointer('directions'),
|
||||
null,
|
||||
'another tool must not displace it',
|
||||
);
|
||||
assert.equal(
|
||||
claimPointer('draw'),
|
||||
null,
|
||||
'a SECOND instance of the same tool is a second owner, not a no-op',
|
||||
);
|
||||
assert.equal(pointerOwner(), 'draw');
|
||||
assert.equal(isLeaseCurrent(first), true);
|
||||
test('a second instance of the same tool takes over from the first', () => {
|
||||
// An old instance mid-teardown and its replacement already running are two
|
||||
// owners: the replacement wins, and the old one is told to turn off.
|
||||
let lost = 0;
|
||||
const old = claimPointer('draw', { onLost: () => (lost += 1) });
|
||||
const live = claimPointer('draw');
|
||||
assert.notEqual(live.id, old.id);
|
||||
assert.equal(lost, 1);
|
||||
assert.equal(isLeaseCurrent(live), true);
|
||||
});
|
||||
|
||||
test('the holder is told after the new claim holds the pointer; its error stays its own', (t) => {
|
||||
const errors = [];
|
||||
t.mock.method(console, 'error', (...args) => errors.push(args));
|
||||
let seen = null;
|
||||
const first = claimPointer('draw', {
|
||||
onLost: () => {
|
||||
seen = { owner: pointerOwner(), current: isLeaseCurrent(first) };
|
||||
throw new Error('onLost');
|
||||
},
|
||||
});
|
||||
const second = claimPointer('directions');
|
||||
assert.deepEqual(seen, { owner: 'directions', current: false });
|
||||
assert.equal(isLeaseCurrent(second), true);
|
||||
assert.equal(errors.length, 1);
|
||||
});
|
||||
|
||||
test('reset tells no one', () => {
|
||||
let lost = 0;
|
||||
claimPointer('draw', { onLost: () => (lost += 1) });
|
||||
resetPointerOwnership();
|
||||
claimPointer('directions');
|
||||
assert.equal(lost, 0);
|
||||
});
|
||||
|
||||
test('a replaced instance cannot free its successor’s claim', () => {
|
||||
@@ -173,3 +214,64 @@ test('ambient selection handlers never claim the pointer themselves', () => {
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
/** A renderer's input port, as the contract's router keeps it. */
|
||||
const portOf = () =>
|
||||
createInputRouter({
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
suspendCamera: () => () => {},
|
||||
}).port;
|
||||
|
||||
test('a bridged port holds a lease for as long as a tool holds the pointer', () => {
|
||||
const port = portOf();
|
||||
const bridge = bridgePointer(port);
|
||||
assert.equal(bridge.lease(), null);
|
||||
const lease = claimPointer('draw');
|
||||
assert.equal(port.isPointerFree(), false, 'the port is taken too');
|
||||
assert.equal(bridge.lease().owner, 'draw');
|
||||
assert.equal(bridge.lease().current, true);
|
||||
const next = claimPointer('directions');
|
||||
assert.equal(bridge.lease().owner, 'directions');
|
||||
releasePointer(lease);
|
||||
assert.equal(port.isPointerFree(), false, 'a stale release frees nothing');
|
||||
releasePointer(next);
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
assert.equal(bridge.lease(), null);
|
||||
bridge.off();
|
||||
});
|
||||
|
||||
test('a claim made on the port takes over from the page’s tool, and back', () => {
|
||||
const port = portOf();
|
||||
const bridge = bridgePointer(port);
|
||||
const told = [];
|
||||
const page = claimPointer('draw', { onLost: () => told.push('draw') });
|
||||
const other = port.claimPointer('other', {
|
||||
onLost: () => told.push('other'),
|
||||
});
|
||||
assert.deepEqual(told, ['draw'], 'the page’s tool is told');
|
||||
assert.equal(isLeaseCurrent(page), false);
|
||||
assert.equal(
|
||||
isPointerFree(),
|
||||
false,
|
||||
'the port’s own claim holds the pointer',
|
||||
);
|
||||
assert.equal(bridge.lease(), null);
|
||||
claimPointer('directions');
|
||||
assert.deepEqual(told, ['draw', 'other'], 'a newer page claim takes it back');
|
||||
assert.equal(other.current, false);
|
||||
assert.equal(bridge.lease().owner, 'directions');
|
||||
bridge.off();
|
||||
});
|
||||
|
||||
test('a port bridged while a tool holds the pointer takes its lease at once; off gives it back', () => {
|
||||
const lease = claimPointer('draw');
|
||||
const port = portOf();
|
||||
const bridge = bridgePointer(port);
|
||||
assert.equal(port.isPointerFree(), false);
|
||||
bridge.off();
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
assert.equal(isLeaseCurrent(lease), true, 'the page claim stands');
|
||||
assert.equal(isPointerFree(), false);
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import { msg } from '../i18n/marker.js';
|
||||
|
||||
/**
|
||||
* Tool name for a pointer owner. Owner ids (inputOwnership.js) never go on
|
||||
* screen; callers translate the English name with translateKnown().
|
||||
*/
|
||||
|
||||
const POINTER_OWNER_NAMES = Object.freeze({
|
||||
draw: msg('Draw'),
|
||||
directions: msg('Directions'),
|
||||
'recent-imagery-box': msg('Recent imagery'),
|
||||
});
|
||||
|
||||
/**
|
||||
* English display name of a pointer owner. An owner without a registered name
|
||||
* falls back to its id.
|
||||
* @param {string|null} owner Pointer-owner id, as `pointerOwner()` returns it.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function pointerOwnerName(owner) {
|
||||
const id = typeof owner === 'string' ? owner.trim() : '';
|
||||
if (!id) return '';
|
||||
return Object.hasOwn(POINTER_OWNER_NAMES, id) ? POINTER_OWNER_NAMES[id] : id;
|
||||
}
|
||||
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
/** Screen-space clustering of drawn points (`screenCluster.js`). */
|
||||
import type { Ecef, ScreenXY } from '../render/contract/index';
|
||||
|
||||
export interface ScreenClusterPoint {
|
||||
id: string;
|
||||
position: Ecef;
|
||||
screen: ScreenXY;
|
||||
/** Its drawn size, CSS pixels. */
|
||||
pixelSize: number;
|
||||
}
|
||||
|
||||
/** What a pass leaves for the next. */
|
||||
export interface ScreenClusterState {
|
||||
clusters: Array<{
|
||||
position: Ecef;
|
||||
width: number;
|
||||
height: number;
|
||||
minimumWidth: number;
|
||||
minimumHeight: number;
|
||||
}>;
|
||||
/** The eye's height above the ground at that pass. */
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function clusterScreenPoints(options: {
|
||||
points: ScreenClusterPoint[];
|
||||
pixelRange: number;
|
||||
minimumClusterSize: number;
|
||||
/** The view's height, CSS pixels. */
|
||||
viewHeight: number;
|
||||
/** The eye's height above the ground, m. */
|
||||
eyeHeight: number;
|
||||
previous?: ScreenClusterState | null;
|
||||
project: (position: Ecef) => ScreenXY | null;
|
||||
isOccluded: (position: Ecef) => boolean;
|
||||
}): {
|
||||
clusters: Array<{ position: Ecef; ids: string[] }>;
|
||||
single: string[];
|
||||
state: ScreenClusterState;
|
||||
};
|
||||
@@ -1085,7 +1085,6 @@
|
||||
"That shape could not be placed.": "تعذّر وضع هذا الشكل.",
|
||||
"Could not place the shape: {error}": "تعذّر وضع الشكل: {error}",
|
||||
"Board cleared.": "تم مسح اللوحة.",
|
||||
"{owner} is using the pointer — close it first.": "المؤشر مستخدم من قِبل «{owner}» — أغلقه أولًا.",
|
||||
"{label} · Detailed outline unavailable": "{label} · المخطط التفصيلي غير متاح",
|
||||
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "وضع المهام الفضائية يعزل بيانات إعادة العرض. اخرج من الوضع لتفعيل طبقة «{layer}».",
|
||||
"Data attribution": "إسناد البيانات",
|
||||
@@ -1623,12 +1622,8 @@
|
||||
"Place A and B first": "ضع A وB أولًا",
|
||||
"action|CLEAR": "مسح",
|
||||
"Remove the route and both markers": "إزالة المسار والعلامتين",
|
||||
"press Escape twice to leave Draw": "اضغط Esc مرتين للخروج من «الرسم»",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "«{name}» قيد الاستخدام — أوقف «{name}»، ثم عيّن {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "«{name}» قيد الاستخدام — {leave}، ثم عيّن {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "لا يُعرض من هذا المسار سوى أول {count} من الانعطافات",
|
||||
"Turn-by-turn directions": "إرشادات خطوة بخطوة",
|
||||
"Another map tool is using clicks — close it, then SET A again": "أداة خريطة أخرى تستخدم النقرات — أغلقها، ثم اضغط «تعيين A» مجددًا",
|
||||
"Routing…": "جارٍ حساب المسار…",
|
||||
"No route found": "لم يُعثر على مسار",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · أول {count} من الانعطافات",
|
||||
@@ -2546,7 +2541,6 @@
|
||||
"Point the camera at the ground to use the view": "وجّه الكاميرا نحو الأرض لاستخدام العرض",
|
||||
"That point cannot anchor a box": "لا يمكن تثبيت منطقة على تلك النقطة",
|
||||
"Imagery stops at ±{limit}° latitude": "تتوقف الصور عند خط العرض ±{limit}°",
|
||||
"{owner} is using the pointer — close it first": "المؤشر مستخدم من قِبل «{owner}» — أغلقه أولًا",
|
||||
"Box is {size} wide · limit {limit}": "اتساع المنطقة {size} · الحد {limit}",
|
||||
"View is {size} wide · limit {limit}": "اتساع العرض الحالي {size} · الحد {limit}",
|
||||
"VS BASEMAP": "مقابل الخريطة",
|
||||
@@ -3811,12 +3805,6 @@
|
||||
"{place} has no position to look for imagery at": "{place}: لا موضع للبحث عن الصور فيه",
|
||||
"No {source} imagery near {place}": "لا توجد صور {source} قرب {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (المرشحات المفعّلة: {filters})",
|
||||
"Clouds": "السحب",
|
||||
"Fog": "الضباب",
|
||||
"Rain": "المطر",
|
||||
"Snow": "الثلج",
|
||||
"Live weather: the conditions under the camera": "الطقس المباشر: الأحوال تحت الكاميرا",
|
||||
"No weather report here": "لا يوجد تقرير طقس هنا",
|
||||
"Rail": "السكك الحديدية",
|
||||
"Urban rail": "القطارات الحضرية",
|
||||
"Local rail": "قطارات الضواحي",
|
||||
|
||||
@@ -1045,7 +1045,6 @@
|
||||
"That shape could not be placed.": "Diese Form konnte nicht platziert werden.",
|
||||
"Could not place the shape: {error}": "Form konnte nicht platziert werden: {error}",
|
||||
"Board cleared.": "Zeichenfläche geleert.",
|
||||
"{owner} is using the pointer — close it first.": "{owner} verwendet gerade den Zeiger – zuerst schließen.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Detaillierter Umriss nicht verfügbar",
|
||||
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Der Modus Raummissionen isoliert Replay-Daten. Modus verlassen, um {layer} zu aktivieren.",
|
||||
"Data attribution": "Datenquellen",
|
||||
@@ -1557,12 +1556,8 @@
|
||||
"Place A and B first": "Zuerst A und B setzen",
|
||||
"action|CLEAR": "LÖSCHEN",
|
||||
"Remove the route and both markers": "Route und beide Markierungen entfernen",
|
||||
"press Escape twice to leave Draw": "zweimal Esc drücken, um Zeichnen zu verlassen",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name} ist aktiv – {name} ausschalten, dann {endpoint} setzen",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name} ist aktiv – {leave}, dann {endpoint} setzen",
|
||||
"Only the first {count} turns of this route are shown": "Nur die ersten {count} Abbiegungen dieser Route werden gezeigt",
|
||||
"Turn-by-turn directions": "Abbiegehinweise",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Ein anderes Kartenwerkzeug nutzt die Klicks – es schließen, dann erneut A SETZEN",
|
||||
"Routing…": "Route wird berechnet…",
|
||||
"No route found": "Keine Route gefunden",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · erste {count} Abbiegungen",
|
||||
@@ -2406,7 +2401,6 @@
|
||||
"Point the camera at the ground to use the view": "Kamera auf den Boden richten, um die Ansicht zu verwenden",
|
||||
"That point cannot anchor a box": "Dieser Punkt kann keinen Bereich verankern",
|
||||
"Imagery stops at ±{limit}° latitude": "Bilder enden bei ±{limit}° Breite",
|
||||
"{owner} is using the pointer — close it first": "{owner} verwendet gerade den Zeiger – zuerst schließen",
|
||||
"Box is {size} wide · limit {limit}": "Bereich ist {size} breit · Limit {limit}",
|
||||
"View is {size} wide · limit {limit}": "Ansicht ist {size} breit · Limit {limit}",
|
||||
"VS BASEMAP": "VGL. KARTE",
|
||||
@@ -3487,12 +3481,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} hat keine Position, an der nach Bildern gesucht werden kann",
|
||||
"No {source} imagery near {place}": "Keine Bilder von {source} in der Nähe von {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (aktive Filter: {filters})",
|
||||
"Clouds": "Wolken",
|
||||
"Fog": "Nebel",
|
||||
"Rain": "Regen",
|
||||
"Snow": "Schnee",
|
||||
"Live weather: the conditions under the camera": "Live-Wetter: die Bedingungen unter der Kamera",
|
||||
"No weather report here": "Hier gibt es keinen Wetterbericht",
|
||||
"Rail": "Bahn",
|
||||
"Urban rail": "Stadtverkehr",
|
||||
"Local rail": "Vorortverkehr",
|
||||
|
||||
@@ -1146,7 +1146,6 @@
|
||||
"SINCE": "DESDE",
|
||||
"That shape already has {count} points — finish it or press Backspace.": "Esa forma ya tiene {count} puntos — termínala o pulsa Backspace.",
|
||||
"Could not place the shape: {error}": "No se pudo colocar la forma: {error}",
|
||||
"{owner} is using the pointer — close it first.": "Puntero en uso: {owner}. Ciérralo primero.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Contorno detallado no disponible",
|
||||
"Witness source": "Fuente de testigo",
|
||||
"{provider} · EMBEDDED SOURCE": "{provider} · FUENTE INSERTADA",
|
||||
@@ -1365,15 +1364,11 @@
|
||||
"Fly the camera along the route": "Volar con la cámara a lo largo de la ruta",
|
||||
"Place A and B first": "Coloca primero A y B",
|
||||
"Remove the route and both markers": "Eliminar la ruta y ambos marcadores",
|
||||
"press Escape twice to leave Draw": "pulsa Esc dos veces para salir de Dibujo",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name} está activo — desactiva {name} y luego fija {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name} está activo — {leave} y luego fija {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Solo se muestran los primeros {count} giros de esta ruta",
|
||||
"Turn-by-turn directions": "Indicaciones paso a paso",
|
||||
"OSM routing": "Rutas de OSM",
|
||||
"DRIVE": "COCHE",
|
||||
"Drive": "En coche",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Otra herramienta del mapa está usando los clics — ciérrala y vuelve a pulsar FIJAR A",
|
||||
"WALK": "A PIE",
|
||||
"Walk": "A pie",
|
||||
"Routing…": "Calculando ruta…",
|
||||
@@ -2661,7 +2656,6 @@
|
||||
"Select one side of the dateline": "No cruces la línea de cambio de fecha",
|
||||
"Box must enclose an area": "El recuadro debe abarcar un área",
|
||||
"Imagery stops at ±{limit}° latitude": "Las imágenes llegan hasta ±{limit}° de latitud",
|
||||
"{owner} is using the pointer — close it first": "Puntero en uso: {owner}. Ciérralo primero",
|
||||
"OpenSky OAuth client missing/invalid": "Cliente OAuth de OpenSky ausente o no válido",
|
||||
"OpenSky OAuth rejected credentials": "OpenSky OAuth rechazó las credenciales",
|
||||
"OpenSky username/password rejected": "OpenSky rechazó el usuario o la contraseña",
|
||||
@@ -3568,12 +3562,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} no tiene una posición donde buscar imágenes",
|
||||
"No {source} imagery near {place}": "No hay imágenes de {source} cerca de {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (filtros activos: {filters})",
|
||||
"Clouds": "Nubes",
|
||||
"Fog": "Niebla",
|
||||
"Rain": "Lluvia",
|
||||
"Snow": "Nieve",
|
||||
"Live weather: the conditions under the camera": "Clima en directo: las condiciones bajo la cámara",
|
||||
"No weather report here": "No hay parte meteorológico aquí",
|
||||
"Rail": "Ferrocarril",
|
||||
"Urban rail": "Urbano",
|
||||
"Local rail": "Suburbano",
|
||||
|
||||
@@ -106,7 +106,6 @@
|
||||
"That shape could not be placed.": "Impossible de placer cette forme.",
|
||||
"Could not place the shape: {error}": "Impossible de placer la forme : {error}",
|
||||
"Board cleared.": "Tableau effacé.",
|
||||
"{owner} is using the pointer — close it first.": "Pointeur utilisé par : {owner}. Fermez d'abord cet outil.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Contour détaillé indisponible",
|
||||
"Restoring shared view...": "Restauration de la vue partagée…",
|
||||
"Configuring viewer...": "Configuration de la vue…",
|
||||
@@ -773,12 +772,8 @@
|
||||
"Place A and B first": "Placez d'abord A et B",
|
||||
"action|CLEAR": "EFFACER",
|
||||
"Remove the route and both markers": "Supprimer l'itinéraire et les deux marqueurs",
|
||||
"press Escape twice to leave Draw": "appuyez deux fois sur Esc pour quitter Dessin",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "Outil actif : {name} — désactivez {name}, puis placez {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "Outil actif : {name} — {leave}, puis placez {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Seules les {count} premières manœuvres de cet itinéraire sont affichées",
|
||||
"Turn-by-turn directions": "Instructions pas à pas",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Un autre outil de carte utilise les clics — fermez-le, puis refaites PLACER A",
|
||||
"Routing…": "Calcul de l'itinéraire…",
|
||||
"No route found": "Aucun itinéraire trouvé",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · {count} premières manœuvres",
|
||||
@@ -2154,7 +2149,6 @@
|
||||
"Point the camera at the ground to use the view": "Orientez la caméra vers le sol pour utiliser la vue",
|
||||
"That point cannot anchor a box": "Ce point ne peut pas ancrer une zone",
|
||||
"Imagery stops at ±{limit}° latitude": "L'imagerie s'arrête à ±{limit}° de latitude",
|
||||
"{owner} is using the pointer — close it first": "Pointeur utilisé par : {owner}. Fermez d'abord cet outil",
|
||||
"Box is {size} wide · limit {limit}": "La zone fait {size} de large · limite {limit}",
|
||||
"View is {size} wide · limit {limit}": "La vue fait {size} de large · limite {limit}",
|
||||
"VS BASEMAP": "VS CARTE",
|
||||
@@ -3568,12 +3562,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} n'a pas de position où chercher des images",
|
||||
"No {source} imagery near {place}": "Aucune image {source} près de {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (filtres actifs : {filters})",
|
||||
"Clouds": "Nuages",
|
||||
"Fog": "Brouillard",
|
||||
"Rain": "Pluie",
|
||||
"Snow": "Neige",
|
||||
"Live weather: the conditions under the camera": "Météo en direct : les conditions sous la caméra",
|
||||
"No weather report here": "Aucun bulletin météo ici",
|
||||
"Rail": "Trains",
|
||||
"Urban rail": "Urbain",
|
||||
"Local rail": "Périurbain",
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
"That shape could not be placed.": "לא היתה אפשרות למקם את הצורה.",
|
||||
"Could not place the shape: {error}": "לא ניתן למקם את הצורה: {error}",
|
||||
"Board cleared.": "הלוח נוקה.",
|
||||
"{owner} is using the pointer — close it first.": "{owner} משתמש במצביע — סגור אותו תחילה.",
|
||||
"{label} · Detailed outline unavailable": "{label} · קו המתאר המפורט אינו זמין",
|
||||
"Restoring shared view...": "משחזר תצוגה משותפת...",
|
||||
"Configuring viewer...": "מגדיר צפייה...",
|
||||
@@ -672,12 +671,8 @@
|
||||
"Place A and B first": "קבע קודם את A ו-B",
|
||||
"action|CLEAR": "נקה",
|
||||
"Remove the route and both markers": "הסרת המסלול ושני הסמנים",
|
||||
"press Escape twice to leave Draw": "הקש Escape פעמיים כדי לצאת משרטוט",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name} פעיל — כבה את {name} ואז קבע את {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name} פעיל — {leave} ואז קבע את {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "מוצגות רק {count} הפניות הראשונות של המסלול הזה",
|
||||
"Turn-by-turn directions": "הכוונה צעד אחר צעד",
|
||||
"Another map tool is using clicks — close it, then SET A again": "כלי מפה אחר משתמש בלחיצות — סגור אותו ואז קבע A שוב",
|
||||
"Routing…": "מחשב מסלול…",
|
||||
"No route found": "לא נמצא מסלול",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · {count} הפניות הראשונות",
|
||||
@@ -1999,7 +1994,6 @@
|
||||
"Point the camera at the ground to use the view": "כוון את המצלמה אל הקרקע כדי להשתמש בתצוגה",
|
||||
"That point cannot anchor a box": "אין אפשרות לעגן תיבה באותה נקודה",
|
||||
"Imagery stops at ±{limit}° latitude": "הצילומים נעצרים ברוחב ±{limit}°",
|
||||
"{owner} is using the pointer — close it first": "{owner} משתמש במצביע — סגור אותו תחילה",
|
||||
"Box is {size} wide · limit {limit}": "רוחב התיבה {size} · מגבלה {limit}",
|
||||
"View is {size} wide · limit {limit}": "רוחב התצוגה {size} · מגבלה {limit}",
|
||||
"VS BASEMAP": "מול מפת הבסיס",
|
||||
@@ -3568,12 +3562,6 @@
|
||||
"{place} has no position to look for imagery at": "ל-{place} אין מיקום לחיפוש צילומים",
|
||||
"No {source} imagery near {place}": "אין צילומים של {source} ליד {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (מסננים פעילים: {filters})",
|
||||
"Clouds": "עננים",
|
||||
"Fog": "ערפל",
|
||||
"Rain": "גשם",
|
||||
"Snow": "שלג",
|
||||
"Live weather: the conditions under the camera": "מזג אוויר חי: התנאים מתחת למצלמה",
|
||||
"No weather report here": "אין כאן דיווח מזג אוויר",
|
||||
"Rail": "רכבות",
|
||||
"Urban rail": "רכבת עירונית",
|
||||
"Local rail": "רכבת מקומית",
|
||||
|
||||
@@ -106,7 +106,6 @@
|
||||
"That shape could not be placed.": "Impossibile posizionare quella forma.",
|
||||
"Could not place the shape: {error}": "Impossibile posizionare la forma: {error}",
|
||||
"Board cleared.": "Lavagna cancellata.",
|
||||
"{owner} is using the pointer — close it first.": "Lo strumento {owner} sta usando il puntatore: chiudilo prima.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Contorno dettagliato non disponibile",
|
||||
"Restoring shared view...": "Ripristino della vista condivisa...",
|
||||
"Configuring viewer...": "Configurazione del visualizzatore...",
|
||||
@@ -773,12 +772,8 @@
|
||||
"Place A and B first": "Posiziona prima A e B",
|
||||
"action|CLEAR": "CANCELLA",
|
||||
"Remove the route and both markers": "Rimuovi il percorso ed entrambi i marcatori",
|
||||
"press Escape twice to leave Draw": "premi Esc due volte per uscire da Disegno",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "Lo strumento {name} è attivo: disattiva {name}, poi imposta {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "Lo strumento {name} è attivo: {leave}, poi imposta {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Sono mostrate solo le prime {count} svolte di questo percorso",
|
||||
"Turn-by-turn directions": "Indicazioni passo passo",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Un altro strumento della mappa sta usando i clic: chiudilo, poi IMPOSTA A di nuovo",
|
||||
"Routing…": "Calcolo del percorso…",
|
||||
"No route found": "Nessun percorso trovato",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · prime {count} svolte",
|
||||
@@ -2154,7 +2149,6 @@
|
||||
"Point the camera at the ground to use the view": "Punta la camera verso il suolo per usare la vista",
|
||||
"That point cannot anchor a box": "Quel punto non può ancorare un riquadro",
|
||||
"Imagery stops at ±{limit}° latitude": "Le immagini si fermano a ±{limit}° di latitudine",
|
||||
"{owner} is using the pointer — close it first": "Lo strumento {owner} sta usando il puntatore: chiudilo prima",
|
||||
"Box is {size} wide · limit {limit}": "Il riquadro è largo {size} · limite {limit}",
|
||||
"View is {size} wide · limit {limit}": "La vista è larga {size} · limite {limit}",
|
||||
"VS BASEMAP": "VS MAPPA BASE",
|
||||
@@ -3568,12 +3562,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} non ha una posizione in cui cercare immagini",
|
||||
"No {source} imagery near {place}": "Nessuna immagine di {source} vicino a {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (filtri attivi: {filters})",
|
||||
"Clouds": "Nuvole",
|
||||
"Fog": "Nebbia",
|
||||
"Rain": "Pioggia",
|
||||
"Snow": "Neve",
|
||||
"Live weather: the conditions under the camera": "Meteo in diretta: le condizioni sotto la telecamera",
|
||||
"No weather report here": "Nessun bollettino meteo qui",
|
||||
"Rail": "Ferrovie",
|
||||
"Urban rail": "Urbano",
|
||||
"Local rail": "Suburbano",
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
"That shape could not be placed.": "図形を配置できませんでした。",
|
||||
"Could not place the shape: {error}": "図形を配置できませんでした:{error}",
|
||||
"Board cleared.": "ボードを消去しました。",
|
||||
"{owner} is using the pointer — close it first.": "{owner}がポインターを使用中です。先に閉じてください。",
|
||||
"{label} · Detailed outline unavailable": "{label} · 詳細な輪郭を取得できません",
|
||||
"Restoring shared view...": "共有ビューを復元中…",
|
||||
"Configuring viewer...": "ビューアーを設定中…",
|
||||
@@ -749,12 +748,8 @@
|
||||
"Place A and B first": "先にAとBを配置してください",
|
||||
"action|CLEAR": "消去",
|
||||
"Remove the route and both markers": "ルートと両方のマーカーを削除",
|
||||
"press Escape twice to leave Draw": "Escを2回押して描画を終了してください",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name}を使用中です。{name}をオフにしてから{endpoint}を設定してください",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name}を使用中です。先に{leave}。その後、{endpoint}を設定してください",
|
||||
"Only the first {count} turns of this route are shown": "このルートは最初の{count}件の案内のみ表示しています",
|
||||
"Turn-by-turn directions": "ターンバイターンのルート案内",
|
||||
"Another map tool is using clicks — close it, then SET A again": "別の地図ツールがクリックを使用中です。そのツールを閉じてから、もう一度[Aを設定]を押してください",
|
||||
"Routing…": "ルート検索中…",
|
||||
"No route found": "ルートが見つかりません",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · 最初の{count}件の案内",
|
||||
@@ -2080,7 +2075,6 @@
|
||||
"Point the camera at the ground to use the view": "このビューを使うにはカメラを地面に向けてください",
|
||||
"That point cannot anchor a box": "その地点は範囲の基点にできません",
|
||||
"Imagery stops at ±{limit}° latitude": "画像は緯度±{limit}°までです",
|
||||
"{owner} is using the pointer — close it first": "{owner}がポインターを使用中です。先に閉じてください",
|
||||
"Box is {size} wide · limit {limit}": "範囲の幅 {size} · 上限 {limit}",
|
||||
"View is {size} wide · limit {limit}": "表示の幅 {size} · 上限 {limit}",
|
||||
"VS BASEMAP": "地図と比較",
|
||||
@@ -3406,12 +3400,6 @@
|
||||
"{place} has no position to look for imagery at": "{place}には画像を探す位置がありません",
|
||||
"No {source} imagery near {place}": "{place}の近くに{source}の画像はありません",
|
||||
"{reason} (filters on: {filters})": "{reason}(有効なフィルター:{filters})",
|
||||
"Clouds": "雲",
|
||||
"Fog": "霧",
|
||||
"Rain": "雨",
|
||||
"Snow": "雪",
|
||||
"Live weather: the conditions under the camera": "ライブ気象:カメラ直下の状況",
|
||||
"No weather report here": "ここには気象情報がありません",
|
||||
"Rail": "鉄道",
|
||||
"Urban rail": "都市鉄道",
|
||||
"Local rail": "近郊列車",
|
||||
|
||||
@@ -106,7 +106,6 @@
|
||||
"That shape could not be placed.": "Não foi possível colocar essa forma.",
|
||||
"Could not place the shape: {error}": "Não foi possível colocar a forma: {error}",
|
||||
"Board cleared.": "Quadro limpo.",
|
||||
"{owner} is using the pointer — close it first.": "A ferramenta \"{owner}\" está usando o ponteiro — feche-a primeiro.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Contorno detalhado indisponível",
|
||||
"Restoring shared view...": "Restaurando a vista compartilhada...",
|
||||
"Configuring viewer...": "Configurando o visualizador...",
|
||||
@@ -771,12 +770,8 @@
|
||||
"Place A and B first": "Coloque A e B primeiro",
|
||||
"action|CLEAR": "LIMPAR",
|
||||
"Remove the route and both markers": "Remover a rota e os dois marcadores",
|
||||
"press Escape twice to leave Draw": "pressione Esc duas vezes para sair de \"Desenho\"",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "A ferramenta \"{name}\" está ativa — desative \"{name}\" e depois defina {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "A ferramenta \"{name}\" está ativa — {leave} e depois defina {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Só as primeiras {count} conversões desta rota são mostradas",
|
||||
"Turn-by-turn directions": "Instruções passo a passo",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Outra ferramenta do mapa está usando os cliques — feche-a e pressione DEFINIR A de novo",
|
||||
"Routing…": "Calculando a rota…",
|
||||
"No route found": "Nenhuma rota encontrada",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · primeiras {count} conversões",
|
||||
@@ -2154,7 +2149,6 @@
|
||||
"Point the camera at the ground to use the view": "Aponte a câmera para o chão para usar a vista",
|
||||
"That point cannot anchor a box": "Esse ponto não pode ancorar uma área",
|
||||
"Imagery stops at ±{limit}° latitude": "As imagens vão até ±{limit}° de latitude",
|
||||
"{owner} is using the pointer — close it first": "A ferramenta \"{owner}\" está usando o ponteiro — feche-a primeiro",
|
||||
"Box is {size} wide · limit {limit}": "A área tem {size} de largura · limite {limit}",
|
||||
"View is {size} wide · limit {limit}": "A vista tem {size} de largura · limite {limit}",
|
||||
"VS BASEMAP": "VS MAPA BASE",
|
||||
@@ -3568,12 +3562,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} não tem uma posição para buscar imagens",
|
||||
"No {source} imagery near {place}": "Nenhuma imagem de {source} perto de {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (filtros ativos: {filters})",
|
||||
"Clouds": "Nuvens",
|
||||
"Fog": "Nevoeiro",
|
||||
"Rain": "Chuva",
|
||||
"Snow": "Neve",
|
||||
"Live weather: the conditions under the camera": "Clima ao vivo: as condições sob a câmara",
|
||||
"No weather report here": "Sem boletim meteorológico aqui",
|
||||
"Rail": "Trens",
|
||||
"Urban rail": "Urbano",
|
||||
"Local rail": "Suburbano",
|
||||
|
||||
@@ -1163,7 +1163,6 @@
|
||||
"SINCE": "С ДАТЫ",
|
||||
"That shape already has {count} points — finish it or press Backspace.": "В этой фигуре уже точек: {count} — завершите её или нажмите Backspace.",
|
||||
"Could not place the shape: {error}": "Не удалось разместить фигуру: {error}",
|
||||
"{owner} is using the pointer — close it first.": "Указатель занят: «{owner}». Закройте его.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Подробный контур недоступен",
|
||||
"Witness source": "Свидетельство очевидца",
|
||||
"{provider} · EMBEDDED SOURCE": "{provider} · ВСТРОЕННЫЙ ИСТОЧНИК",
|
||||
@@ -1387,15 +1386,11 @@
|
||||
"Fly the camera along the route": "Пролететь камерой по маршруту",
|
||||
"Place A and B first": "Сначала поставьте A и B",
|
||||
"Remove the route and both markers": "Удалить маршрут и обе метки",
|
||||
"press Escape twice to leave Draw": "дважды нажмите Esc, чтобы выйти из режима «Рисование»",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "Активно: {name} — выключите {name}, затем задайте {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "Активно: {name} — {leave}, затем задайте {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Показаны только первые повороты маршрута: {count}",
|
||||
"Turn-by-turn directions": "Пошаговые указания",
|
||||
"OSM routing": "Маршрутизация OSM",
|
||||
"DRIVE": "АВТО",
|
||||
"Drive": "На машине",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Щелчки перехватывает другой инструмент карты — закройте его и снова нажмите «ЗАДАТЬ A»",
|
||||
"WALK": "ПЕШКОМ",
|
||||
"Walk": "Пешком",
|
||||
"Routing…": "Построение маршрута…",
|
||||
@@ -2707,7 +2702,6 @@
|
||||
"Select one side of the dateline": "Не пересекайте линию перемены дат",
|
||||
"Box must enclose an area": "Область должна иметь площадь",
|
||||
"Imagery stops at ±{limit}° latitude": "Снимки есть только до ±{limit}° широты",
|
||||
"{owner} is using the pointer — close it first": "Указатель занят: «{owner}». Закройте его",
|
||||
"OpenSky OAuth client missing/invalid": "Клиент OAuth OpenSky отсутствует или недействителен",
|
||||
"OpenSky OAuth rejected credentials": "OpenSky OAuth отклонил учётные данные",
|
||||
"OpenSky username/password rejected": "OpenSky отклонил имя пользователя или пароль",
|
||||
@@ -3649,12 +3643,6 @@
|
||||
"{place} has no position to look for imagery at": "У места «{place}» нет координат для поиска снимков",
|
||||
"No {source} imagery near {place}": "Нет снимков {source} рядом с местом «{place}»",
|
||||
"{reason} (filters on: {filters})": "{reason} (включены фильтры: {filters})",
|
||||
"Clouds": "Облака",
|
||||
"Fog": "Туман",
|
||||
"Rain": "Дождь",
|
||||
"Snow": "Снег",
|
||||
"Live weather: the conditions under the camera": "Погода сейчас: условия под камерой",
|
||||
"No weather report here": "Здесь нет сводки погоды",
|
||||
"Rail": "Железная дорога",
|
||||
"Urban rail": "Городской",
|
||||
"Local rail": "Пригородный",
|
||||
|
||||
@@ -967,7 +967,6 @@
|
||||
"That shape could not be placed.": "Formen kunde inte placeras.",
|
||||
"Could not place the shape: {error}": "Kunde inte placera formen: {error}",
|
||||
"Board cleared.": "Ritytan rensad.",
|
||||
"{owner} is using the pointer — close it first.": "Verktyget ”{owner}” använder pekaren – stäng det först.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Detaljerad kontur otillgänglig",
|
||||
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Läget ”Rymduppdrag” isolerar uppspelningsdata. Lämna läget för att aktivera {layer}.",
|
||||
"Data attribution": "Datakällor",
|
||||
@@ -1479,12 +1478,8 @@
|
||||
"Place A and B first": "Placera A och B först",
|
||||
"action|CLEAR": "RENSA",
|
||||
"Remove the route and both markers": "Ta bort rutten och båda markörerna",
|
||||
"press Escape twice to leave Draw": "tryck två gånger på Esc för att lämna ”Rita”",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "”{name}” är aktivt – stäng av ”{name}” och välj sedan {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "”{name}” är aktivt – {leave} och välj sedan {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Endast de första {count} svängarna på rutten visas",
|
||||
"Turn-by-turn directions": "Vägbeskrivning steg för steg",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Ett annat kartverktyg använder klicken – stäng det och tryck sedan på VÄLJ A igen",
|
||||
"Routing…": "Beräknar rutt …",
|
||||
"No route found": "Ingen rutt hittades",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · första {count} svängarna",
|
||||
@@ -2328,7 +2323,6 @@
|
||||
"Point the camera at the ground to use the view": "Rikta kameran mot marken för att använda vyn",
|
||||
"That point cannot anchor a box": "Den punkten kan inte förankra ett område",
|
||||
"Imagery stops at ±{limit}° latitude": "Bilderna slutar vid ±{limit}° latitud",
|
||||
"{owner} is using the pointer — close it first": "Verktyget ”{owner}” använder pekaren – stäng det först",
|
||||
"Box is {size} wide · limit {limit}": "Området är {size} brett · gräns {limit}",
|
||||
"View is {size} wide · limit {limit}": "Vyn är {size} bred · gräns {limit}",
|
||||
"VS BASEMAP": "JFR KARTA",
|
||||
@@ -3487,12 +3481,6 @@
|
||||
"Scroll or pinch to zoom, drag to move along · double-click to see it all": "Scrolla eller nyp för att zooma, dra för att flytta · dubbelklicka för att se allt",
|
||||
"Live": "Live",
|
||||
"Back to live": "Tillbaka till live",
|
||||
"Clouds": "Moln",
|
||||
"Fog": "Dimma",
|
||||
"Rain": "Regn",
|
||||
"Snow": "Snö",
|
||||
"Live weather: the conditions under the camera": "Väder live: förhållandena under kameran",
|
||||
"No weather report here": "Ingen väderrapport här",
|
||||
"Rail": "Järnväg",
|
||||
"Urban rail": "Tunnelbana/spårväg",
|
||||
"Local rail": "Lokaltåg",
|
||||
|
||||
@@ -110,7 +110,6 @@
|
||||
"That shape could not be placed.": "Не вдалося розмістити фігуру.",
|
||||
"Could not place the shape: {error}": "Не вдалося розмістити фігуру: {error}",
|
||||
"Board cleared.": "Дошку очищено.",
|
||||
"{owner} is using the pointer — close it first.": "Вказівник зайнятий: «{owner}». Спершу закрийте його.",
|
||||
"{label} · Detailed outline unavailable": "{label} · Докладний контур недоступний",
|
||||
"Restoring shared view...": "Відновлення спільного вигляду...",
|
||||
"Configuring viewer...": "Налаштування переглядача...",
|
||||
@@ -784,12 +783,8 @@
|
||||
"Place A and B first": "Спершу поставте A і B",
|
||||
"action|CLEAR": "СКИНУТИ",
|
||||
"Remove the route and both markers": "Видалити маршрут і обидві мітки",
|
||||
"press Escape twice to leave Draw": "двічі натисніть Esc, щоб вийти з режиму «Малювання»",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "Активно: {name} — вимкніть {name}, потім задайте {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "Активно: {name} — {leave}, потім задайте {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "Показано лише перші повороти маршруту: {count}",
|
||||
"Turn-by-turn directions": "Покрокові вказівки",
|
||||
"Another map tool is using clicks — close it, then SET A again": "Клацання перехоплює інший інструмент карти — закрийте його й знову натисніть «ЗАДАТИ A»",
|
||||
"Routing…": "Побудова маршруту…",
|
||||
"No route found": "Маршрут не знайдено",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · перші повороти: {count}",
|
||||
@@ -2190,7 +2185,6 @@
|
||||
"Point the camera at the ground to use the view": "Наведіть камеру на землю, щоб вибрати видиму область",
|
||||
"That point cannot anchor a box": "Від цієї точки не можна побудувати область",
|
||||
"Imagery stops at ±{limit}° latitude": "Знімки є лише до ±{limit}° широти",
|
||||
"{owner} is using the pointer — close it first": "Вказівник зайнятий: «{owner}». Спершу закрийте його",
|
||||
"Box is {size} wide · limit {limit}": "Область завширшки {size} · межа {limit}",
|
||||
"View is {size} wide · limit {limit}": "Видима ширина {size} · межа {limit}",
|
||||
"VS BASEMAP": "З ПІДКЛАДКОЮ",
|
||||
@@ -3649,12 +3643,6 @@
|
||||
"{place} has no position to look for imagery at": "Для місця «{place}» немає координат для пошуку знімків",
|
||||
"No {source} imagery near {place}": "Немає знімків {source} поблизу: {place}",
|
||||
"{reason} (filters on: {filters})": "{reason} (увімкнено фільтри: {filters})",
|
||||
"Clouds": "Хмари",
|
||||
"Fog": "Туман",
|
||||
"Rain": "Дощ",
|
||||
"Snow": "Сніг",
|
||||
"Live weather: the conditions under the camera": "Погода зараз: умови під камерою",
|
||||
"No weather report here": "Тут немає зведення погоди",
|
||||
"Rail": "Залізниця",
|
||||
"Urban rail": "Міський",
|
||||
"Local rail": "Приміський",
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
"That shape could not be placed.": "该形状无法放置。",
|
||||
"Could not place the shape: {error}": "无法放置形状:{error}",
|
||||
"Board cleared.": "画板已清除。",
|
||||
"{owner} is using the pointer — close it first.": "{owner} 正在使用指针——请先关闭它。",
|
||||
"{label} · Detailed outline unavailable": "{label} · 无法获取详细轮廓",
|
||||
"Restoring shared view...": "正在恢复分享视图…",
|
||||
"Configuring viewer...": "正在配置视图…",
|
||||
@@ -748,12 +747,8 @@
|
||||
"Place A and B first": "请先放置 A 和 B",
|
||||
"action|CLEAR": "清除",
|
||||
"Remove the route and both markers": "移除路线和两个标注点",
|
||||
"press Escape twice to leave Draw": "按两次 Escape 退出“绘制”",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name} 正在使用——请先关闭 {name},再设置 {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name} 正在使用——请先{leave},再设置 {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "此路线仅显示前 {count} 个转向",
|
||||
"Turn-by-turn directions": "分步导航",
|
||||
"Another map tool is using clicks — close it, then SET A again": "另一个地图工具正在拦截点击——请先关闭它,再重新设置 A",
|
||||
"Routing…": "正在规划路线…",
|
||||
"No route found": "未找到路线",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · 前 {count} 个转向",
|
||||
@@ -2050,7 +2045,6 @@
|
||||
"Point the camera at the ground to use the view": "将相机对准地面才能使用当前视野",
|
||||
"That point cannot anchor a box": "该点无法作为框选锚点",
|
||||
"Imagery stops at ±{limit}° latitude": "影像仅覆盖到纬度 ±{limit}°",
|
||||
"{owner} is using the pointer — close it first": "{owner} 正在使用指针——请先将其关闭",
|
||||
"Box is {size} wide · limit {limit}": "框选宽 {size} · 上限 {limit}",
|
||||
"View is {size} wide · limit {limit}": "视野宽 {size} · 上限 {limit}",
|
||||
"VS BASEMAP": "对比底图",
|
||||
@@ -3406,12 +3400,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} 没有可查找影像的位置",
|
||||
"No {source} imagery near {place}": "{place} 附近没有 {source} 影像",
|
||||
"{reason} (filters on: {filters})": "{reason}(已开启筛选:{filters})",
|
||||
"Clouds": "云",
|
||||
"Fog": "雾",
|
||||
"Rain": "雨",
|
||||
"Snow": "雪",
|
||||
"Live weather: the conditions under the camera": "实时天气:相机下方的状况",
|
||||
"No weather report here": "此处没有天气报告",
|
||||
"Rail": "铁路",
|
||||
"Urban rail": "城市轨道",
|
||||
"Local rail": "市郊铁路",
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
"That shape could not be placed.": "該形狀無法放置。",
|
||||
"Could not place the shape: {error}": "無法放置形狀:{error}",
|
||||
"Board cleared.": "畫板已清除。",
|
||||
"{owner} is using the pointer — close it first.": "{owner} 正在使用指針——請先關閉它。",
|
||||
"{label} · Detailed outline unavailable": "{label} · 無法獲取詳細輪廓",
|
||||
"Restoring shared view...": "正在恢復分享視圖…",
|
||||
"Configuring viewer...": "正在配置視圖…",
|
||||
@@ -743,12 +742,8 @@
|
||||
"Place A and B first": "請先放置 A 和 B",
|
||||
"action|CLEAR": "清除",
|
||||
"Remove the route and both markers": "移除路線和兩個標註點",
|
||||
"press Escape twice to leave Draw": "按兩次 Escape 退出“繪製”",
|
||||
"{name} is active — turn {name} off, then set {endpoint}": "{name} 正在使用——請先關閉 {name},再設置 {endpoint}",
|
||||
"{name} is active — {leave}, then set {endpoint}": "{name} 正在使用——請先{leave},再設置 {endpoint}",
|
||||
"Only the first {count} turns of this route are shown": "此路線僅顯示前 {count} 個轉向",
|
||||
"Turn-by-turn directions": "分步導航",
|
||||
"Another map tool is using clicks — close it, then SET A again": "另一個地圖工具正在攔截點擊——請先關閉它,再重新設置 A",
|
||||
"Routing…": "正在規劃路線…",
|
||||
"No route found": "未找到路線",
|
||||
"{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · 前 {count} 個轉向",
|
||||
@@ -2040,7 +2035,6 @@
|
||||
"Point the camera at the ground to use the view": "將相機對準地面才能使用當前視野",
|
||||
"That point cannot anchor a box": "該點無法作為框選錨點",
|
||||
"Imagery stops at ±{limit}° latitude": "影像僅覆蓋到緯度 ±{limit}°",
|
||||
"{owner} is using the pointer — close it first": "{owner} 正在使用指針——請先將其關閉",
|
||||
"Box is {size} wide · limit {limit}": "框選寬 {size} · 上限 {limit}",
|
||||
"View is {size} wide · limit {limit}": "視野寬 {size} · 上限 {limit}",
|
||||
"VS BASEMAP": "對比底圖",
|
||||
@@ -3406,12 +3400,6 @@
|
||||
"{place} has no position to look for imagery at": "{place} 沒有可查找影像的位置",
|
||||
"No {source} imagery near {place}": "{place} 附近沒有 {source} 影像",
|
||||
"{reason} (filters on: {filters})": "{reason}(已開啟篩選:{filters})",
|
||||
"Clouds": "雲",
|
||||
"Fog": "霧",
|
||||
"Rain": "雨",
|
||||
"Snow": "雪",
|
||||
"Live weather: the conditions under the camera": "即時天氣:相機下方的狀況",
|
||||
"No weather report here": "此處沒有天氣報告",
|
||||
"Rail": "鐵路",
|
||||
"Urban rail": "城市軌道",
|
||||
"Local rail": "市郊鐵路",
|
||||
|
||||
+47
-33
@@ -14,17 +14,21 @@
|
||||
* and every subscriber reads the same {@link ClickEvent}; what a layer does
|
||||
* with a click that is not its own stays the layer's decision.
|
||||
*
|
||||
* Who gets the pointer:
|
||||
* Who gets the pointer: while a tool holds it (src/data/inputOwnership.js)
|
||||
* the port holds a lease for it (`bridgePointer`), so the port is not free,
|
||||
* but that lease takes no press: each event is decided here when it arrives.
|
||||
* - Ambient subscribers ({@link InputDispatcher.onClick}, and `onPointer`
|
||||
* without a lease) run only while no tool holds the pointer
|
||||
* (src/data/inputOwnership.js). The check is made once per event, before
|
||||
* any subscriber runs, so a tool that releases its lease while handling a
|
||||
* click does not let that same click through to ambient selection. Ambient
|
||||
* `move` and `up` are the exceptions: hover sees every move, so it can drop
|
||||
* its cursor or card when a tool takes the pointer, and a release always
|
||||
* reaches whoever began the press, so a drag started while the pointer was
|
||||
* free still ends (and gives its camera hold back).
|
||||
* without a lease) run only while no tool holds the pointer. The check is
|
||||
* made once per event, before any subscriber runs, so a tool that releases
|
||||
* its lease while handling a click does not let that same click through
|
||||
* to ambient selection. Ambient `move` and `up` are the exceptions: hover
|
||||
* sees every move, so it can drop its cursor or card when a tool takes the
|
||||
* pointer, and a release always reaches whoever began the press, so a drag
|
||||
* started while the pointer was free still ends (and gives its camera hold
|
||||
* back).
|
||||
* - Tool subscribers pass their lease and run only while it is current.
|
||||
* - A claim made on the port by anyone else takes the presses it grabs; the
|
||||
* rest reach the subscribers here as above.
|
||||
*
|
||||
* Camera input is suspended through the input port's counted holds
|
||||
* (`suspendCameraControls`), so a camera flight that ends cannot re-enable
|
||||
@@ -39,7 +43,11 @@
|
||||
* lives until {@link InputDispatcher.destroy}; the application scene owns
|
||||
* it.
|
||||
*/
|
||||
import { isLeaseCurrent, isPointerFree } from '../data/inputOwnership.js';
|
||||
import {
|
||||
bridgePointer,
|
||||
isLeaseCurrent,
|
||||
pointerOwner,
|
||||
} from '../data/inputOwnership.js';
|
||||
import {
|
||||
findPickOwner,
|
||||
pickContact,
|
||||
@@ -267,6 +275,10 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
|
||||
const cameraHolds = new Set();
|
||||
let destroyed = false;
|
||||
|
||||
// The port holds a lease while a tool here holds the pointer.
|
||||
const bridge = bridgePointer(port);
|
||||
|
||||
/** Tool subscribers whose lease is current, and ambient ones if `free`. */
|
||||
const run = (list, free, arg) => {
|
||||
for (const entry of [...list]) {
|
||||
if (entry.lease ? !isLeaseCurrent(leaseOf(entry)) : !free) continue;
|
||||
@@ -278,16 +290,18 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
|
||||
}
|
||||
};
|
||||
|
||||
// Each type is one port listener; the pointer's owner is read once per
|
||||
// event, before any subscriber runs.
|
||||
const offPort = [
|
||||
port.on('down', (ev) => {
|
||||
// Whether ambient subscribers hear a press, read once as it arrives. A
|
||||
// claim on the port that is not this bridge's has already taken the
|
||||
// presses it grabs; what reaches here is free unless a tool here holds it.
|
||||
const free = () => pointerOwner() === null;
|
||||
|
||||
// Each type is one port listener.
|
||||
const deliver = {
|
||||
down: (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.down, isPointerFree(), {
|
||||
position: xy(ev.position),
|
||||
});
|
||||
}),
|
||||
port.on('move', (ev) => {
|
||||
run(pointerSubscribers.down, free(), { position: xy(ev.position) });
|
||||
},
|
||||
move: (ev) => {
|
||||
if (!unmodified(ev)) return;
|
||||
const endPosition = xy(ev.endPosition ?? ev.position);
|
||||
let pickPosition;
|
||||
@@ -305,30 +319,29 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
|
||||
return pickPosition;
|
||||
},
|
||||
});
|
||||
}),
|
||||
port.on('up', (ev) => {
|
||||
},
|
||||
up: (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.up, true, { position: xy(ev.position) });
|
||||
}),
|
||||
port.on('click', (ev) => {
|
||||
},
|
||||
click: (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
const free = isPointerFree();
|
||||
const ambient = free();
|
||||
const event = createClickEvent(
|
||||
viewer,
|
||||
queryOf,
|
||||
xy(ev.position),
|
||||
ev.gesture ?? { travelPx: 0, durationMs: 0 },
|
||||
);
|
||||
run(pointerSubscribers.click, free, event);
|
||||
if (free) run(clickSubscribers, true, event);
|
||||
}),
|
||||
port.on('dblclick', (ev) => {
|
||||
run(pointerSubscribers.click, ambient, event);
|
||||
if (ambient) run(clickSubscribers, true, event);
|
||||
},
|
||||
dblclick: (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.dblclick, isPointerFree(), {
|
||||
position: xy(ev.position),
|
||||
});
|
||||
}),
|
||||
];
|
||||
run(pointerSubscribers.dblclick, free(), { position: xy(ev.position) });
|
||||
},
|
||||
};
|
||||
const offPort = POINTER_TYPES.map((type) => port.on(type, deliver[type]));
|
||||
|
||||
const subscribe = (list, entry) => {
|
||||
if (destroyed) return () => {};
|
||||
@@ -393,6 +406,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
|
||||
clickSubscribers.length = 0;
|
||||
for (const type of POINTER_TYPES) pointerSubscribers[type].length = 0;
|
||||
for (const off of offPort) off();
|
||||
bridge.off();
|
||||
for (const hold of [...stockHolds]) hold();
|
||||
for (const hold of [...cameraHolds]) hold();
|
||||
// A port built for this viewer goes with its dispatcher; a
|
||||
|
||||
@@ -2,7 +2,7 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { inputFor, pickAt } from './dispatcher.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { bindRenderer, findInput } from '../render/rendererOf.js';
|
||||
import {
|
||||
FAKE_EVENT_TYPES,
|
||||
FakeScreenSpaceEventHandler as FakeHandler,
|
||||
@@ -193,6 +193,98 @@ test('a stale lease gets nothing once its successor holds the pointer', (t) => {
|
||||
assert.equal(staleRan, 0);
|
||||
});
|
||||
|
||||
test("a tool's claim holds the renderer's input port without taking its presses", (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const port = findInput(h.viewer);
|
||||
const heard = [];
|
||||
port.on('click', () => heard.push('port'));
|
||||
const lease = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
h.input.onPointer('click', () => heard.push('tool'), { lease });
|
||||
assert.equal(port.isPointerFree(), false);
|
||||
h.click();
|
||||
// Who hears a click is decided here, when it arrives; the port gives
|
||||
// every press on, so the renderer's own select runs unless held off.
|
||||
assert.deepEqual(heard, ['tool', 'port']);
|
||||
releasePointer(lease);
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
h.click();
|
||||
assert.deepEqual(heard, ['tool', 'port', 'port']);
|
||||
});
|
||||
|
||||
test('a click goes where the pointer is when it arrives: a tool that claims during the press gets it, ambient selection does not', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const heard = [];
|
||||
h.input.onClick(() => heard.push('ambient'));
|
||||
let lease = null;
|
||||
h.input.onPointer('click', () => heard.push('tool'), {
|
||||
lease: () => lease,
|
||||
});
|
||||
h.input.onPointer('dblclick', () => heard.push('tool:dblclick'), {
|
||||
lease: () => lease,
|
||||
});
|
||||
h.input.onPointer('dblclick', () => heard.push('ambient:dblclick'));
|
||||
h.handler.fire(TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
|
||||
lease = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
h.handler.fire(TYPES.LEFT_UP, { position: { x: 10, y: 10 } });
|
||||
h.handler.fire(TYPES.LEFT_CLICK, { position: { x: 10, y: 10 } });
|
||||
h.handler.fire(TYPES.LEFT_DOUBLE_CLICK, { position: { x: 10, y: 10 } });
|
||||
assert.deepEqual(heard, ['tool', 'tool:dblclick']);
|
||||
});
|
||||
|
||||
test('a click goes where the pointer is when it arrives: after a tool lets go during the press, ambient selection gets it', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const heard = [];
|
||||
h.input.onClick(() => heard.push('ambient'));
|
||||
const lease = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
h.input.onPointer('click', () => heard.push('tool'), { lease });
|
||||
h.input.onPointer('dblclick', () => heard.push('ambient:dblclick'));
|
||||
h.handler.fire(TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
|
||||
releasePointer(lease);
|
||||
h.handler.fire(TYPES.LEFT_UP, { position: { x: 10, y: 10 } });
|
||||
h.handler.fire(TYPES.LEFT_CLICK, { position: { x: 10, y: 10 } });
|
||||
h.handler.fire(TYPES.LEFT_DOUBLE_CLICK, { position: { x: 10, y: 10 } });
|
||||
assert.deepEqual(heard, ['ambient', 'ambient:dblclick']);
|
||||
});
|
||||
|
||||
test("a claim on the renderer's port takes over from the tool, which is told", (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const port = findInput(h.viewer);
|
||||
const told = [];
|
||||
const heard = [];
|
||||
const lease = claimPointer('test-tool', { onLost: () => told.push('tool') });
|
||||
h.input.onPointer('click', () => heard.push('tool'), { lease });
|
||||
h.input.onClick(() => heard.push('ambient'));
|
||||
const other = port.claimPointer('other');
|
||||
t.after(() => other.release());
|
||||
port.on('click', () => heard.push('other'), { lease: other });
|
||||
assert.deepEqual(told, ['tool']);
|
||||
h.click();
|
||||
assert.deepEqual(
|
||||
heard,
|
||||
['other'],
|
||||
'neither the old tool nor ambient selection',
|
||||
);
|
||||
releasePointer(lease);
|
||||
assert.equal(other.current, true, "the old tool's release frees nothing");
|
||||
});
|
||||
|
||||
test('destroy gives the port its lease back', () => {
|
||||
const h = harness();
|
||||
const port = findInput(h.viewer);
|
||||
const lease = claimPointer('test-tool');
|
||||
assert.equal(port.isPointerFree(), false);
|
||||
h.input.destroy();
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
releasePointer(lease);
|
||||
});
|
||||
|
||||
test('camera input returns only when the last hold releases', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
|
||||
+26
-103
@@ -20,14 +20,7 @@ import { roadLabel } from '../../data/routeSteps.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import {
|
||||
t,
|
||||
msg,
|
||||
formatNumber,
|
||||
getLocale,
|
||||
translateKnown,
|
||||
} from '../../i18n/index.js';
|
||||
import { pointerOwnerName } from '../../data/pointerOwnerNames.js';
|
||||
import { t, msg, formatNumber, getLocale } from '../../i18n/index.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
formatQuantity,
|
||||
@@ -519,46 +512,6 @@ export function directionsRowControls(state) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Plain names for the tools that can be holding the pointer, and how to leave
|
||||
* each one. A tool missing from here still gets a usable sentence from its id.
|
||||
*/
|
||||
export const POINTER_TOOL_EXITS = Object.freeze({
|
||||
draw: Object.freeze({
|
||||
name: msg('Draw'),
|
||||
leave: msg('press Escape twice to leave Draw'),
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* What to say when a globe click cannot be armed because something else owns
|
||||
* the pointer.
|
||||
*
|
||||
* The claim failing used to be silent: the chip simply did not light and the
|
||||
* operator was left to guess which of the open tools was eating the click
|
||||
* (owner field test — he thought Directions was broken). So the message names
|
||||
* the tool and says how to put it down. Pure.
|
||||
* @param {string|null} owner Current pointer-owner id.
|
||||
* @param {'a'|'b'} which Endpoint that was being armed.
|
||||
* @returns {string|null} Toast text, or null when nothing holds the pointer.
|
||||
*/
|
||||
export function pointerBlockedMessage(owner, which) {
|
||||
const id = typeof owner === 'string' ? owner.trim() : '';
|
||||
if (!id || id === DIRECTIONS_POINTER_OWNER) return null;
|
||||
const endpoint = which === 'b' ? 'B' : 'A';
|
||||
const known = POINTER_TOOL_EXITS[id];
|
||||
if (!known)
|
||||
return t('{name} is active — turn {name} off, then set {endpoint}', {
|
||||
name: translateKnown(pointerOwnerName(id)),
|
||||
endpoint,
|
||||
});
|
||||
return t('{name} is active — {leave}, then set {endpoint}', {
|
||||
name: t(known.name),
|
||||
leave: t(known.leave),
|
||||
endpoint,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Which maneuvers get a dot on the globe: every one except departure and
|
||||
* arrival, which the A and B markers already stand for.
|
||||
@@ -675,29 +628,8 @@ export function stepIndexAtDistance(steps, traveledM) {
|
||||
* @returns {object}
|
||||
*/
|
||||
export function directionsStats(state) {
|
||||
const {
|
||||
mode,
|
||||
a,
|
||||
b,
|
||||
status,
|
||||
error,
|
||||
route,
|
||||
lastUpdate,
|
||||
armed,
|
||||
pointerBlocked,
|
||||
} = state;
|
||||
const { mode, a, b, status, error, route, lastUpdate, armed } = state;
|
||||
const source = 'OSM routing'; // English in layer state; the layer row translates it
|
||||
if (pointerBlocked) {
|
||||
return {
|
||||
count: route?.steps.length || 0,
|
||||
lastUpdate,
|
||||
error: msg(
|
||||
'Another map tool is using clicks — close it, then SET A again',
|
||||
),
|
||||
status: 'empty',
|
||||
source,
|
||||
};
|
||||
}
|
||||
if (status === 'routing') {
|
||||
return {
|
||||
count: 0,
|
||||
@@ -970,8 +902,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
let _renderHeld = false;
|
||||
let _rowControlsListener = null;
|
||||
let _dataManager = null;
|
||||
/** Set when arming failed because another tool holds the pointer. */
|
||||
let _pointerBlocked = false;
|
||||
/**
|
||||
* What `claimPointer` handed back for the claim this layer currently holds, or
|
||||
* null. Held rather than re-derived so the release names THIS claim: a claim
|
||||
@@ -1020,7 +950,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
lastUpdate: _lastUpdate,
|
||||
selectedStep: _selectedStep,
|
||||
flightStep: _flightStep,
|
||||
pointerBlocked: _pointerBlocked,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1346,11 +1275,14 @@ export function createDirectionsLayer({ services, source }) {
|
||||
* Give the pointer back, but only once the click that consumed it has finished
|
||||
* being dispatched.
|
||||
*
|
||||
* The input dispatcher decides who hears a click before any subscriber runs,
|
||||
* but DOM listeners on the canvas (evidence cards) still run later inside
|
||||
* the SAME browser event. Releasing the claim the instant this layer places
|
||||
* an endpoint would hand that same click to them. A timer, not a microtask:
|
||||
* a microtask checkpoint runs between two DOM listeners, which is exactly the
|
||||
* The input dispatcher decides who hears a click before any subscriber
|
||||
* runs, so its own click subscribers cannot hear this click once it is let
|
||||
* go. DOM `click` listeners on the canvas (the evidence cards) are another
|
||||
* matter: the renderer's click comes from the pointer's `up`, and the
|
||||
* browser's `click` follows inside the SAME input event, where they ask
|
||||
* `isPointerFree()`. Releasing the claim the instant this layer places an
|
||||
* endpoint would hand that same click to them. A timer, not a microtask: a
|
||||
* microtask checkpoint runs between two DOM listeners, which is exactly the
|
||||
* gap this closes.
|
||||
*/
|
||||
function releaseClaimAfterDispatch() {
|
||||
@@ -1368,7 +1300,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
*/
|
||||
function disarm({ afterDispatch = false } = {}) {
|
||||
_armed = null;
|
||||
_pointerBlocked = false;
|
||||
if (afterDispatch) releaseClaimAfterDispatch();
|
||||
else releaseClaim();
|
||||
}
|
||||
@@ -1403,8 +1334,9 @@ export function createDirectionsLayer({ services, source }) {
|
||||
* Arm (or cancel) a globe click for one endpoint.
|
||||
*
|
||||
* Placement is a TOOL: it takes the pointer so no ambient layer also selects
|
||||
* whatever happened to be under the click. If another tool already holds it,
|
||||
* this refuses — nothing is armed and the row says why.
|
||||
* whatever happened to be under the click. The newest claim takes over: the
|
||||
* tool holding it is told and turns itself off, and a newer tool taking it
|
||||
* disarms this layer.
|
||||
* @param {null|'a'|'b'} which
|
||||
* @returns {boolean} Whether the layer is armed after this call.
|
||||
*/
|
||||
@@ -1413,23 +1345,19 @@ export function createDirectionsLayer({ services, source }) {
|
||||
disarm();
|
||||
return false;
|
||||
}
|
||||
// A claim does not stack, not even under the same name — two live instances
|
||||
// of one tool are two owners. So re-arming for the other endpoint reuses the
|
||||
// lease already held instead of asking for a second one.
|
||||
// Two live instances of one tool are two owners, so a second claim under
|
||||
// the same name would end this layer's own. Re-arming for the other
|
||||
// endpoint reuses the lease already held instead.
|
||||
if (!services.input.isLeaseCurrent(_pointerClaim)) {
|
||||
const lease = services.input.claimPointer(DIRECTIONS_POINTER_OWNER);
|
||||
if (!lease) {
|
||||
_armed = null;
|
||||
_pointerBlocked = true;
|
||||
// The row already says it, but the row is not where the operator is
|
||||
// looking after pressing a chip — say it where the app says everything.
|
||||
const message = pointerBlockedMessage(
|
||||
services.input.pointerOwner(),
|
||||
which,
|
||||
);
|
||||
if (message) _shellSeams?.showToast?.(message);
|
||||
return false;
|
||||
}
|
||||
// The newest claim takes over: a tool holding the pointer is told and
|
||||
// turns itself off, and a newer one disarms this layer as Escape would.
|
||||
const lease = services.input.claimPointer(DIRECTIONS_POINTER_OWNER, {
|
||||
onLost: () => {
|
||||
if (_pointerClaim !== lease) return;
|
||||
disarm();
|
||||
notifyRow();
|
||||
},
|
||||
});
|
||||
_pointerClaim = lease;
|
||||
}
|
||||
// A pending release from the previous placement would otherwise hand the
|
||||
@@ -1438,7 +1366,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
clearTimeout(_releaseTimer);
|
||||
_releaseTimer = null;
|
||||
}
|
||||
_pointerBlocked = false;
|
||||
_armed = which;
|
||||
_clearStepSelection();
|
||||
return true;
|
||||
@@ -1741,7 +1668,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
*/
|
||||
enable(viewer) {
|
||||
_enabled = true;
|
||||
_pointerBlocked = false;
|
||||
if (_sets) _sets.steps.show = true;
|
||||
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, true);
|
||||
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, true);
|
||||
@@ -1839,10 +1765,7 @@ export function createDirectionsLayer({ services, source }) {
|
||||
* the same immediate-navigation facade voice destinations use — so the route
|
||||
* dolly is one more caller of the single camera owner rather than a second
|
||||
* one. `floorFn`/`warmFn` are the shared ground floor the dolly flies over.
|
||||
* `showToast` is the app's own toast, so a refusal is said where the rest of
|
||||
* the UI says things.
|
||||
* @param {{runNavigation?: Function, floorFn?: Function, warmFn?: Function,
|
||||
* showToast?: Function}|null} services
|
||||
* @param {{runNavigation?: Function, floorFn?: Function, warmFn?: Function}|null} services
|
||||
*/
|
||||
attachShellServices(services) {
|
||||
_shellSeams = services || null;
|
||||
|
||||
@@ -20,10 +20,6 @@ const idle = {
|
||||
};
|
||||
|
||||
const cases = [
|
||||
[
|
||||
{ ...idle, pointerBlocked: true },
|
||||
'Another map tool is using clicks — close it, then SET A again',
|
||||
],
|
||||
[{ ...idle, status: 'error' }, 'No route found'],
|
||||
[
|
||||
{ ...idle, status: 'error', error: 'Routing timed out' },
|
||||
|
||||
@@ -123,6 +123,8 @@ export function createIcons({ flightState, services, parts }) {
|
||||
icons._planIcon(icao24, { fromCourseDeg: set.course(icao24, t) });
|
||||
return;
|
||||
}
|
||||
// Following the clock, not drawn at a time before it was there.
|
||||
set.setUnseen(icao24, flightState._drUnseen);
|
||||
const planned = set.expires(icao24) !== -Infinity;
|
||||
const prev = planned ? set.course(icao24, t) : null;
|
||||
// The pin holds the position; the renderer glides the course onto the
|
||||
|
||||
@@ -5,6 +5,14 @@ import { createFlightState } from './state.js';
|
||||
import { createIcons } from './icons.js';
|
||||
import { createContactIcons } from '../../data/aircraftIconLayer.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import {
|
||||
aircraftMotionRegime,
|
||||
createMotionRegime,
|
||||
fixEpochMs,
|
||||
} from '../../data/aircraftMotionRegime.js';
|
||||
import { mergeAircraftTimelineFixes } from '../../data/timelineHistory.js';
|
||||
import { julianFromEpochMs } from '../../geo/julian.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js';
|
||||
|
||||
function services(focus = {}) {
|
||||
return {
|
||||
@@ -300,3 +308,110 @@ test('a live contact a placement places is drawn along where it places it', (t)
|
||||
icons._planIcon('p');
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
/**
|
||||
* A layer following the world clock at `world.ms`, its contacts placed by
|
||||
* the shared regime on their own fixes around the time.
|
||||
*/
|
||||
function clockSetup(world) {
|
||||
const fields = { speed: 'velocity', track: 'true_track' };
|
||||
const { flightState, icons, set } = setup({
|
||||
motion: {
|
||||
_displayTimeAt: (ms) => julianFromEpochMs(ms),
|
||||
_fixEpochMs: fixEpochMs,
|
||||
_deadReckon: () => null,
|
||||
_motionRegime: (history, info, renderTime) =>
|
||||
aircraftMotionRegime(
|
||||
history,
|
||||
info,
|
||||
renderTime,
|
||||
fields,
|
||||
createMotionRegime(),
|
||||
),
|
||||
},
|
||||
});
|
||||
flightState.timeline = { active: () => true };
|
||||
flightState.now = () => world.ms;
|
||||
return { flightState, icons, set };
|
||||
}
|
||||
|
||||
/** A contact's row, never planned, and its own fixes at `times` (ms). */
|
||||
function onFixes(flightState, set, id, times) {
|
||||
set.put(
|
||||
{
|
||||
id,
|
||||
pos: { x: 0, y: 0, z: 0 },
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
course: 0,
|
||||
size: [20, 20],
|
||||
show: true,
|
||||
focus: 1,
|
||||
meta: { layer: 'flights', id },
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
);
|
||||
flightState.records.data.set(id, { velocity: 100 });
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
fixes: times.map((atMs, i) => ({
|
||||
atMs,
|
||||
lat: 30,
|
||||
lon: i * 0.05,
|
||||
altitudeM: null,
|
||||
})),
|
||||
},
|
||||
{ renderAltitudeM: 3_000 },
|
||||
100,
|
||||
times[0],
|
||||
);
|
||||
flightState._positionHistory.set(id, history);
|
||||
return history;
|
||||
}
|
||||
|
||||
test('following the clock, a contact is not drawn before it was there, and is from its warm-up on', () => {
|
||||
const first = Date.UTC(2026, 10, 9, 12);
|
||||
const world = { ms: first - 10 * 60_000 };
|
||||
const { flightState, icons, set } = clockSetup(world);
|
||||
onFixes(flightState, set, 'c', [first, first + 60_000]);
|
||||
icons._planIcon('c');
|
||||
assert.equal(set.shown('c'), false, 'ten minutes before its first fix');
|
||||
assert.equal(set.expires('c'), first - TIMELINE_UNSEEN_MS);
|
||||
|
||||
// Half a minute before its first fix it is drawn, reaching it.
|
||||
world.ms = first - 30_000;
|
||||
icons._replanExpired(world.ms);
|
||||
assert.equal(set.shown('c'), true);
|
||||
|
||||
// The clock moved back: not there yet again.
|
||||
world.ms = first - 5 * 60_000;
|
||||
icons._replanExpired(world.ms);
|
||||
assert.equal(set.shown('c'), false);
|
||||
});
|
||||
|
||||
test('following the clock, a move back within the fixes draws a contact where it was then', () => {
|
||||
const t0 = Date.UTC(2026, 10, 9, 12);
|
||||
const world = { ms: t0 + 100_000 };
|
||||
const { flightState, icons, set } = clockSetup(world);
|
||||
const history = onFixes(flightState, set, 'c', [
|
||||
t0,
|
||||
t0 + 60_000,
|
||||
t0 + 120_000,
|
||||
]);
|
||||
icons._planIcon('c');
|
||||
icons._replanExpired(world.ms);
|
||||
// Back to half way between the first two fixes.
|
||||
world.ms = t0 + 30_000;
|
||||
icons._replanExpired(world.ms);
|
||||
const drawn = set.position('c', world.ms);
|
||||
const half = Cesium.Cartesian3.distance(
|
||||
history[0].position,
|
||||
history[1].position,
|
||||
);
|
||||
for (const fix of history.slice(0, 2))
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Cartesian3.distance(drawn, fix.position) - half / 2) <
|
||||
half * 0.05,
|
||||
'half way between its first two fixes',
|
||||
);
|
||||
});
|
||||
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Wind streamlines baked from a wind grid (`streamlines.js`): the paths a
|
||||
* `windStreamlines` field draws.
|
||||
*/
|
||||
|
||||
/** A wind grid: row-major from `la1` (north) southward. */
|
||||
export interface WindGrid {
|
||||
u: Float32Array;
|
||||
v: Float32Array;
|
||||
nx: number;
|
||||
ny: number;
|
||||
lo1: number;
|
||||
la1: number;
|
||||
dx: number;
|
||||
dy: number;
|
||||
}
|
||||
|
||||
export interface WindPath {
|
||||
coordinates: Array<[lon: number, lat: number]>;
|
||||
speed: number;
|
||||
seed: number;
|
||||
phase: number;
|
||||
}
|
||||
|
||||
export const WIND_PATH_LIMIT: number;
|
||||
export const WIND_NARROW_PATH_LIMIT: number;
|
||||
export const WIND_PATH_STEPS: number;
|
||||
export const WIND_DISPLAY_HEIGHT_METERS: number;
|
||||
export const WIND_CELL_DEGREES: number;
|
||||
|
||||
/**
|
||||
* Bake streamlines once from a wind grid; with `bounds` (degrees), seeds
|
||||
* fall inside it and paths stop at its edges.
|
||||
*/
|
||||
export function bakeWindStreamlines(
|
||||
grid: WindGrid,
|
||||
options?: {
|
||||
count?: number;
|
||||
steps?: number;
|
||||
stepSeconds?: number;
|
||||
bounds?: {
|
||||
west: number;
|
||||
south: number;
|
||||
east: number;
|
||||
north: number;
|
||||
} | null;
|
||||
},
|
||||
): WindPath[];
|
||||
|
||||
/** Group baked paths by their middle coordinate. */
|
||||
export function groupWindPaths(
|
||||
paths: WindPath[],
|
||||
cellDegrees?: number,
|
||||
): Array<{ id: number; paths: WindPath[] }>;
|
||||
+26
-25
@@ -56,7 +56,10 @@ function sameView(a, b) {
|
||||
* report: (error: unknown) => void, thresholds?: boolean}} options `pose`
|
||||
* is read only while a `changed` listener is registered; `world` (the
|
||||
* eye in world coordinates; `pose()` when omitted) is read by
|
||||
* `stepMoveDetection`; `thresholds`
|
||||
* `stepMoveDetection`, which keeps what it returns: a view it is handed
|
||||
* again is the same eye, and a view is never changed once handed (a new
|
||||
* eye is a new object); `pose` and `world` results are read, never
|
||||
* changed; `thresholds`
|
||||
* false (a renderer without `cameraChangeThreshold`) ignores a listener's
|
||||
* own threshold, so every listener fires at 0.5.
|
||||
*/
|
||||
@@ -66,8 +69,10 @@ export function createCameraEvents({
|
||||
report,
|
||||
thresholds = true,
|
||||
}) {
|
||||
// Lists are copied on change, not on delivery: a delivery runs over the
|
||||
// list as it stood, and a change made during it makes a new one.
|
||||
const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []]));
|
||||
const commandHooks = [];
|
||||
let commandHooks = [];
|
||||
let lastView = null;
|
||||
let moving = false;
|
||||
let lastMovedAt = 0;
|
||||
@@ -82,7 +87,7 @@ export function createCameraEvents({
|
||||
}
|
||||
|
||||
function emit(event) {
|
||||
for (const entry of listeners[event].slice()) deliver(entry);
|
||||
for (const entry of listeners[event]) deliver(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,15 +97,14 @@ export function createCameraEvents({
|
||||
* @returns {() => void}
|
||||
*/
|
||||
function on(event, cb, options = {}) {
|
||||
const list = listeners[event];
|
||||
if (!list) throw new Error(`Unknown camera event: ${event}`);
|
||||
if (!listeners[event]) throw new Error(`Unknown camera event: ${event}`);
|
||||
const threshold = thresholds ? (options.threshold ?? 0.5) : 0.5;
|
||||
const entry = { cb, live: true, threshold };
|
||||
list.push(entry);
|
||||
listeners[event] = [...listeners[event], entry];
|
||||
return () => {
|
||||
if (!entry.live) return;
|
||||
entry.live = false;
|
||||
const i = list.indexOf(entry);
|
||||
if (i >= 0) list.splice(i, 1);
|
||||
listeners[event] = listeners[event].filter((e) => e !== entry);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -113,7 +117,7 @@ export function createCameraEvents({
|
||||
const list = listeners.changed;
|
||||
if (!list.length) return;
|
||||
const current = pose();
|
||||
for (const entry of list.slice()) {
|
||||
for (const entry of list) {
|
||||
if (!entry.live) continue;
|
||||
const t = entry.threshold;
|
||||
entry.heading ??= current.heading;
|
||||
@@ -152,14 +156,11 @@ export function createCameraEvents({
|
||||
* @param {number} now
|
||||
*/
|
||||
function stepMoveDetection(now) {
|
||||
const v = world();
|
||||
const current = {
|
||||
position: v.position,
|
||||
direction: v.direction,
|
||||
up: v.up,
|
||||
lens: v.lens,
|
||||
};
|
||||
const changed = lastView && !sameView(lastView, current);
|
||||
// `world` hands its last view again while the eye stands: that one is
|
||||
// unchanged without comparing.
|
||||
const current = world();
|
||||
const changed =
|
||||
lastView !== null && current !== lastView && !sameView(lastView, current);
|
||||
lastView = current;
|
||||
if (changed) {
|
||||
lastMovedAt = now;
|
||||
@@ -178,7 +179,7 @@ export function createCameraEvents({
|
||||
* @param {import('../contract/camera').CameraCommand['kind']} kind
|
||||
*/
|
||||
function command(kind) {
|
||||
for (const entry of commandHooks.slice()) {
|
||||
for (const entry of commandHooks) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb({ kind });
|
||||
@@ -196,22 +197,22 @@ export function createCameraEvents({
|
||||
*/
|
||||
function onCommand(cb) {
|
||||
const entry = { cb, live: true };
|
||||
commandHooks.push(entry);
|
||||
commandHooks = [...commandHooks, entry];
|
||||
return () => {
|
||||
if (!entry.live) return;
|
||||
entry.live = false;
|
||||
const i = commandHooks.indexOf(entry);
|
||||
if (i >= 0) commandHooks.splice(i, 1);
|
||||
commandHooks = commandHooks.filter((e) => e !== entry);
|
||||
};
|
||||
}
|
||||
|
||||
/** Drop every listener and hook, including those of an event under way. */
|
||||
function clear() {
|
||||
for (const list of Object.values(listeners)) {
|
||||
for (const entry of list) entry.live = false;
|
||||
list.length = 0;
|
||||
for (const event of CAMERA_EVENTS) {
|
||||
for (const entry of listeners[event]) entry.live = false;
|
||||
listeners[event] = [];
|
||||
}
|
||||
for (const entry of commandHooks) entry.live = false;
|
||||
commandHooks.length = 0;
|
||||
commandHooks = [];
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
|
||||
* engine type crosses the contract.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { createApplicationViewer } from './applicationViewer.js';
|
||||
import { CONTRACT_VERSION } from '../contract/index.js';
|
||||
import { bindRenderer } from '../rendererOf.js';
|
||||
@@ -80,7 +81,13 @@ export function createCesiumRendererPlugin({
|
||||
id: 'cesium',
|
||||
/**
|
||||
* The credentials are the globe port's, for a base set through it; the
|
||||
* scene still loads the application's own base itself.
|
||||
* scene still loads the application's own base itself. `msaa` makes
|
||||
* the viewer (4 when not given);
|
||||
* `sky` and `time` are set before the first frame; `clock.now` is what
|
||||
* the frame ticks, the camera's `moveEnd` wait, input and flights (the
|
||||
* scene's tweens step on it) read, `clock.date` what a `live` motion
|
||||
* clock reads. Inertia keeps Cesium's own timing: its camera controls
|
||||
* time a release by the system clock.
|
||||
* @param {import('../contract/renderer').CreateOptions} options
|
||||
* @returns {Promise<TransitionalRenderer>}
|
||||
*/
|
||||
@@ -90,6 +97,10 @@ export function createCesiumRendererPlugin({
|
||||
googleApiKey,
|
||||
googleTokens,
|
||||
worldDataToken,
|
||||
msaa,
|
||||
sky,
|
||||
time,
|
||||
clock,
|
||||
}) {
|
||||
signal?.throwIfAborted();
|
||||
// Provider attribution stays visible, including clean-view and recording.
|
||||
@@ -109,7 +120,11 @@ export function createCesiumRendererPlugin({
|
||||
// The application's notice (`renderFailureNotice`) replaces
|
||||
// Cesium's dead-end panel when rendering stops.
|
||||
showRenderLoopErrors: false,
|
||||
msaa,
|
||||
});
|
||||
if (Number.isFinite(time))
|
||||
viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date(time));
|
||||
const now = clock ? () => clock.now() : undefined;
|
||||
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
|
||||
ports = createCesiumPorts(viewer, {
|
||||
capabilities,
|
||||
@@ -117,6 +132,7 @@ export function createCesiumRendererPlugin({
|
||||
idleFps: IDLE_FRAME_RATE,
|
||||
credentials: { googleApiKey, googleTokens, worldDataToken },
|
||||
...(cameraController ? { cameraController } : {}),
|
||||
...(clock ? { now, date: () => clock.date() } : {}),
|
||||
});
|
||||
input = createCesiumInput(viewer, {
|
||||
query: ports.query,
|
||||
@@ -124,7 +140,10 @@ export function createCesiumRendererPlugin({
|
||||
...(ports.suspendCamera
|
||||
? { suspendCamera: ports.suspendCamera }
|
||||
: {}),
|
||||
...(clock ? { now } : {}),
|
||||
});
|
||||
// Before the first frame, so nothing draws in the wrong sky.
|
||||
if (sky) ports.globe.sky.set(sky);
|
||||
ports.attachInput?.(input.port);
|
||||
// Free look is limited to low heights from the start, on Cesium's
|
||||
// own controls (the controller keeps its own limits).
|
||||
|
||||
@@ -193,7 +193,7 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('work pending at destroy settles and lets go of the scene', async (t) => {
|
||||
test('work pending at destroy is rejected and lets go of the scene', async (t) => {
|
||||
withDocument(t, fakeDocument());
|
||||
const viewers = [];
|
||||
const plugin = createCesiumRendererPlugin({
|
||||
@@ -207,9 +207,10 @@ test('work pending at destroy settles and lets go of the scene', async (t) => {
|
||||
const renderer = await plugin.create({ container: {} });
|
||||
const rendered = renderer.frame.renderOnce();
|
||||
renderer.destroy();
|
||||
await rendered;
|
||||
await assert.rejects(rendered, /renderer destroyed/, 'the one waiting');
|
||||
assert.equal(viewers[0].listeners.size, 0, 'no one-shot render stays');
|
||||
await renderer.frame.renderOnce();
|
||||
await assert.rejects(renderer.frame.renderOnce(), /renderer destroyed/);
|
||||
await assert.rejects(renderer.capture(), /renderer destroyed/);
|
||||
|
||||
const waiting = await plugin.create({ container: {} });
|
||||
const standing = viewers[1].listeners.size;
|
||||
@@ -325,3 +326,61 @@ test('only renderers this plugin made reach a Cesium viewer', () => {
|
||||
});
|
||||
|
||||
const EXPECTED_MISSING = [];
|
||||
|
||||
test('the plugin makes its viewer with the creation options, and sets the sky, time and clock before the first frame', async (t) => {
|
||||
const doc = fakeDocument();
|
||||
withDocument(t, doc);
|
||||
const log = [];
|
||||
let given;
|
||||
let viewer;
|
||||
const plugin = createCesiumRendererPlugin({
|
||||
createViewer(options) {
|
||||
given = options;
|
||||
viewer = fakeViewer(log);
|
||||
for (const phase of [
|
||||
'preUpdate',
|
||||
'postUpdate',
|
||||
'preRender',
|
||||
'postRender',
|
||||
])
|
||||
viewer.scene[phase] = new Cesium.Event();
|
||||
viewer.scene.skyAtmosphere = { show: true };
|
||||
viewer.scene.fog = { enabled: true };
|
||||
viewer.clock = { currentTime: Cesium.JulianDate.now() };
|
||||
return viewer;
|
||||
},
|
||||
});
|
||||
const time = Date.UTC(2030, 5, 21, 12);
|
||||
const clock = { now: () => 1234.5, date: () => time + 60_000 };
|
||||
const renderer = await plugin.create({
|
||||
container: { tag: 'container' },
|
||||
signal: new AbortController().signal,
|
||||
msaa: 2,
|
||||
sky: { atmosphere: false, fog: false },
|
||||
time,
|
||||
clock,
|
||||
});
|
||||
assert.equal(given.msaa, 2, 'multisampling');
|
||||
assert.equal(viewer.scene.skyAtmosphere.show, false, 'the sky, set');
|
||||
assert.equal(viewer.scene.fog.enabled, false);
|
||||
assert.equal(renderer.globe.sky.get().fog, false);
|
||||
assert.equal(
|
||||
Cesium.JulianDate.toDate(viewer.clock.currentTime).getTime(),
|
||||
time,
|
||||
'the scene time',
|
||||
);
|
||||
const ticks = [];
|
||||
renderer.frame.on('preUpdate', (tick) => ticks.push(tick.now));
|
||||
viewer.scene.preUpdate.raiseEvent(viewer.scene, viewer.clock.currentTime);
|
||||
assert.deepEqual(ticks, [1234.5], 'ticks read the clock given');
|
||||
renderer.destroy();
|
||||
|
||||
// Not given, the viewer is made as it always was.
|
||||
await plugin
|
||||
.create({
|
||||
container: { tag: 'container' },
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
.then((r) => r.destroy());
|
||||
assert.equal(given.msaa, undefined);
|
||||
});
|
||||
@@ -54,11 +54,13 @@ if (typeof window !== 'undefined' && !window.__CESIUM__)
|
||||
/**
|
||||
* Cesium.Viewer options of the standard globe viewer. `showRenderLoopErrors`
|
||||
* false leaves render errors to the caller's own notice instead of Cesium's
|
||||
* panel.
|
||||
* panel; `msaa` is the multisampling to start with (0 off, 4 by default).
|
||||
* The drawing buffer is kept after presenting, for `capture` and
|
||||
* `readPixels` to read the frame drawn.
|
||||
*/
|
||||
export function applicationViewerOptions(
|
||||
creditContainer,
|
||||
{ showRenderLoopErrors = true } = {},
|
||||
{ showRenderLoopErrors = true, msaa = 4 } = {},
|
||||
) {
|
||||
return {
|
||||
timeline: false,
|
||||
@@ -77,23 +79,31 @@ export function applicationViewerOptions(
|
||||
// which would also stop CesiumWidget from creating the Sun and Moon.
|
||||
skyBox: new StarrySky(),
|
||||
creditContainer,
|
||||
msaaSamples: 4,
|
||||
// Cesium's 1 is no multisampling.
|
||||
msaaSamples: msaa || 1,
|
||||
contextOptions: { webgl: { preserveDrawingBuffer: true } },
|
||||
showRenderLoopErrors,
|
||||
};
|
||||
}
|
||||
|
||||
/** Create the standard globe viewer in caller-owned, visible containers. */
|
||||
/**
|
||||
* Create the standard globe viewer in caller-owned, visible containers;
|
||||
* `msaa` as `applicationViewerOptions` takes it.
|
||||
*/
|
||||
export function createApplicationViewer({
|
||||
container,
|
||||
creditContainer,
|
||||
showRenderLoopErrors,
|
||||
msaa,
|
||||
}) {
|
||||
if (!container || !creditContainer)
|
||||
throw new TypeError('Viewer and credit containers are required');
|
||||
const viewer = new Cesium.Viewer(
|
||||
container,
|
||||
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
|
||||
applicationViewerOptions(creditContainer, {
|
||||
showRenderLoopErrors,
|
||||
msaa,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
// Until the frame port takes over (appRenderer.js), tick at the idle
|
||||
|
||||
@@ -74,3 +74,15 @@ test('flat maps keep zooming out unlimited', () => {
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, Infinity);
|
||||
});
|
||||
|
||||
test('the viewer options take multisampling, by default 4, and keep the drawing buffer', async () => {
|
||||
const { applicationViewerOptions } = await import('./applicationViewer.js');
|
||||
const credits = {};
|
||||
const plain = applicationViewerOptions(credits);
|
||||
assert.equal(plain.msaaSamples, 4);
|
||||
assert.equal(plain.contextOptions.webgl.preserveDrawingBuffer, true);
|
||||
const given = applicationViewerOptions(credits, { msaa: 0 });
|
||||
assert.equal(given.msaaSamples, 1, 'Cesium’s 1 is off');
|
||||
assert.equal(given.contextOptions.webgl.preserveDrawingBuffer, true);
|
||||
assert.equal(applicationViewerOptions(credits, { msaa: 8 }).msaaSamples, 8);
|
||||
});
|
||||
+130
-44
@@ -79,20 +79,31 @@ function matrixArray(matrix) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether `array` holds a Cesium matrix's 16 values, each the same. */
|
||||
function sameMatrix(array, matrix) {
|
||||
for (let i = 0; i < 16; i++)
|
||||
if (!Object.is(array[i], matrix[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{scene: object, camera: object, report: (error: unknown) => void,
|
||||
* widget?: object, capabilities?: ReadonlySet<string>,
|
||||
* now?: () => number, itemPosition?: Function}} options `scene`
|
||||
* gives `requestRender` and the `postUpdate` tick `changed` is measured
|
||||
* on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
|
||||
* gives `requestRender`, the `preUpdate` a frame drawn without the
|
||||
* clock's tick measures `changed` at, and the `postUpdate` move detection
|
||||
* runs on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
|
||||
* `follow` runs on (without it the camera cannot follow);
|
||||
* `capabilities`, the renderer's, gates the optional members (a camera
|
||||
* with none given has them all); `now`, the clock moveEnd waits by,
|
||||
* ms (`performance.now` by default); `itemPosition`, where the draw port
|
||||
* draws an item at a scene time, which a follow of a drawn item tracks.
|
||||
* @returns {{port: import('../contract/camera').CameraPort,
|
||||
* emit: (event: string) => void, dispose: () => void}} `emit` raises
|
||||
* one of the port's events (a test's fake camera that raises its own).
|
||||
* measureChanged: () => void, emit: (event: string) => void,
|
||||
* dispose: () => void}} `measureChanged` measures this frame's `changed`
|
||||
* if nothing has yet, for a frame loop to run before its own `preUpdate`
|
||||
* listeners; `emit` raises one of the port's events (a test's fake camera
|
||||
* that raises its own).
|
||||
*/
|
||||
export function createCesiumCamera({
|
||||
scene,
|
||||
@@ -105,42 +116,92 @@ export function createCesiumCamera({
|
||||
}) {
|
||||
const removers = [];
|
||||
let lastWorld = null;
|
||||
let lastMatrices = null;
|
||||
let lastFollowFrame = null;
|
||||
// Camera events, measured on every tick: moveStart and moveEnd (500 ms
|
||||
// after the last change of the eye or its field of view, by `now`,
|
||||
// following or not, as Cesium's own), and `changed` per listener, where Cesium measures its
|
||||
// single threshold (`camera.percentageChanged`, which this leaves as it
|
||||
// is for everyone else listening to Cesium's own event). Cesium's own
|
||||
// moveStart and moveEnd are left out: it times them by the system clock.
|
||||
// What the events read Cesium's camera through while it stands: the
|
||||
// camera's own vectors, compared in place.
|
||||
const eye = { position: null, direction: null, up: null };
|
||||
const cameraEvents = createCameraEvents({
|
||||
pose: () => cameraPort.pose(),
|
||||
// The memoised pose itself: the events only read it.
|
||||
pose: () => sharedPose(),
|
||||
world: () => {
|
||||
// Copies (Cesium updates its own vectors in place), and the last one
|
||||
// again while Cesium's stand within rounding of it.
|
||||
// The last view again while Cesium's vectors stand within rounding of
|
||||
// it; copies once they move (Cesium updates its own in place).
|
||||
const f = camera.frustum;
|
||||
const current = {
|
||||
position: Cesium.Cartesian3.clone(camera.positionWC),
|
||||
direction: Cesium.Cartesian3.clone(camera.directionWC),
|
||||
up: Cesium.Cartesian3.clone(camera.upWC),
|
||||
eye.position = camera.positionWC;
|
||||
eye.direction = camera.directionWC;
|
||||
eye.up = camera.upWC;
|
||||
if (
|
||||
lastWorld &&
|
||||
// A new field of view or aspect (a resize) is a move too, as
|
||||
// Cesium's own camera events count it.
|
||||
Object.is(lastWorld.fovy, f.fovy) &&
|
||||
Object.is(lastWorld.aspectRatio, f.aspectRatio) &&
|
||||
sameEye(eye, lastWorld)
|
||||
)
|
||||
return lastWorld;
|
||||
lastWorld = {
|
||||
position: Cesium.Cartesian3.clone(eye.position),
|
||||
direction: Cesium.Cartesian3.clone(eye.direction),
|
||||
up: Cesium.Cartesian3.clone(eye.up),
|
||||
fovy: f.fovy,
|
||||
aspectRatio: f.aspectRatio,
|
||||
lens: `${f.fovy} ${f.aspectRatio}`,
|
||||
};
|
||||
if (
|
||||
!lastWorld ||
|
||||
current.lens !== lastWorld.lens ||
|
||||
!sameEye(current, lastWorld)
|
||||
)
|
||||
lastWorld = current;
|
||||
return lastWorld;
|
||||
},
|
||||
report,
|
||||
thresholds: capabilities?.has('cameraChangeThreshold') ?? true,
|
||||
});
|
||||
// `changed` is measured once a frame where the contract's frame order
|
||||
// puts it: after the flight and input (Cesium's `initializeFrame`), before
|
||||
// follow and `preUpdate` move the camera. Cesium moves a followed target's
|
||||
// camera in its clock's tick, so a frame of the loop is measured as that
|
||||
// tick starts; a frame drawn with no tick (a forced render), as
|
||||
// `preUpdate` starts. Move detection runs after `preUpdate`.
|
||||
let measured = false;
|
||||
const measureChanged = () => {
|
||||
if (measured) return;
|
||||
measured = true;
|
||||
applyFov();
|
||||
cameraEvents.stepChanged();
|
||||
};
|
||||
const clock = widget?.clock;
|
||||
if (typeof clock?.tick === 'function') {
|
||||
const ownTick = clock.tick;
|
||||
let wrapping = true;
|
||||
const tick = function (...args) {
|
||||
if (wrapping) {
|
||||
measured = false;
|
||||
measureChanged();
|
||||
}
|
||||
return ownTick.apply(this, args);
|
||||
};
|
||||
clock.tick = tick;
|
||||
// Disposed, the clock gets its own tick back; if something has wrapped
|
||||
// it since, that wrapper stays and this part of it only passes through.
|
||||
removers.push(() => {
|
||||
wrapping = false;
|
||||
if (clock.tick !== tick) return;
|
||||
if (Object.getPrototypeOf(clock)?.tick === ownTick) delete clock.tick;
|
||||
else clock.tick = ownTick;
|
||||
});
|
||||
}
|
||||
const offPreUpdate = scene.preUpdate?.addEventListener(measureChanged);
|
||||
if (offPreUpdate) removers.push(offPreUpdate);
|
||||
removers.push(
|
||||
scene.postUpdate.addEventListener(() => {
|
||||
applyFov();
|
||||
cameraEvents.stepChanged();
|
||||
// Measured already, unless the scene has no `preUpdate`.
|
||||
measureChanged();
|
||||
cameraEvents.stepMoveDetection(now());
|
||||
measured = false;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -413,10 +474,19 @@ export function createCesiumCamera({
|
||||
// The scene's own frame: ECEF in 3D, the only mode the app runs (Cesium's
|
||||
// 2D and Columbus view frames are projected map coordinates).
|
||||
matrices() {
|
||||
return {
|
||||
view: matrixArray(camera.viewMatrix),
|
||||
projection: matrixArray(camera.frustum.projectionMatrix),
|
||||
};
|
||||
// The last ones again while Cesium's stand, new ones once they move.
|
||||
const view = camera.viewMatrix;
|
||||
const projection = camera.frustum.projectionMatrix;
|
||||
if (
|
||||
!lastMatrices ||
|
||||
!sameMatrix(lastMatrices.view, view) ||
|
||||
!sameMatrix(lastMatrices.projection, projection)
|
||||
)
|
||||
lastMatrices = {
|
||||
view: matrixArray(view),
|
||||
projection: matrixArray(projection),
|
||||
};
|
||||
return lastMatrices;
|
||||
},
|
||||
// Cesium's own corner picks (`computeViewRectangle`), on rays that
|
||||
// keep their precision (`pickRayAt`).
|
||||
@@ -442,18 +512,24 @@ export function createCesiumCamera({
|
||||
);
|
||||
},
|
||||
pose() {
|
||||
// An unmoved camera answers from the pose last read: a frame reads
|
||||
// the pose many times over. Each caller gets objects of its own.
|
||||
if (!poseKeyHolds() || !poseMemo) {
|
||||
poseMemo = readPose();
|
||||
// Outside 3D, Cesium measures heading, pitch and roll by moving the
|
||||
// camera into the eye's frame and back, which can change its last
|
||||
// bits: keyed as it is left.
|
||||
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
|
||||
}
|
||||
return copyPose(poseMemo);
|
||||
// Each caller gets objects of its own.
|
||||
return copyPose(sharedPose());
|
||||
},
|
||||
};
|
||||
/**
|
||||
* The pose, read again only when the camera has moved: a frame reads the
|
||||
* pose many times over. Shared: never changed once read.
|
||||
*/
|
||||
function sharedPose() {
|
||||
if (!poseKeyHolds() || !poseMemo) {
|
||||
poseMemo = readPose();
|
||||
// Outside 3D, Cesium measures heading, pitch and roll by moving the
|
||||
// camera into the eye's frame and back, which can change its last
|
||||
// bits: keyed as it is left.
|
||||
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
|
||||
}
|
||||
return poseMemo;
|
||||
}
|
||||
// The camera as the memoised pose was read: eye, axes, transform,
|
||||
// frustum and mode, compared value for value.
|
||||
const poseKey = new Float64Array(37);
|
||||
@@ -469,15 +545,8 @@ export function createCesiumCamera({
|
||||
const r = camera.rightWC;
|
||||
const f = camera.frustum;
|
||||
const t = camera.transform;
|
||||
let same = true;
|
||||
let at = 0;
|
||||
const put = (value) => {
|
||||
if (!Object.is(poseKey[at], value)) {
|
||||
same = false;
|
||||
poseKey[at] = value;
|
||||
}
|
||||
at += 1;
|
||||
};
|
||||
keySame = true;
|
||||
keyAt = 0;
|
||||
put(p.x);
|
||||
put(p.y);
|
||||
put(p.z);
|
||||
@@ -502,7 +571,17 @@ export function createCesiumCamera({
|
||||
put(f.bottom ?? NaN);
|
||||
put(scene.mode ?? NaN);
|
||||
for (let i = 0; i < 16; i++) put(t[i]);
|
||||
return same;
|
||||
return keySame;
|
||||
}
|
||||
// Where `poseKeyHolds` writes next, and whether all it wrote held.
|
||||
let keyAt = 0;
|
||||
let keySame = true;
|
||||
function put(value) {
|
||||
if (!Object.is(poseKey[keyAt], value)) {
|
||||
keySame = false;
|
||||
poseKey[keyAt] = value;
|
||||
}
|
||||
keyAt += 1;
|
||||
}
|
||||
const enuScratch = new Cesium.Matrix4();
|
||||
/**
|
||||
@@ -591,10 +670,15 @@ export function createCesiumCamera({
|
||||
// Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a
|
||||
// `lookAt` target's, or the identity.
|
||||
if (!capabilities || capabilities.has('followFrame'))
|
||||
cameraPort.followFrame = () => matrixArray(camera.transform);
|
||||
cameraPort.followFrame = () => {
|
||||
if (!lastFollowFrame || !sameMatrix(lastFollowFrame, camera.transform))
|
||||
lastFollowFrame = matrixArray(camera.transform);
|
||||
return lastFollowFrame;
|
||||
};
|
||||
|
||||
return {
|
||||
port: cameraPort,
|
||||
measureChanged,
|
||||
emit: (event) => cameraEvents.emit(event),
|
||||
dispose() {
|
||||
following?.dispose();
|
||||
@@ -607,7 +691,9 @@ export function createCesiumCamera({
|
||||
}
|
||||
|
||||
// A Cesium viewer with no renderer bound to it gets a
|
||||
// camera port over its camera when code first asks `cameraOf` for one.
|
||||
// camera port over its camera when code first asks `cameraOf` for one. The
|
||||
// port wraps the viewer's `clock.tick` to measure `changed`, and gives it
|
||||
// back when a renderer is bound to the viewer.
|
||||
provideUnboundCamera((viewer) =>
|
||||
// By shape, not `instanceof`: the viewer may come from another
|
||||
// copy of Cesium.
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from './cameraGoldens.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumPorts } from './ports.js';
|
||||
import { cameraOf } from '../rendererOf.js';
|
||||
import { bindRenderer, cameraOf } from '../rendererOf.js';
|
||||
|
||||
/** Records the headless scene cannot answer: they need the query port. */
|
||||
const QUERY_RECORDS = new Set([
|
||||
@@ -78,6 +78,7 @@ function headlessHarness(clock, { input = false } = {}) {
|
||||
clock.now += FRAME_MS;
|
||||
scene.tweens.update();
|
||||
if (input) scene.screenSpaceCameraController.update();
|
||||
scene.preUpdate.raiseEvent(scene);
|
||||
scene.postUpdate.raiseEvent(scene);
|
||||
},
|
||||
scene,
|
||||
@@ -287,6 +288,55 @@ test('a Cesium viewer with no renderer bound gets a camera port over its own cam
|
||||
});
|
||||
});
|
||||
|
||||
test('the camera port gives the clock its own tick back as it goes', () => {
|
||||
const ownTick = Cesium.Clock.prototype.tick;
|
||||
// A viewer with no renderer bound: its port goes when a renderer is bound.
|
||||
{
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
scene.requestRender = () => {};
|
||||
const viewer = { scene, camera, clock: new Cesium.Clock() };
|
||||
cameraOf(viewer);
|
||||
assert.notEqual(viewer.clock.tick, ownTick, 'measured as the tick starts');
|
||||
bindRenderer(viewer, {});
|
||||
assert.equal(viewer.clock.tick, ownTick, 'its own tick once unbound');
|
||||
assert.equal(Object.hasOwn(viewer.clock, 'tick'), false);
|
||||
}
|
||||
// Wrapped again after the port: disposing leaves the later wrapper, and
|
||||
// the port's own part of the tick measures nothing more.
|
||||
{
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
scene.requestRender = () => {};
|
||||
const clock = new Cesium.Clock();
|
||||
const part = createCesiumCamera({
|
||||
scene,
|
||||
camera,
|
||||
report: () => {},
|
||||
widget: { clock },
|
||||
});
|
||||
const wrapped = clock.tick;
|
||||
let later = 0;
|
||||
clock.tick = function (...args) {
|
||||
later += 1;
|
||||
return wrapped.apply(this, args);
|
||||
};
|
||||
part.dispose();
|
||||
let reads = 0;
|
||||
const frustum = camera.frustum;
|
||||
Object.defineProperty(camera, 'frustum', {
|
||||
get: () => {
|
||||
reads += 1;
|
||||
return frustum;
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
clock.tick();
|
||||
assert.equal(later, 1, 'the later wrapper still runs');
|
||||
assert.equal(reads, 0, 'the disposed port reads nothing');
|
||||
}
|
||||
});
|
||||
|
||||
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
|
||||
@@ -14,22 +14,24 @@ import * as Cesium from 'cesium';
|
||||
* @param {(error: unknown) => void} onThrow
|
||||
*/
|
||||
export function listenerList(onThrow) {
|
||||
const entries = [];
|
||||
// Copied on change, not on delivery: a delivery runs over the list as it
|
||||
// stood, and a change made during it makes a new one.
|
||||
let entries = [];
|
||||
return {
|
||||
get size() {
|
||||
return entries.length;
|
||||
},
|
||||
on(cb) {
|
||||
const entry = { cb, live: true };
|
||||
entries.push(entry);
|
||||
entries = [...entries, entry];
|
||||
return () => {
|
||||
if (!entry.live) return;
|
||||
entry.live = false;
|
||||
const i = entries.indexOf(entry);
|
||||
if (i >= 0) entries.splice(i, 1);
|
||||
entries = entries.filter((e) => e !== entry);
|
||||
};
|
||||
},
|
||||
fire(...args) {
|
||||
for (const entry of entries.slice()) {
|
||||
for (const entry of entries) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb(...args);
|
||||
@@ -40,7 +42,7 @@ export function listenerList(onThrow) {
|
||||
},
|
||||
clear() {
|
||||
for (const entry of entries) entry.live = false;
|
||||
entries.length = 0;
|
||||
entries = [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ const plain = (v) => ({ x: v.x, y: v.y, z: v.z });
|
||||
/**
|
||||
* @param {{
|
||||
* scene: object,
|
||||
* controller: Function,
|
||||
* controller: import('../contract/camera').CameraControllerFactory,
|
||||
* query: {pickPosition?: Function, sampleHeightNow?: Function},
|
||||
* itemPosition?: (item: {set: string, id: string|number}, aheadMs?: number) => object|null,
|
||||
* requestRender: (reason: string) => void,
|
||||
|
||||
@@ -207,23 +207,8 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
|
||||
const { statics, screen, lightbox, logo } = creditDisplayContents(
|
||||
displayLive() ? display : undefined,
|
||||
);
|
||||
let same = true;
|
||||
let at = 0;
|
||||
const put = (value) => {
|
||||
if (!Object.is(lastInputs[at], value)) {
|
||||
same = false;
|
||||
lastInputs[at] = value;
|
||||
}
|
||||
at += 1;
|
||||
};
|
||||
const putElements = (elements) => {
|
||||
put(elements.length);
|
||||
for (const element of elements) {
|
||||
put(element.credit);
|
||||
put(element.count);
|
||||
put(element.credit?.showOnScreen);
|
||||
}
|
||||
};
|
||||
inputsSame = true;
|
||||
inputAt = 0;
|
||||
put(coreVersion);
|
||||
put(logo);
|
||||
put(logo?.showOnScreen);
|
||||
@@ -234,7 +219,25 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
|
||||
}
|
||||
putElements(screen);
|
||||
putElements(lightbox);
|
||||
return same;
|
||||
return inputsSame;
|
||||
}
|
||||
// Where `inputsHeld` writes next, and whether all it wrote held.
|
||||
let inputAt = 0;
|
||||
let inputsSame = true;
|
||||
function put(value) {
|
||||
if (!Object.is(lastInputs[inputAt], value)) {
|
||||
inputsSame = false;
|
||||
lastInputs[inputAt] = value;
|
||||
}
|
||||
inputAt += 1;
|
||||
}
|
||||
function putElements(elements) {
|
||||
put(elements.length);
|
||||
for (const element of elements) {
|
||||
put(element.credit);
|
||||
put(element.count);
|
||||
put(element.credit?.showOnScreen);
|
||||
}
|
||||
}
|
||||
inputsHeld();
|
||||
|
||||
|
||||
+158
-47
@@ -24,7 +24,7 @@
|
||||
* settle into static batches that cost nothing until they change, and a
|
||||
* line that moves again goes back to the collection (`settleLines`).
|
||||
*
|
||||
* Icon sets whose items move, glide, recede, pick by proxy or switch images
|
||||
* Icon sets that recede, or whose items move, glide, pick by proxy or switch images
|
||||
* by size, or that take columns, draw on the GPU instead (`gpuIcons.js`).
|
||||
*
|
||||
* Built over a scene by `createCesiumPorts`, and on its own over a Cesium
|
||||
@@ -441,6 +441,9 @@ const ICONS_KEPT = 'kept';
|
||||
const POINTS_ADDED = 'added';
|
||||
const POINTS_KEPT = 'kept';
|
||||
|
||||
/** Whether a set's GPU icons move on in the frames that follow. */
|
||||
const animating = (record) => record.gpu?.animating();
|
||||
|
||||
/**
|
||||
* The draw port over `scene`, and what the other ports read of it: the live
|
||||
* sets by id, a version that changes with what height queries see through
|
||||
@@ -448,17 +451,20 @@ const POINTS_KEPT = 'kept';
|
||||
* the clamp-state watch the frame loop runs after each draw.
|
||||
* @param {{scene: object, report: (error: unknown) => void,
|
||||
* capabilities?: ReadonlySet<string>,
|
||||
* requestRender?: (reason: string) => void}} options `capabilities` gate
|
||||
* requestRender?: (reason: string) => void,
|
||||
* date?: () => number}} options `capabilities` gate
|
||||
* the GPU icon sets' members (by default they all are); `requestRender`,
|
||||
* the frame port's, asks for the frames a GPU icon set needs on its own
|
||||
* (its images packed), under the reason `icons:<set id>` (by default the
|
||||
* scene's, with no reason).
|
||||
* scene's, with no reason); `date`, the epoch ms a `live` motion clock
|
||||
* reads (by default the system clock's).
|
||||
*/
|
||||
export function createCesiumDraw({
|
||||
scene,
|
||||
report,
|
||||
capabilities = new Set(GPU_ICON_CAPABILITIES),
|
||||
requestRender: requestFrame = null,
|
||||
date = null,
|
||||
}) {
|
||||
const sets = new Map();
|
||||
// Fields share the sets' ids.
|
||||
@@ -481,6 +487,15 @@ export function createCesiumDraw({
|
||||
const requestRender = () => {
|
||||
if (live()) scene.requestRender();
|
||||
};
|
||||
// Once the port is disposed (its renderer destroyed), every set does
|
||||
// nothing, and so does a set asked for after that.
|
||||
let portDisposed = false;
|
||||
|
||||
/** A disposed set's listeners hear nothing more, even mid-delivery. */
|
||||
function silence(record) {
|
||||
record.listeners.ready.clear();
|
||||
record.listeners.loadFailed.clear();
|
||||
}
|
||||
|
||||
function makeSet(kind, spec, build) {
|
||||
if (sets.has(spec.id) || fieldPart.has(spec.id))
|
||||
@@ -569,6 +584,9 @@ export function createCesiumDraw({
|
||||
record.gpu.write(list);
|
||||
return patched();
|
||||
}
|
||||
// Icons drawn already, with the images they are drawn with, each
|
||||
// changed where it is.
|
||||
if (patchDrawnIcons(record, list)) return iconsPatched(ICONS_KEPT);
|
||||
// Points restyled, moved or added keep the pick ids they had, so
|
||||
// only points added change what height queries see through.
|
||||
const points = patchPoints(record, list);
|
||||
@@ -578,13 +596,22 @@ export function createCesiumDraw({
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
// Models are changed where they are; moved or restyled they keep
|
||||
// their pick ids, so only models added change what height queries
|
||||
// see through.
|
||||
if (kind === 'models') {
|
||||
const added = modelSets.upsert(record, list);
|
||||
for (const item of list) items.set(item.id, item);
|
||||
if (added) setsVersion += 1;
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
// Lines that only change how they show or where an undraped one
|
||||
// runs, and clamped shapes that only show or hide, or a few colour
|
||||
// fills that only move (`moveShape`), are changed where they are.
|
||||
if (
|
||||
patchLines(record, list) ||
|
||||
patchShapes(record, list) ||
|
||||
(kind === 'models' && modelSets.upsert(record, list)) ||
|
||||
(kind === 'quads' && quadSets.upsert(record, list)) ||
|
||||
(kind === 'meshes' && meshSets.upsert(record, list))
|
||||
) {
|
||||
@@ -639,8 +666,12 @@ export function createCesiumDraw({
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
// Refused, changing nothing, where icons on the GPU cannot take it.
|
||||
// Refused, changing nothing, where icons on the GPU cannot take it
|
||||
// (all of them, for billboards told to recede, which go onto it).
|
||||
const toGpu =
|
||||
kind === 'icons' && !record.gpu && Boolean(options.recede);
|
||||
if (record.gpu) gpu.check([], { ...spec, ...options });
|
||||
else if (toGpu) gpu.check(items.values(), { ...spec, ...options });
|
||||
const culled = spec.horizonCull;
|
||||
const clampTo = spec.clampTo;
|
||||
const blend = spec.blend;
|
||||
@@ -666,6 +697,10 @@ export function createCesiumDraw({
|
||||
// A set that stops picking lets its old ground go now: still drawn
|
||||
// while the new builds, it would keep hiding the ground from picks.
|
||||
if (pickable && spec.pickable === false) retire(record);
|
||||
if (toGpu) {
|
||||
onGpu(record, [], true, true);
|
||||
record.gpu.sync();
|
||||
}
|
||||
record.gpu?.restyle();
|
||||
if (kind === 'models') modelSets.restyle(record);
|
||||
setsVersion += 1;
|
||||
@@ -784,6 +819,42 @@ export function createCesiumDraw({
|
||||
handle.upsert([...record.inertialDraped.values()]);
|
||||
};
|
||||
}
|
||||
// A disposed set does nothing on later calls: one would draw what
|
||||
// nothing removes.
|
||||
record.disposed = portDisposed;
|
||||
for (const name of [
|
||||
'set',
|
||||
'upsert',
|
||||
'remove',
|
||||
'clear',
|
||||
'setOptions',
|
||||
'setColumns',
|
||||
]) {
|
||||
const call = handle[name];
|
||||
if (!call) continue;
|
||||
handle[name] = (...args) => {
|
||||
if (!record.disposed) return call(...args);
|
||||
};
|
||||
}
|
||||
const { set: showSet } = Object.getOwnPropertyDescriptor(handle, 'show');
|
||||
Object.defineProperty(handle, 'show', {
|
||||
get: () => spec.show !== false,
|
||||
set(value) {
|
||||
if (!record.disposed) showSet.call(handle, value);
|
||||
},
|
||||
enumerable: true,
|
||||
});
|
||||
const on = handle.on;
|
||||
handle.on = (event, cb) => (record.disposed ? () => {} : on(event, cb));
|
||||
const disposeOnce = handle.dispose;
|
||||
handle.dispose = () => {
|
||||
if (record.disposed) return;
|
||||
record.disposed = true;
|
||||
// A listener that disposes the set stops the rest of that delivery.
|
||||
silence(record);
|
||||
disposeOnce();
|
||||
};
|
||||
if (record.disposed) return handle;
|
||||
sets.set(spec.id, record);
|
||||
setsVersion += 1;
|
||||
return handle;
|
||||
@@ -792,6 +863,7 @@ export function createCesiumDraw({
|
||||
const gpu = createGpuIcons({
|
||||
scene,
|
||||
capabilities,
|
||||
date,
|
||||
toColor,
|
||||
imageOf: (record, image) => iconImage(record, image),
|
||||
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
|
||||
@@ -811,7 +883,7 @@ export function createCesiumDraw({
|
||||
*/
|
||||
function onGpu(record, list, replacing = false, force = false) {
|
||||
if (record.kind !== 'icons') return false;
|
||||
if (!record.gpu && !force && !gpu.wants(list)) return false;
|
||||
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
|
||||
gpu.check(list, record.spec);
|
||||
if (record.gpu) return true;
|
||||
if (!replacing) gpu.check(record.items.values(), record.spec);
|
||||
@@ -1073,11 +1145,6 @@ export function createCesiumDraw({
|
||||
*/
|
||||
function clusterIcons(frameState = scene.frameState) {
|
||||
let pose;
|
||||
const poseNow = () => {
|
||||
const eye = scene.camera?.positionWC;
|
||||
const dir = scene.camera?.directionWC;
|
||||
return `${eye?.x},${eye?.y},${eye?.z},${dir?.x},${dir?.y},${dir?.z},${scene.canvas?.clientWidth},${scene.canvas?.clientHeight}`;
|
||||
};
|
||||
for (const record of sets.values()) {
|
||||
if (!clusters(record)) {
|
||||
if (record.clusterHost || record.clusterState) {
|
||||
@@ -1095,21 +1162,54 @@ export function createCesiumDraw({
|
||||
record.clusterKey = null;
|
||||
record.clusteredHost = host;
|
||||
}
|
||||
pose ??= poseNow();
|
||||
// Rows still moving on their segments cluster again every frame.
|
||||
const key = record.gpu?.moving(frameState)
|
||||
? `${pose}@${frameState?.frameNumber ?? Math.random()}`
|
||||
: pose;
|
||||
if (record.clusterKey === key) {
|
||||
pose ??= clusterPoseNow();
|
||||
// Rows still moving on their segments cluster again every frame (NaN,
|
||||
// a frame with no number, is never the last).
|
||||
const frameKey = record.gpu?.moving(frameState)
|
||||
? (frameState?.frameNumber ?? NaN)
|
||||
: null;
|
||||
if (record.clusterKey === pose && record.clusterFrame === frameKey) {
|
||||
if (record.clusterHost)
|
||||
record.clusterHost.show = record.spec.show !== false;
|
||||
continue;
|
||||
}
|
||||
record.clusterKey = key;
|
||||
record.clusterKey = pose;
|
||||
record.clusterFrame = frameKey;
|
||||
reclusterIcons(record, frameState);
|
||||
}
|
||||
}
|
||||
|
||||
// The eye and canvas the clusters were last measured at, and a count of
|
||||
// their changes: a set clusters again when the count it clustered at is
|
||||
// not the count now.
|
||||
const clusterPose = new Float64Array(8).fill(NaN);
|
||||
let clusterPoseVersion = 0;
|
||||
let clusterPoseAt = 0;
|
||||
let clusterPoseSame = true;
|
||||
function putClusterPose(value) {
|
||||
if (!Object.is(clusterPose[clusterPoseAt], value)) {
|
||||
clusterPoseSame = false;
|
||||
clusterPose[clusterPoseAt] = value;
|
||||
}
|
||||
clusterPoseAt += 1;
|
||||
}
|
||||
function clusterPoseNow() {
|
||||
const eye = scene.camera?.positionWC;
|
||||
const dir = scene.camera?.directionWC;
|
||||
clusterPoseAt = 0;
|
||||
clusterPoseSame = true;
|
||||
putClusterPose(eye?.x ?? NaN);
|
||||
putClusterPose(eye?.y ?? NaN);
|
||||
putClusterPose(eye?.z ?? NaN);
|
||||
putClusterPose(dir?.x ?? NaN);
|
||||
putClusterPose(dir?.y ?? NaN);
|
||||
putClusterPose(dir?.z ?? NaN);
|
||||
putClusterPose(scene.canvas?.clientWidth ?? NaN);
|
||||
putClusterPose(scene.canvas?.clientHeight ?? NaN);
|
||||
if (!clusterPoseSame) clusterPoseVersion += 1;
|
||||
return clusterPoseVersion;
|
||||
}
|
||||
|
||||
/** The points a GPU set clusters: its shown rows where they are drawn. */
|
||||
function gpuClusterPoints(record, frameState, horizon) {
|
||||
const points = [];
|
||||
@@ -1274,9 +1374,13 @@ export function createCesiumDraw({
|
||||
|
||||
/** Whether a shown set shows flow lines, which draw on in later frames. */
|
||||
const flowing = () =>
|
||||
[...sets.values()].some(
|
||||
(record) => record.spec.show !== false && record.flowShown,
|
||||
);
|
||||
anySet((record) => record.spec.show !== false && record.flowShown);
|
||||
|
||||
/** Whether any set passes `test`, without copying the sets (per frame). */
|
||||
function anySet(test) {
|
||||
for (const record of sets.values()) if (test(record)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Note whether a line set shows any flow line, once its lines change. */
|
||||
function noteFlows(record) {
|
||||
@@ -1621,37 +1725,48 @@ export function createCesiumDraw({
|
||||
}
|
||||
|
||||
/**
|
||||
* `syncIcons`' quick case: every item is drawn, every touched one keeps
|
||||
* the image it is drawn with, and nothing drawn has gone, so each touched
|
||||
* one is changed where it is and nothing is added, removed or reordered.
|
||||
* False, changing nothing, otherwise.
|
||||
* `upsert`'s quick case for an icon set on billboards: every item is
|
||||
* drawn, every one of `list` keeps the image it is drawn with, and
|
||||
* nothing drawn has gone, so each of `list` is changed where it is
|
||||
* (`patchIcon`: only moved, when that is all that changed) and nothing is
|
||||
* added, removed or reordered. Each item is read once: a layer moves its
|
||||
* icons every frame. The items are taken as the set's. False, changing
|
||||
* nothing, otherwise.
|
||||
* @param {object} record
|
||||
* @param {readonly string[]} touched
|
||||
* @param {readonly object[]} list
|
||||
*/
|
||||
function patchDrawnIcons(record, touched) {
|
||||
function patchDrawnIcons(record, list) {
|
||||
const drawn = record.billboards;
|
||||
const host = record.billboardHost;
|
||||
// Nothing to remove: every item drawn, and nothing drawn but items.
|
||||
if (
|
||||
!Array.isArray(touched) ||
|
||||
touched.length === 0 ||
|
||||
record.kind !== 'icons' ||
|
||||
!drawn ||
|
||||
!host ||
|
||||
record.host !== host ||
|
||||
host.isDestroyed() ||
|
||||
list.length === 0 ||
|
||||
drawn.size !== record.items.size
|
||||
)
|
||||
return false;
|
||||
for (const id of touched) {
|
||||
const entry = drawn.get(id);
|
||||
const item = record.items.get(id);
|
||||
if (!entry || !item) return false;
|
||||
const image = iconImage(record, item.image);
|
||||
const entries = new Array(list.length);
|
||||
const images = new Array(list.length);
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const entry = drawn.get(list[i].id);
|
||||
if (!entry) return false;
|
||||
const image = iconImage(record, list[i].image);
|
||||
if (
|
||||
image === undefined ||
|
||||
imageKeyOf(image) !== entry.image ||
|
||||
(isKeyed(image) && image.canvas !== entry.canvas)
|
||||
)
|
||||
return false;
|
||||
entries[i] = entry;
|
||||
images[i] = image;
|
||||
}
|
||||
for (const id of touched) {
|
||||
const item = record.items.get(id);
|
||||
patchIcon(record, drawn.get(id), item, iconImage(record, item.image));
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
record.items.set(list[i].id, list[i]);
|
||||
patchIcon(record, entries[i], list[i], images[i]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1685,7 +1800,6 @@ export function createCesiumDraw({
|
||||
host.isDestroyed()
|
||||
)
|
||||
return false;
|
||||
if (!reordered && patchDrawnIcons(record, touched)) return ICONS_KEPT;
|
||||
const images = new Map();
|
||||
for (const id of touched) {
|
||||
const item = record.items.get(id);
|
||||
@@ -2467,7 +2581,7 @@ export function createCesiumDraw({
|
||||
? Cesium.JulianDate.toDate(
|
||||
scene.frameState?.time ?? Cesium.JulianDate.now(),
|
||||
).getTime()
|
||||
: Date.now() - (clock?.delayMs ?? 0);
|
||||
: (date ? date() : Date.now()) - (clock?.delayMs ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5300,7 +5414,7 @@ export function createCesiumDraw({
|
||||
return record.gpu.drawnAt(ref.id, aheadMs, time ? { time } : undefined);
|
||||
},
|
||||
/** Whether a set's ground primitives are still being built. */
|
||||
building: () => [...sets.values()].some((record) => record.pending),
|
||||
building: () => anySet((record) => record.pending),
|
||||
/** Each frame, before it draws: the horizon cull. */
|
||||
beforeRender() {
|
||||
pulsing = runPulses();
|
||||
@@ -5343,19 +5457,14 @@ export function createCesiumDraw({
|
||||
// Rows moving on a live clock, and flowing lines, draw on in the
|
||||
// frames that follow.
|
||||
const playing = quadSets.afterRender(sets.values());
|
||||
if (
|
||||
[...sets.values()].some((record) => record.gpu?.animating()) ||
|
||||
flowing() ||
|
||||
pulsing ||
|
||||
playing
|
||||
)
|
||||
requestRender();
|
||||
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
|
||||
},
|
||||
/**
|
||||
* Let go of the sets; with `removeHosts`, take what they draw out of
|
||||
* the scene too (a scene the port does not own outlives it).
|
||||
*/
|
||||
dispose({ removeHosts = false } = {}) {
|
||||
portDisposed = true;
|
||||
clampListeners.clear();
|
||||
// Fields go with the port, and their frame listeners with them.
|
||||
fieldPart.dispose();
|
||||
@@ -5366,6 +5475,8 @@ export function createCesiumDraw({
|
||||
retire(record);
|
||||
}
|
||||
record.host = null;
|
||||
record.disposed = true;
|
||||
silence(record);
|
||||
}
|
||||
sets.clear();
|
||||
},
|
||||
|
||||
@@ -4394,6 +4394,22 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del
|
||||
assert.equal(flags & ICON_RECEDES, ICON_RECEDES);
|
||||
assert.equal(flags & ICON_CULL_LIFT, ICON_CULL_LIFT);
|
||||
assert.ok(set.depthTestDistance(row) >= 1e30, 'over depth everywhere');
|
||||
// The set recedes by the aircraft tuning, and follows it when it changes.
|
||||
const recession = await import('../../data/aircraftRecession.js');
|
||||
assert.equal(
|
||||
part.sets.get(setId).spec.recede,
|
||||
recession.aircraftRecedeSpec(),
|
||||
);
|
||||
assert.equal('recede' in part.sets.get(setId).items.get('abc123'), false);
|
||||
try {
|
||||
recession.setAircraftRecessionParams({ scaleFloor: 0.6 });
|
||||
icons._syncRecede();
|
||||
assert.equal(host._recedeParams().scaleFloor, 0.6);
|
||||
} finally {
|
||||
recession.resetAircraftRecessionParams();
|
||||
icons._syncRecede();
|
||||
}
|
||||
assert.equal(host._recedeParams().scaleFloor, 0.45);
|
||||
|
||||
// Drawn where the layer reads it, between its two fixes.
|
||||
const t = Date.now() - delayMs;
|
||||
@@ -6674,7 +6690,7 @@ test('models re-pose and restyle in place; only a new url loads again', async ()
|
||||
Cesium.ColorBlendMode.HIGHLIGHT,
|
||||
'no tint to blend in: its own colour',
|
||||
);
|
||||
assert.equal(model.color.alpha, 1);
|
||||
assert.equal(model.color, undefined, 'and no colour of its own');
|
||||
set.upsert([plane({ show: false })]);
|
||||
assert.equal(model.show, false, 'hidden in place');
|
||||
|
||||
@@ -6911,6 +6927,193 @@ test('a model past its pixel cap is scaled down each frame; fades and culls too'
|
||||
}
|
||||
});
|
||||
|
||||
test('an untinted model drawn fully opaque is given no colour; a fade gives one, and full opacity takes it away again', async () => {
|
||||
// A colour on a Cesium model adds a colour stage to every draw of it.
|
||||
const { loads, restore } = fakeModelLoads();
|
||||
try {
|
||||
const scene = fakeScene();
|
||||
let metresPerPixel = 0.1;
|
||||
scene.camera.getPixelSize = () => metresPerPixel;
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const set = part.port.models({ id: 'm' });
|
||||
const eye = scene.camera.positionWC;
|
||||
const at = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
|
||||
const distance = Cesium.Cartesian3.distance(eye, at);
|
||||
const item = (extra = {}) => ({
|
||||
id: 'a',
|
||||
pos: { lon: 0, lat: 0, height: 1000 },
|
||||
url: 'a.glb',
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
...extra,
|
||||
});
|
||||
set.set([item()]);
|
||||
loads[0].resolve();
|
||||
await settle();
|
||||
const model = loads[0].model;
|
||||
loads[0].ready();
|
||||
part.beforeRender();
|
||||
assert.equal(model.color, undefined, 'opaque, untinted: no colour');
|
||||
set.upsert([
|
||||
item({
|
||||
fadeByDistance: {
|
||||
near: distance - 10,
|
||||
nearValue: 1,
|
||||
far: distance + 10,
|
||||
farValue: 0,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
part.beforeRender();
|
||||
assert.ok(model.color, 'faded: a colour');
|
||||
assert.ok(Math.abs(model.color.alpha - 0.5) < 1e-6, 'faded halfway');
|
||||
set.upsert([item()]);
|
||||
part.beforeRender();
|
||||
assert.equal(model.color, undefined, 'opaque again: no colour');
|
||||
set.dispose();
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('models moved every frame keep their shader and pick ids: only a new look or a new model changes them', async () => {
|
||||
// A fleet re-poses every model each frame with the same look.
|
||||
const { loads, restore } = fakeModelLoads();
|
||||
const toCss = Cesium.Color.prototype.toCssHexString;
|
||||
let shaderLookups = 0;
|
||||
Cesium.Color.prototype.toCssHexString = function () {
|
||||
shaderLookups += 1;
|
||||
return toCss.call(this);
|
||||
};
|
||||
try {
|
||||
const scene = fakeScene();
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const set = part.port.models({ id: 'fleet' });
|
||||
const item = (id, lon, extra = {}) => ({
|
||||
id,
|
||||
pos: { lon, lat: 0, height: 10 },
|
||||
url: 'a.glb',
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
maskColor: '#ff8800',
|
||||
...extra,
|
||||
});
|
||||
set.set([item('a', 0), item('b', 1)]);
|
||||
for (const load of loads) load.resolve();
|
||||
await settle();
|
||||
for (const load of loads) load.ready();
|
||||
const [a, b] = loads.map((load) => load.model);
|
||||
const shader = a.customShader;
|
||||
assert.ok(shader instanceof Cesium.CustomShader, 'the mask shader');
|
||||
const version = part.version();
|
||||
shaderLookups = 0;
|
||||
for (let frame = 1; frame <= 5; frame++) {
|
||||
set.upsert([item('a', frame * 1e-5), item('b', 1 + frame * 1e-5)]);
|
||||
part.beforeRender();
|
||||
}
|
||||
const moved = Cesium.Matrix4.getTranslation(
|
||||
a.modelMatrix,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(
|
||||
moved,
|
||||
Cesium.Cartesian3.fromDegrees(5e-5, 0, 10),
|
||||
) < 1e-6,
|
||||
'moved',
|
||||
);
|
||||
assert.equal(a.customShader, shader, 'the same shader');
|
||||
assert.equal(shaderLookups, 0, 'not looked up again');
|
||||
assert.equal(part.version(), version, 'no pick id added or gone');
|
||||
|
||||
// A new mask colour, a new shading and the mask again: each drawn.
|
||||
set.upsert([item('a', 0, { maskColor: '#0000ff' })]);
|
||||
assert.notEqual(a.customShader, shader, 'a new colour, a new shader');
|
||||
assert.equal(b.customShader, shader, 'the other keeps its own');
|
||||
set.upsert([item('a', 0, { maskColor: '#0000ff', shading: 'thermal' })]);
|
||||
const thermal = a.customShader;
|
||||
assert.ok(thermal instanceof Cesium.CustomShader);
|
||||
assert.notEqual(thermal, shader);
|
||||
set.upsert([item('a', 0)]);
|
||||
assert.equal(a.customShader, shader, 'its mask again');
|
||||
set.upsert([item('a', 0, { maskColor: undefined })]);
|
||||
assert.equal(a.customShader, undefined, 'no mask: lit as it is');
|
||||
|
||||
// A model added changes what height queries see through.
|
||||
set.upsert([item('c', 2)]);
|
||||
assert.notEqual(part.version(), version, 'a pick id added');
|
||||
set.dispose();
|
||||
} finally {
|
||||
Cesium.Color.prototype.toCssHexString = toCss;
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a model set that recedes fades its models toward the limb with their focus; focus alone dims', async () => {
|
||||
const { recedeFactors, recedeFrame, recedeParams, recededAlpha } =
|
||||
await import('../recession.js');
|
||||
const { loads, restore } = fakeModelLoads();
|
||||
try {
|
||||
const scene = fakeScene();
|
||||
const heightM = 1_000_000;
|
||||
scene.camera.positionWC = new Cesium.Cartesian3(6_378_137 + heightM, 0, 0);
|
||||
scene.camera.positionCartographic = { height: heightM };
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const set = part.port.models({ id: 'm', recede: {} });
|
||||
const item = (extra = {}) => ({
|
||||
id: 'a',
|
||||
pos: { lon: 25, lat: 0, height: 0 },
|
||||
url: 'a.glb',
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
tint: [1, 0, 0, 0.8],
|
||||
focus: 0.5,
|
||||
...extra,
|
||||
});
|
||||
set.set([item()]);
|
||||
loads[0].resolve();
|
||||
await settle();
|
||||
const model = loads[0].model;
|
||||
loads[0].ready();
|
||||
part.beforeRender();
|
||||
const params = recedeParams({});
|
||||
const d = Cesium.Cartesian3.distance(
|
||||
scene.camera.positionWC,
|
||||
Cesium.Cartesian3.fromDegrees(25, 0, 0),
|
||||
);
|
||||
const haze = recedeFactors(d, recedeFrame(heightM, params), params).alpha;
|
||||
assert.ok(haze < 0.9, `receding: ${haze}`);
|
||||
const want = 0.8 * recededAlpha(0.5, haze, params);
|
||||
assert.ok(
|
||||
Math.abs(model.color.alpha - want) < 1e-6,
|
||||
`${model.color.alpha} vs ${want}`,
|
||||
);
|
||||
assert.equal(model.color.red, 1, 'the tint kept');
|
||||
// Not receding: the tint's alpha times the focus.
|
||||
set.setOptions({ recede: null });
|
||||
part.beforeRender();
|
||||
assert.ok(Math.abs(model.color.alpha - 0.4) < 1e-6, `${model.color.alpha}`);
|
||||
set.upsert([item({ focus: undefined })]);
|
||||
part.beforeRender();
|
||||
assert.ok(Math.abs(model.color.alpha - 0.8) < 1e-6);
|
||||
// Receding again, over the blend band: only the combined floor holds.
|
||||
set.setOptions({ recede: {} });
|
||||
scene.camera.positionCartographic = { height: 9_000_000 };
|
||||
set.upsert([item({ focus: 0.1 })]);
|
||||
part.beforeRender();
|
||||
assert.ok(Math.abs(model.color.alpha - 0.8 * 0.2) < 1e-6);
|
||||
set.dispose();
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a raised polygon outlines its holes as well as its outer ring', () =>
|
||||
withImageClasses(() => {
|
||||
const { scene, draw } = drawOver();
|
||||
@@ -7894,6 +8097,70 @@ test('icons that only move are moved on the billboards they have, and still rest
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('icons moved every frame are each read once, and a new image or a new icon still draws', () => {
|
||||
const scene = fakeScene();
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const set = part.port.icons({ id: 'icons:fleet' });
|
||||
// Reads of each item's image: what a moved icon is drawn with is
|
||||
// looked up once an update.
|
||||
let imageReads = 0;
|
||||
const icon = (id, lon) => {
|
||||
let image = 'a.png';
|
||||
return {
|
||||
id,
|
||||
pos: { ...Cesium.Cartesian3.fromDegrees(lon, 10) },
|
||||
get image() {
|
||||
imageReads += 1;
|
||||
return image;
|
||||
},
|
||||
set image(value) {
|
||||
image = value;
|
||||
},
|
||||
size: [20, 20],
|
||||
color: '#33ccff',
|
||||
rotationMode: 'screen',
|
||||
rotation: 0,
|
||||
disableDepthTest: Infinity,
|
||||
meta: { id },
|
||||
};
|
||||
};
|
||||
const items = [icon('a', 0), icon('b', 1), icon('c', 2)];
|
||||
set.set(items);
|
||||
const [host] = scene.added;
|
||||
const billboards = [0, 1, 2].map((i) => host.get(i));
|
||||
const version = part.version();
|
||||
imageReads = 0;
|
||||
for (let frame = 1; frame <= 4; frame++) {
|
||||
for (const item of items) item.pos.x += 1;
|
||||
set.upsert(items);
|
||||
}
|
||||
assert.equal(imageReads, 4 * items.length, 'each image read once a frame');
|
||||
assert.equal(scene.added[0], host, 'the same collection');
|
||||
billboards.forEach((billboard, i) => {
|
||||
assert.equal(host.get(i), billboard, 'the same billboards');
|
||||
assert.equal(billboard.position.x, items[i].pos.x, 'moved');
|
||||
});
|
||||
assert.equal(part.version(), version, 'nothing added or removed');
|
||||
|
||||
// Only some moved: the others stay where they are.
|
||||
items[1].pos.x += 1;
|
||||
set.upsert([items[1]]);
|
||||
assert.equal(billboards[1].position.x, items[1].pos.x);
|
||||
// A new image is drawn on the billboard it has.
|
||||
items[0].image = 'b.png';
|
||||
set.upsert(items);
|
||||
assert.equal(host.get(0), billboards[0], 'the same billboard');
|
||||
assert.equal(billboards[0].image, 'b.png');
|
||||
// An icon added joins after the others.
|
||||
set.upsert([...items, icon('d', 3)]);
|
||||
assert.equal(host.length, 4);
|
||||
assert.notEqual(part.version(), version, 'an icon added');
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('the transit layer draws its vehicles as two icon sets, moving a marker between them, on a viewer of its own', async () => {
|
||||
const { createRendering } = await import('../../layers/transit/rendering.js');
|
||||
const { createState } = await import('../../layers/transit/state.js');
|
||||
@@ -8361,3 +8628,139 @@ test('a quad that moves from a blob to a URL lets the blob go once its old mater
|
||||
names.forEach((name, i) => (globalThis[name] = real[i]));
|
||||
}
|
||||
});
|
||||
|
||||
test('a set disposed by one of its listeners tells the later ones nothing more', async () => {
|
||||
const { loads, restore } = fakeModelLoads();
|
||||
try {
|
||||
const plane = (id) => ({
|
||||
id,
|
||||
pos: { lon: 0, lat: 0, height: 10 },
|
||||
url: 'a.glb',
|
||||
});
|
||||
const loaded = async (load) => {
|
||||
load.resolve();
|
||||
await settle();
|
||||
load.ready();
|
||||
};
|
||||
|
||||
// Disposed by its handle, from its first ready listener.
|
||||
const part = createCesiumDraw({
|
||||
scene: fakeScene(),
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const set = part.port.models({ id: 'planes' });
|
||||
const heard = [];
|
||||
set.on('ready', () => set.dispose());
|
||||
set.on('ready', (id) => heard.push(id));
|
||||
set.on('loadFailed', (id) => heard.push(`failed ${id}`));
|
||||
set.set([plane('p')]);
|
||||
await loaded(loads[0]);
|
||||
assert.deepEqual(heard, [], 'the second listener does not run');
|
||||
|
||||
// Every set, when the port is disposed from a ready listener.
|
||||
const gone = createCesiumDraw({
|
||||
scene: fakeScene(),
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const other = gone.port.models({ id: 'planes' });
|
||||
const late = [];
|
||||
other.on('ready', () => gone.dispose({ removeHosts: true }));
|
||||
other.on('ready', (id) => late.push(id));
|
||||
other.set([plane('q')]);
|
||||
await loaded(loads[1]);
|
||||
assert.deepEqual(late, [], 'nothing after the port is gone');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a disposed set, and every set once the port is disposed, does nothing on later calls', async () => {
|
||||
const { loads, restore } = fakeModelLoads();
|
||||
try {
|
||||
const items = {
|
||||
points: { id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' },
|
||||
lines: {
|
||||
id: 'a',
|
||||
positions: [
|
||||
{ lon: 0, lat: 0 },
|
||||
{ lon: 1, lat: 1 },
|
||||
],
|
||||
widthPx: 2,
|
||||
style: { kind: 'solid', color: '#fff' },
|
||||
},
|
||||
icons: {
|
||||
id: 'a',
|
||||
pos: { lon: 0, lat: 0 },
|
||||
image: 'data:image/png;base64,iVBORw0KGgo=',
|
||||
},
|
||||
shapes: {
|
||||
id: 'a',
|
||||
geometry: {
|
||||
kind: 'ellipse',
|
||||
center: { lon: 0, lat: 0 },
|
||||
semiMajor: 1000,
|
||||
semiMinor: 1000,
|
||||
},
|
||||
fill: [1, 0, 0, 0.5],
|
||||
},
|
||||
models: { id: 'a', pos: { lon: 0, lat: 0, height: 10 }, url: 'a.glb' },
|
||||
};
|
||||
const lateCalls = (set, item) => {
|
||||
set.set([item]);
|
||||
set.upsert([{ ...item, id: 'b' }]);
|
||||
set.show = true;
|
||||
set.setOptions({ clampTo: 'terrain', pickable: false, drawOrder: 3 });
|
||||
set.setOptions({ show: true });
|
||||
set.setColumns?.({
|
||||
ids: ['c'],
|
||||
positions: new Float64Array([6378137, 0, 0]),
|
||||
});
|
||||
set.remove(['a']);
|
||||
set.clear();
|
||||
assert.equal(typeof set.on('ready', () => {}), 'function');
|
||||
};
|
||||
|
||||
// Disposed by its handle.
|
||||
const scene = fakeScene();
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
for (const [kind, item] of Object.entries(items)) {
|
||||
const set = part.port[kind]({ id: kind });
|
||||
set.dispose();
|
||||
lateCalls(set, item);
|
||||
assert.equal(scene.added.length, 0, `${kind}: nothing drawn`);
|
||||
assert.equal(part.sets.size, 0, `${kind}: no set live`);
|
||||
set.dispose();
|
||||
}
|
||||
// A newer set under the same id is not changed by the old handle.
|
||||
const old = part.port.points({ id: 'same' });
|
||||
old.dispose();
|
||||
const newer = part.port.points({ id: 'same' });
|
||||
old.set([items.points]);
|
||||
assert.equal(newer.size(), 0, 'the newer set keeps its items');
|
||||
newer.dispose();
|
||||
|
||||
// Every set, once the port is disposed (its renderer destroyed), and a
|
||||
// set asked for after that.
|
||||
const held = fakeScene();
|
||||
const gone = createCesiumDraw({
|
||||
scene: held,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
const before = Object.keys(items).map((kind) => [
|
||||
kind,
|
||||
gone.port[kind]({ id: kind }),
|
||||
]);
|
||||
gone.dispose({ removeHosts: true });
|
||||
for (const [kind, set] of before) lateCalls(set, items[kind]);
|
||||
for (const [kind, item] of Object.entries(items))
|
||||
lateCalls(gone.port[kind]({ id: `${kind}:late` }), item);
|
||||
assert.equal(held.added.length, 0, 'nothing drawn after the port is gone');
|
||||
assert.equal(gone.sets.size, 0, 'no set live after the port is gone');
|
||||
assert.equal(loads.length, 0, 'no model loads');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -664,8 +664,20 @@ export function createCesiumFields({
|
||||
return handle;
|
||||
}
|
||||
|
||||
// Once the fields are disposed (their renderer destroyed), a field asked
|
||||
// for draws nothing and does nothing.
|
||||
let gone = false;
|
||||
const inert = (spec) => ({
|
||||
id: spec?.id,
|
||||
show: true,
|
||||
update() {},
|
||||
on: () => () => {},
|
||||
dispose() {},
|
||||
});
|
||||
|
||||
return {
|
||||
field(spec) {
|
||||
if (gone) return inert(spec);
|
||||
if (fields.has(spec?.id))
|
||||
throw new Error(`a field with id ${spec.id} is live`);
|
||||
if (spec?.kind === 'rasterShell') return rasterShell(spec);
|
||||
@@ -688,6 +700,7 @@ export function createCesiumFields({
|
||||
},
|
||||
has: (id) => fields.has(id),
|
||||
dispose() {
|
||||
gone = true;
|
||||
for (const handle of [...fields.values()]) handle.dispose();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -691,3 +691,32 @@ test('the Cesium fields refuse kinds they cannot draw and live ids', () => {
|
||||
field.dispose();
|
||||
h.fields.field(spec).dispose();
|
||||
});
|
||||
|
||||
test('once the fields are disposed, a field asked for draws nothing and does nothing', () => {
|
||||
const h = fieldHarness();
|
||||
const field = h.fields.field({
|
||||
kind: 'rasterShell',
|
||||
id: 'shell',
|
||||
image: h.image(),
|
||||
rectangle: RECT,
|
||||
heightM: 1,
|
||||
});
|
||||
h.fields.dispose();
|
||||
assert.equal(h.live().length, 0, 'the live field went');
|
||||
field.update({ alpha: 0.5 });
|
||||
field.show = true;
|
||||
const late = h.fields.field({
|
||||
kind: 'rasterShell',
|
||||
id: 'late',
|
||||
image: h.image(),
|
||||
rectangle: RECT,
|
||||
heightM: 1,
|
||||
});
|
||||
late.update({ heightM: 2 });
|
||||
late.show = true;
|
||||
assert.equal(typeof late.on('drawn', () => {}), 'function');
|
||||
h.render();
|
||||
assert.equal(h.live().length, 0, 'nothing drawn after');
|
||||
assert.equal(h.fields.has('late'), false);
|
||||
late.dispose();
|
||||
});
|
||||
+101
-13
@@ -14,7 +14,10 @@
|
||||
* `maxPixelSize` (the scale capped so the bounding sphere spans at most that
|
||||
* many drawing-buffer pixels at its distance from the eye, as Cesium
|
||||
* measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's
|
||||
* alpha) and the set's `horizonCull`.
|
||||
* alpha), the set's `horizonCull`, and its `recede`: the tint's alpha times
|
||||
* the focus and haze (`render/recession.js`), written again once that moves
|
||||
* by more than `RECEDE_WRITE_EPSILON`. A model of a set that does not
|
||||
* recede draws at its tint's alpha times its `focus`.
|
||||
*
|
||||
* A failed load fires `loadFailed` (after the frame Cesium reported it in,
|
||||
* so a listener may change the set), and is tried again when its item is
|
||||
@@ -25,6 +28,12 @@
|
||||
* them. Heights are absolute: models clamp nothing.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
recedeFactors,
|
||||
recedeFrame,
|
||||
recedeParams,
|
||||
recededAlpha,
|
||||
} from '../recession.js';
|
||||
|
||||
const BLEND_MODES = {
|
||||
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
|
||||
@@ -39,6 +48,13 @@ const BLEND_MODES = {
|
||||
*/
|
||||
export const MODEL_RETRY_MS = 5000;
|
||||
|
||||
/**
|
||||
* How far a receding model's emphasis (focus and haze) moves before its
|
||||
* colour is written again: an eye in motion would otherwise write every
|
||||
* model's colour every frame.
|
||||
*/
|
||||
export const RECEDE_WRITE_EPSILON = 0.005;
|
||||
|
||||
/** Cesium's own blend amount, for a `mix` that names none. */
|
||||
const DEFAULT_MIX = 0.5;
|
||||
|
||||
@@ -85,9 +101,17 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
*/
|
||||
function entryShader(entry) {
|
||||
const shading = entry.item.shading;
|
||||
if (entry.mask && shading !== 'thermal')
|
||||
return maskShaderOf(shading, entry.mask);
|
||||
return shaderOf(shading);
|
||||
// Kept while its shading and mask colour are: a fleet re-poses every
|
||||
// frame with the same look.
|
||||
if (entry.shaderShading === shading && entry.shaderMask === entry.mask)
|
||||
return entry.shader;
|
||||
entry.shader =
|
||||
entry.mask && shading !== 'thermal'
|
||||
? maskShaderOf(shading, entry.mask)
|
||||
: shaderOf(shading);
|
||||
entry.shaderShading = shading;
|
||||
entry.shaderMask = entry.mask;
|
||||
return entry.shader;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,8 +175,12 @@ const scratchAxes = new Cesium.Cartesian3();
|
||||
const scratchMatrix = new Cesium.Matrix4();
|
||||
const scratchSphere = new Cesium.BoundingSphere();
|
||||
const scratchColor = new Cesium.Color();
|
||||
const scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
|
||||
const scratchFrame = { active: false, limbM: 1, strength: 0 };
|
||||
/** The colour last written to each model. */
|
||||
const writtenColors = new WeakMap();
|
||||
/** Written to a model drawn in its own colours: no colour at all. */
|
||||
const NO_COLOR = Symbol('drawModels.noColor');
|
||||
/** What the per-frame pass found, for a model it does not run on. */
|
||||
const STILL = Object.freeze({ scale: 1, alpha: 1, shown: true });
|
||||
|
||||
@@ -189,7 +217,12 @@ const needsFrame = (item, spec) =>
|
||||
item.maxPixelSize > 0 ||
|
||||
Boolean(item.scaleByDistance) ||
|
||||
Boolean(item.fadeByDistance) ||
|
||||
Boolean(spec.horizonCull);
|
||||
Boolean(spec.horizonCull) ||
|
||||
Boolean(spec.recede);
|
||||
|
||||
/** An item's focus, 0..1. */
|
||||
const focusOf = (item) =>
|
||||
Number.isFinite(item.focus) ? Math.min(1, Math.max(0, item.focus)) : 1;
|
||||
|
||||
/**
|
||||
* The models part of a Cesium draw port.
|
||||
@@ -421,12 +454,27 @@ export function createModelSets({
|
||||
entry.tint ?? Cesium.Color.WHITE,
|
||||
scratchColor,
|
||||
);
|
||||
color.alpha *= frame.alpha;
|
||||
color.alpha *= frame.alpha * (entry.emphasis ?? focusOf(item));
|
||||
// An untinted model at full opacity is drawn without a colour: a colour
|
||||
// adds a colour stage to every draw of the model.
|
||||
const plain = !entry.tint && color.alpha === 1;
|
||||
// Written only when what is asked changes, so a theme's own write to a
|
||||
// model's colour stands until then.
|
||||
const written = writtenColors.get(model);
|
||||
if (!written || !Cesium.Color.equals(written, color)) {
|
||||
writtenColors.set(model, Cesium.Color.clone(color, written));
|
||||
if (plain) {
|
||||
if (written !== NO_COLOR) {
|
||||
writtenColors.set(model, NO_COLOR);
|
||||
model.color = undefined;
|
||||
}
|
||||
} else if (
|
||||
!written ||
|
||||
written === NO_COLOR ||
|
||||
!Cesium.Color.equals(written, color)
|
||||
) {
|
||||
writtenColors.set(
|
||||
model,
|
||||
Cesium.Color.clone(color, written === NO_COLOR ? undefined : written),
|
||||
);
|
||||
model.color = color;
|
||||
}
|
||||
const show =
|
||||
@@ -434,17 +482,24 @@ export function createModelSets({
|
||||
if (model.show !== show) model.show = show;
|
||||
}
|
||||
|
||||
/** Add or change items, by id; true once handled (always, for models). */
|
||||
/**
|
||||
* Add or change items, by id. Whether any was added: models moved or
|
||||
* restyled keep their pick ids, so only one added changes what height
|
||||
* queries see through.
|
||||
*/
|
||||
function upsert(record, list) {
|
||||
hostOf(record);
|
||||
for (const item of list) put(record, item);
|
||||
notePickIds(record);
|
||||
let added = false;
|
||||
for (const item of list) if (put(record, item)) added = true;
|
||||
if (added) notePickIds(record);
|
||||
requestRender();
|
||||
return true;
|
||||
return added;
|
||||
}
|
||||
|
||||
/** Draw `item` on its entry, made when it has none; true when made. */
|
||||
function put(record, item) {
|
||||
let entry = record.models.get(item.id);
|
||||
const made = !entry;
|
||||
if (!entry) {
|
||||
entry = {
|
||||
item,
|
||||
@@ -463,8 +518,15 @@ export function createModelSets({
|
||||
failedAt: 0,
|
||||
settleLoad: null,
|
||||
styled: null,
|
||||
// The custom shader drawn with, for the shading and mask it is of
|
||||
// (`entryShader`).
|
||||
shader: undefined,
|
||||
shaderShading: null,
|
||||
shaderMask: null,
|
||||
dynamic: false,
|
||||
frame: null,
|
||||
// Focus and haze in a set that recedes, else null (focus alone).
|
||||
emphasis: null,
|
||||
pickId: pickId(record, item),
|
||||
};
|
||||
record.models.set(item.id, entry);
|
||||
@@ -495,6 +557,7 @@ export function createModelSets({
|
||||
if (model) style(record, entry, model);
|
||||
const retry = entry.failed && Date.now() - entry.failedAt >= MODEL_RETRY_MS;
|
||||
if (entry.url !== item.url || retry) load(record, entry);
|
||||
return made;
|
||||
}
|
||||
|
||||
/** Stop the entry's load in flight, keeping the model it draws. */
|
||||
@@ -527,8 +590,17 @@ export function createModelSets({
|
||||
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
|
||||
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
|
||||
let horizon;
|
||||
const eyeHeight = scene.camera.positionCartographic?.height;
|
||||
for (const record of sets) {
|
||||
if (record.kind !== 'models' || !record.models) continue;
|
||||
if (record.recedeFrom !== record.spec.recede) {
|
||||
record.recedeFrom = record.spec.recede;
|
||||
record.recede = recedeParams(record.spec.recede);
|
||||
}
|
||||
const recede = record.recede;
|
||||
const recedeNow = recede
|
||||
? recedeFrame(eyeHeight, recede, scratchFrame)
|
||||
: null;
|
||||
for (const entry of record.models.values()) {
|
||||
if (!entry.dynamic) {
|
||||
if (entry.frame) {
|
||||
@@ -548,6 +620,20 @@ export function createModelSets({
|
||||
Math.max(0, nearFarValue(item.fadeByDistance, distance)),
|
||||
)
|
||||
: 1;
|
||||
if (recede) {
|
||||
const haze = recedeFactors(
|
||||
distance,
|
||||
recedeNow,
|
||||
recede,
|
||||
scratchFactors,
|
||||
).alpha;
|
||||
const emphasis = recededAlpha(focusOf(item), haze, recede);
|
||||
if (
|
||||
entry.emphasis === null ||
|
||||
Math.abs(entry.emphasis - emphasis) > RECEDE_WRITE_EPSILON
|
||||
)
|
||||
entry.emphasis = emphasis;
|
||||
} else entry.emphasis = null;
|
||||
let shown = frame.alpha > 0;
|
||||
if (record.spec.horizonCull) {
|
||||
horizon ??= horizonNow();
|
||||
@@ -609,8 +695,10 @@ export function createModelSets({
|
||||
/** The set's options changed: whether models need the frame pass. */
|
||||
function restyle(record) {
|
||||
if (!record.models) return;
|
||||
for (const entry of record.models.values())
|
||||
for (const entry of record.models.values()) {
|
||||
entry.dynamic = needsFrame(entry.item, record.spec);
|
||||
if (!record.spec.recede) entry.emphasis = null;
|
||||
}
|
||||
}
|
||||
|
||||
return { build, upsert, beforeRender, restyle };
|
||||
|
||||
Vendored
+3
-2
@@ -150,7 +150,7 @@ export function createCesiumEffects(
|
||||
onChange: () => {
|
||||
if (gone() || modulation.draws() === modulationListed) return;
|
||||
modulationListed = modulation.draws();
|
||||
listeners.fire(port.diagnostics());
|
||||
if (listeners.size) listeners.fire(port.diagnostics());
|
||||
},
|
||||
})
|
||||
: null;
|
||||
@@ -223,7 +223,8 @@ export function createCesiumEffects(
|
||||
if (gone()) return;
|
||||
apply();
|
||||
frame.requestRender(reason);
|
||||
listeners.fire(port.diagnostics());
|
||||
// A fade changes every frame: its diagnostics are listed only for ears.
|
||||
if (listeners.size) listeners.fire(port.diagnostics());
|
||||
}
|
||||
|
||||
/** Whether `id` names a style; changes to unknown ones are ignored. */
|
||||
|
||||
@@ -144,9 +144,12 @@ export function createCesiumGlobe(
|
||||
// The vector base's sources' credits.
|
||||
const vectorCredits = [];
|
||||
|
||||
/** Every 3D tileset the scene holds. */
|
||||
function tilesets() {
|
||||
const found = [];
|
||||
/**
|
||||
* Every 3D tileset the scene holds, into `found` (emptied first): the
|
||||
* per-frame readers pass `scratchTilesets` rather than make a list.
|
||||
*/
|
||||
function tilesets(found = []) {
|
||||
found.length = 0;
|
||||
const primitives = scene.primitives;
|
||||
const n = primitives?.length ?? 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -155,12 +158,13 @@ export function createCesiumGlobe(
|
||||
}
|
||||
return found;
|
||||
}
|
||||
const scratchTilesets = [];
|
||||
|
||||
/** The base tileset drawn now, which `objects` imagery drapes on. */
|
||||
function drawnBase() {
|
||||
if (photoreal && !photoreal.isDestroyed() && photoreal.show)
|
||||
return photoreal;
|
||||
for (const tileset of tilesets())
|
||||
for (const tileset of tilesets(scratchTilesets))
|
||||
if (isBaseTileset(tileset) && tileset.show && !tileset.isDestroyed())
|
||||
return tileset;
|
||||
return null;
|
||||
@@ -401,7 +405,7 @@ export function createCesiumGlobe(
|
||||
function surfaceLoaded() {
|
||||
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
|
||||
let found = false;
|
||||
for (const tileset of tilesets()) {
|
||||
for (const tileset of tilesets(scratchTilesets)) {
|
||||
if (!tileset.show || tileset.isDestroyed?.()) continue;
|
||||
found = true;
|
||||
if (tileset.tilesLoaded === false) return false;
|
||||
@@ -423,7 +427,7 @@ export function createCesiumGlobe(
|
||||
// The shown tilesets as a set: their order among the primitives is no
|
||||
// change to the surface.
|
||||
let count = 0;
|
||||
for (const tileset of tilesets()) {
|
||||
for (const tileset of tilesets(scratchTilesets)) {
|
||||
if (!tileset.show || tileset.isDestroyed?.()) continue;
|
||||
count += 1;
|
||||
if (!surfaceSeen.tiles.has(tileset)) changed = true;
|
||||
@@ -433,7 +437,7 @@ export function createCesiumGlobe(
|
||||
surfaceSeen.globe = globe;
|
||||
surfaceSeen.terrain = terrain;
|
||||
surfaceSeen.tiles.clear();
|
||||
for (const tileset of tilesets())
|
||||
for (const tileset of scratchTilesets)
|
||||
if (tileset.show && !tileset.isDestroyed?.())
|
||||
surfaceSeen.tiles.add(tileset);
|
||||
surfaceVersion = ++surfaceVersions;
|
||||
@@ -480,7 +484,7 @@ export function createCesiumGlobe(
|
||||
applyShading();
|
||||
requestRender('base');
|
||||
}
|
||||
if (imagery.list().length) imagery.sync();
|
||||
if (imagery.size) imagery.sync();
|
||||
if (progressListeners.size === 0) return;
|
||||
const base = drawnBase();
|
||||
progress.tilesPending = base && !base.tilesLoaded ? 1 : 0;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* @module render/cesium/gpuIcons
|
||||
* @description The Cesium draw port's GPU icon sets: an icon set whose items
|
||||
* move (`motionSegments`), glide their course (`courseGlide`), recede
|
||||
* toward the limb, pick through a larger proxy,
|
||||
* toward the limb (`recede`, the set's), pick through a larger proxy,
|
||||
* switch images by drawn size, or that takes columns (`columns`), draws as
|
||||
* one instanced primitive (`IconSetPrimitive`) over an icon set's typed
|
||||
* columns (`iconSet.js`) instead of a billboard collection. Each item is one
|
||||
@@ -200,16 +200,19 @@ function rasterPxOf(url, item) {
|
||||
|
||||
/**
|
||||
* @param {{scene: object, capabilities: ReadonlySet<string>,
|
||||
* date?: (() => number)|null,
|
||||
* toColor: (color: unknown) => Cesium.Color,
|
||||
* imageOf: (record: object, image: unknown) => unknown,
|
||||
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
|
||||
* requestRender: (reason: string) => void}} options `imageOf` reads an atlas slot
|
||||
* requestRender: (reason: string) => void}} options `date` is the epoch
|
||||
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
|
||||
* through the draw port's atlases (undefined while it is not registered),
|
||||
* noting that the set draws from it; `peekImage` only reads it.
|
||||
*/
|
||||
export function createGpuIcons({
|
||||
scene,
|
||||
capabilities,
|
||||
date = null,
|
||||
toColor,
|
||||
imageOf,
|
||||
peekImage,
|
||||
@@ -217,13 +220,13 @@ export function createGpuIcons({
|
||||
}) {
|
||||
const can = (capability) => capabilities.has(capability);
|
||||
|
||||
/** Whether drawing these items needs a GPU icon set. */
|
||||
function wants(items) {
|
||||
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
|
||||
function wants(items, spec = {}) {
|
||||
if (spec.recede) return true;
|
||||
for (const item of items) {
|
||||
if (
|
||||
(item.motion && can('motionSegments')) ||
|
||||
(item.courseGlide && can('courseGlide')) ||
|
||||
item.recede ||
|
||||
item.pickProxy ||
|
||||
item.imageLod
|
||||
)
|
||||
@@ -293,7 +296,9 @@ export function createGpuIcons({
|
||||
result,
|
||||
);
|
||||
return Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(result),
|
||||
date
|
||||
? Cesium.JulianDate.fromDate(new Date(date()), result)
|
||||
: Cesium.JulianDate.now(result),
|
||||
-(clock?.delayMs ?? 0) / 1000,
|
||||
result,
|
||||
);
|
||||
@@ -309,6 +314,7 @@ export function createGpuIcons({
|
||||
clockTime(frameState, new Cesium.JulianDate()),
|
||||
requestRender: () => requestRender(`icons:${spec.id}`),
|
||||
cull: () => spec.horizonCull === true,
|
||||
recede: () => spec.recede,
|
||||
translucent: () => spec.blend === 'translucent',
|
||||
// Picked as the draw port's other items are: `{set, id, meta}` as
|
||||
// the item now is, hidden row by row for drill picks.
|
||||
@@ -423,7 +429,7 @@ export function createGpuIcons({
|
||||
isCurve(item.scaleByDistance) ? item.scaleByDistance : undefined,
|
||||
);
|
||||
set.setFlag(row, ICON_ROTATES, item.rotationMode === 'course');
|
||||
set.setFlag(row, ICON_RECEDES, item.recede === true);
|
||||
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
|
||||
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
|
||||
set.setPickProxy(
|
||||
row,
|
||||
@@ -727,10 +733,15 @@ export function createGpuIcons({
|
||||
}
|
||||
columnIds = ids;
|
||||
},
|
||||
/** After `setOptions`: the cull lift follows `horizonCull`. */
|
||||
/**
|
||||
* After `setOptions`: the cull lift follows `horizonCull`, and every
|
||||
* row recedes while the set does.
|
||||
*/
|
||||
restyle() {
|
||||
for (let row = 0; row < set.count; row++)
|
||||
for (let row = 0; row < set.count; row++) {
|
||||
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
|
||||
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
|
||||
}
|
||||
},
|
||||
/** Rewrite the rows drawing from atlas `id`. */
|
||||
reatlas(id) {
|
||||
|
||||
@@ -221,9 +221,45 @@ test('rows moving on a live clock keep frames coming until their segments end',
|
||||
assert.equal(scene.renders, onScene);
|
||||
});
|
||||
|
||||
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
|
||||
const { scene, part, draw } = drawOver();
|
||||
// An item's own `recede` is not the contract's: it changes nothing.
|
||||
const still = draw.icons({ id: 'gpu:still' });
|
||||
still.set([icon('a', { recede: true })]);
|
||||
assert.ok(
|
||||
!(scene.added.at(-1) instanceof IconSetPrimitive),
|
||||
'still icons stay billboards',
|
||||
);
|
||||
const set = draw.icons({
|
||||
id: 'gpu:recede',
|
||||
recede: { scaleFloor: 0.6 },
|
||||
});
|
||||
set.set([icon('a'), icon('b')]);
|
||||
const host = scene.added.at(-1);
|
||||
assert.ok(host instanceof IconSetPrimitive, 'on the GPU, though still');
|
||||
const { set: s } = rows(part, 'gpu:recede');
|
||||
for (const id of ['a', 'b'])
|
||||
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, ICON_RECEDES, id);
|
||||
assert.equal(host._recedeParams().scaleFloor, 0.6);
|
||||
assert.equal(host._recedeParams().alphaFloor, 0.35, 'the rest the defaults');
|
||||
set.setOptions({ recede: null });
|
||||
for (const id of ['a', 'b'])
|
||||
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, 0, `${id} no longer`);
|
||||
assert.equal(host._recedeParams(), null);
|
||||
// A billboard set told to recede goes onto the GPU, its icons with it.
|
||||
still.setOptions({ recede: {} });
|
||||
const moved = part.sets.get('gpu:still').gpu;
|
||||
assert.ok(moved, 'on the GPU now');
|
||||
assert.equal(moved.set.count, 1);
|
||||
assert.equal(
|
||||
moved.set.flags(moved.set.row('a')) & ICON_RECEDES,
|
||||
ICON_RECEDES,
|
||||
);
|
||||
});
|
||||
|
||||
test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy, depth and images', () => {
|
||||
const { part, draw } = drawOver();
|
||||
const set = draw.icons({ id: 'gpu:look', horizonCull: true });
|
||||
const set = draw.icons({ id: 'gpu:look', horizonCull: true, recede: {} });
|
||||
set.set([
|
||||
icon('a', {
|
||||
motion: { kind: 'hold', courseDeg: 10 },
|
||||
@@ -232,7 +268,6 @@ test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy
|
||||
alpha: 0.5,
|
||||
color: [1, 0, 0, 1],
|
||||
focus: 0.25,
|
||||
recede: true,
|
||||
rotationMode: 'course',
|
||||
pickProxy: { size: [48, 40] },
|
||||
disableDepthTest: Infinity,
|
||||
@@ -1127,3 +1162,28 @@ test('a GPU icon set asks the frame port for its atlas frames, under its own rea
|
||||
iconAtlas.onChange = onChange;
|
||||
}
|
||||
});
|
||||
|
||||
test('a live motion clock reads the date the draw port is given', () => {
|
||||
const t0 = Date.UTC(2031, 0, 2, 3, 4, 5);
|
||||
let date = t0 + 4000;
|
||||
const { part, draw } = drawOver({ date: () => date });
|
||||
const set = draw.icons({
|
||||
id: 'gpu:dated',
|
||||
motionClock: { kind: 'live', delayMs: 1000 },
|
||||
});
|
||||
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
|
||||
const item = icon('a', {
|
||||
motion: { kind: 'lerp', from: ecef(AT), to, t0, t1: t0 + 10_000 },
|
||||
});
|
||||
set.set([item]);
|
||||
const at = (ms) => iconPosition(item, ms);
|
||||
assert.ok(
|
||||
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 3000)) <
|
||||
0.1,
|
||||
);
|
||||
date = t0 + 8000;
|
||||
assert.ok(
|
||||
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 7000)) <
|
||||
0.1,
|
||||
);
|
||||
});
|
||||
@@ -24,6 +24,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'camera.trace.commands inside a lookAt frame',
|
||||
'camera.trace.changed fires by each listener’s threshold',
|
||||
'camera.moveEnd',
|
||||
'camera.changed.order',
|
||||
'camera.controls.holds',
|
||||
'camera.controls.settings',
|
||||
'camera.follow',
|
||||
@@ -74,6 +75,9 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.lines.segments',
|
||||
'draw.lines.segmentStyles',
|
||||
'draw.sets.blend',
|
||||
'draw.sets.recede',
|
||||
'draw.sets.recede.models',
|
||||
'draw.afterDispose',
|
||||
'draw.ids',
|
||||
'draw.models',
|
||||
'draw.shapes.lit',
|
||||
@@ -123,6 +127,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'input.clickPick',
|
||||
'input.lease',
|
||||
'input.lease.grab',
|
||||
'input.lease.lost',
|
||||
'input.lease.press',
|
||||
'query.heights',
|
||||
'query.pickBeforeStyles',
|
||||
@@ -134,12 +139,24 @@ export const CESIUM_CHECKS = new Set([
|
||||
'quality',
|
||||
'quality.signals',
|
||||
'quality.signals.gpuTiming',
|
||||
'renderer.afterDestroy',
|
||||
'renderer.afterDestroy.frames',
|
||||
'renderer.listeners',
|
||||
'renderer.listenerRules',
|
||||
'renderer.shape',
|
||||
'renderer.capture',
|
||||
'renderer.readPixels',
|
||||
'renderer.releaseUnused',
|
||||
'renderer.whenSettled',
|
||||
'renderer.resize',
|
||||
'frame.setTargetFps',
|
||||
'globe.setTerrain',
|
||||
'globe.setPhotoreal',
|
||||
'globe.progress',
|
||||
'effects.setStyleParams',
|
||||
'effects.bloom',
|
||||
'effects.sharpen',
|
||||
'quality.probe',
|
||||
]);
|
||||
|
||||
/** A frame fails the check rather than hang it when frames stop. */
|
||||
@@ -183,6 +200,7 @@ export function createCesiumHarness({
|
||||
// own that each frame moves on by 1/60 s: flights then step as the
|
||||
// reference traces do, frame by frame.
|
||||
const clocks = new WeakMap();
|
||||
const containers = new WeakMap();
|
||||
return {
|
||||
name,
|
||||
// A camera controller hears the pointer events sent through `pointer`
|
||||
@@ -220,8 +238,15 @@ export function createCesiumHarness({
|
||||
}
|
||||
};
|
||||
clocks.set(renderer, clock);
|
||||
containers.set(renderer, container);
|
||||
return renderer;
|
||||
},
|
||||
resizeContainer: (r, { width, height }) => {
|
||||
const container = containers.get(r);
|
||||
if (!container) return;
|
||||
container.style.width = `${width}px`;
|
||||
container.style.height = `${height}px`;
|
||||
},
|
||||
frame: (r) => {
|
||||
const clock = clocks.get(r);
|
||||
if (clock) clock.ms += 1000 / 60;
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
* (`alignedAxis` zero), depth test disabled at any distance (drawn on the near plane),
|
||||
* opaque and translucent passes, horizon culling, and per-row picks whose object is
|
||||
* `{ id, meta, primitive }` (`primitive.show` hides that one row, as drillPick expects).
|
||||
* Rows flagged to recede also take the aircraft limb recession, composed with focus.
|
||||
* Rows flagged to recede (the set's `recede`) also take the limb recession
|
||||
* (`render/recession.js`), composed with focus.
|
||||
*
|
||||
* On WebGL 2 each row also reads its extras ({@link module:iconSet}'s
|
||||
* `extras`) from a float texture by instance: a screen offset and anchor, a
|
||||
@@ -37,10 +38,10 @@ import {
|
||||
MIN_ICON_SLOTS,
|
||||
NEAR_IMAGE_DEVICE_PX,
|
||||
} from '../../data/iconAtlas.js';
|
||||
import {
|
||||
cameraLimbDistanceM,
|
||||
getAircraftRecessionParams,
|
||||
} from '../../data/aircraftRecession.js';
|
||||
import { recedeFrame, recedeParams } from '../recession.js';
|
||||
|
||||
/** The parameters the uniforms hold while the set does not recede. */
|
||||
const NO_RECEDE = recedeParams({});
|
||||
|
||||
const ATTRIBUTE_LOCATIONS = Object.freeze({
|
||||
corner: 0,
|
||||
@@ -339,12 +340,18 @@ export class IconSetPrimitive {
|
||||
renderTime,
|
||||
requestRender,
|
||||
cull,
|
||||
recede,
|
||||
translucent,
|
||||
pickObject,
|
||||
}) {
|
||||
this.set = set;
|
||||
this.renderTime = renderTime;
|
||||
this._cull = cull ?? (() => true);
|
||||
// The set's `recede`, and the parameters last made from it.
|
||||
this._recede = recede ?? (() => null);
|
||||
this._recedeFrom = undefined;
|
||||
this._recedeResolved = null;
|
||||
this._recedeFrame = { active: false, limbM: 1, strength: 0 };
|
||||
this._translucent = translucent ?? (() => false);
|
||||
this._pickObject = pickObject ?? null;
|
||||
this._pickPass = 0;
|
||||
@@ -694,31 +701,19 @@ export class IconSetPrimitive {
|
||||
this._horizon,
|
||||
);
|
||||
|
||||
const tuning = getAircraftRecessionParams();
|
||||
const height = camera.positionCartographic?.height;
|
||||
const limb = cameraLimbDistanceM(height, tuning.earthRadiusM);
|
||||
const active =
|
||||
Number.isFinite(height) &&
|
||||
height > 0 &&
|
||||
height < tuning.globeViewBlendEndM &&
|
||||
limb > 0;
|
||||
let strength = 0;
|
||||
if (active) {
|
||||
const g = Math.min(
|
||||
1,
|
||||
Math.max(
|
||||
0,
|
||||
(height - tuning.globeViewBlendStartM) /
|
||||
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM),
|
||||
),
|
||||
);
|
||||
strength = 1 - g * g * (3 - 2 * g);
|
||||
}
|
||||
// Rows recede only while the set does (their flag says so); its
|
||||
// parameters, or the defaults' while it does not, fill the uniforms.
|
||||
const tuning = this._recedeParams() ?? NO_RECEDE;
|
||||
const frame = recedeFrame(
|
||||
camera.positionCartographic?.height,
|
||||
tuning,
|
||||
this._recedeFrame,
|
||||
);
|
||||
Cesium.Cartesian4.fromElements(
|
||||
active ? limb : 1,
|
||||
frame.limbM,
|
||||
tuning.startLimbRatio,
|
||||
strength,
|
||||
active ? 1 : 0,
|
||||
frame.strength,
|
||||
frame.active ? 1 : 0,
|
||||
this._recession,
|
||||
);
|
||||
Cesium.Cartesian3.fromElements(
|
||||
@@ -729,6 +724,16 @@ export class IconSetPrimitive {
|
||||
);
|
||||
}
|
||||
|
||||
/** The set's `recede` as the parameters it draws with; null: it does not recede. */
|
||||
_recedeParams() {
|
||||
const spec = this._recede();
|
||||
if (spec !== this._recedeFrom) {
|
||||
this._recedeFrom = spec;
|
||||
this._recedeResolved = recedeParams(spec);
|
||||
}
|
||||
return this._recedeResolved;
|
||||
}
|
||||
|
||||
_createCommands(context) {
|
||||
this._slotCount = contextIconSlots(context);
|
||||
this._slotUniform = this._slots.slice(0, this._slotCount);
|
||||
|
||||
@@ -835,6 +835,10 @@ export function createCesiumImagery(
|
||||
/** After each frame: each timed layer's shown frame, once it is drawn. */
|
||||
function announceFrames() {
|
||||
if (disposed) return;
|
||||
// Most frames have no timed layer: the copy below is made only for one.
|
||||
let timedLayers = false;
|
||||
for (const record of layers) if (record.timed?.at) timedLayers = true;
|
||||
if (!timedLayers) return;
|
||||
for (const record of layers.slice()) {
|
||||
const timed = record.timed;
|
||||
// A layer removed by another's listener says nothing.
|
||||
@@ -858,6 +862,10 @@ export function createCesiumImagery(
|
||||
return {
|
||||
add,
|
||||
list: () => layers.map((record) => record.handle),
|
||||
/** How many layers the port holds, without listing them. */
|
||||
get size() {
|
||||
return layers.length;
|
||||
},
|
||||
/** Layers whose providers are still being built, as promises. */
|
||||
ready: (handles) =>
|
||||
Promise.allSettled(
|
||||
|
||||
@@ -94,6 +94,7 @@ function setup({ stock = true, document = null, takeStock = true } = {}) {
|
||||
handler.fire(T.LEFT_CLICK, { position: at(x, y) }, modifier);
|
||||
};
|
||||
return {
|
||||
widget,
|
||||
input,
|
||||
port: input.port,
|
||||
handler,
|
||||
@@ -442,3 +443,31 @@ test('not taking the stock, they stay on the viewer’s handler but while held',
|
||||
'dispose gives a held one back',
|
||||
);
|
||||
});
|
||||
|
||||
test("a tool that does not hold off stock clicks leaves the viewer's select and double-click follow running; one that does stops them", async (t) => {
|
||||
const { inputFor } = await import('../../input/dispatcher.js');
|
||||
const { claimPointer, releasePointer } =
|
||||
await import('../../data/inputOwnership.js');
|
||||
const s = setup();
|
||||
// The dispatcher over this port, as the application's layers take input.
|
||||
const dispatcher = inputFor(s.widget, {
|
||||
query: { pick: () => null, drillPick: () => [] },
|
||||
});
|
||||
t.after(() => dispatcher.destroy());
|
||||
const placed = [];
|
||||
const lease = claimPointer('placing-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
dispatcher.onPointer('click', () => placed.push('tool'), { lease });
|
||||
s.press(5, 6);
|
||||
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
|
||||
assert.deepEqual(placed, ['tool']);
|
||||
assert.equal(s.selected.length, 1, 'the stock select ran on its click');
|
||||
assert.equal(s.followed.length, 1, 'and the double-click follow');
|
||||
const hold = dispatcher.suppressStockClicks();
|
||||
s.press(5, 6);
|
||||
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
|
||||
hold();
|
||||
assert.deepEqual(placed, ['tool', 'tool']);
|
||||
assert.equal(s.selected.length, 1, 'held off: no stock select');
|
||||
assert.equal(s.followed.length, 1, 'nor follow');
|
||||
});
|
||||
+110
-46
@@ -108,20 +108,26 @@ export function cesiumCapabilities(scene, only) {
|
||||
);
|
||||
}
|
||||
|
||||
/** What `renderOnce` and `capture` reject with once the renderer is destroyed. */
|
||||
const destroyedError = () => new Error('renderer destroyed');
|
||||
|
||||
/**
|
||||
* @param {object} widget A Cesium `CesiumWidget` or `Viewer`.
|
||||
* @param {{capabilities: ReadonlySet<string>, credentials?: object,
|
||||
* cameraController?: Function, now?: () => number,
|
||||
* cameraController?: import('../contract/camera').CameraControllerFactory,
|
||||
* now?: () => number,
|
||||
* date?: () => number,
|
||||
* idleFps?: number}} options
|
||||
* The renderer's capabilities, which gate the members that need them, and
|
||||
* the credentials its globe loads photoreal tiles and world data with
|
||||
* (`googleApiKey`, `googleTokens`, `worldDataToken`). `now` is the clock
|
||||
* each tick reads (`performance.now` by default; a test's virtual one).
|
||||
* With `idleFps`, the loop ticks at most that often while no hold is out
|
||||
* (Cesium ticks its clock and every update listener each animation frame
|
||||
* even when it draws nothing), and at the display's rate while one is;
|
||||
* `setTargetFps` then caps both, and the loop starts with no cap of its
|
||||
* own. Without it, the widget's own rate is the cap.
|
||||
* each tick reads (`performance.now` by default; a test's virtual one);
|
||||
* `date`, the epoch ms a `live` motion clock reads (the system clock's by
|
||||
* default). With `idleFps`, the loop ticks at most that often while no
|
||||
* hold is out (Cesium ticks its clock and every update listener each
|
||||
* animation frame even when it draws nothing), and at the display's rate
|
||||
* while one is; `setTargetFps` then caps both, and the loop starts with no
|
||||
* cap of its own. Without it, the widget's own rate is the cap.
|
||||
* With
|
||||
* `cameraController`, the camera port is that controller's over Cesium's
|
||||
* camera (`controlledCamera.js`); the ports then have `attachInput` and
|
||||
@@ -134,6 +140,7 @@ export function createCesiumPorts(
|
||||
credentials = {},
|
||||
cameraController,
|
||||
now: clockNow = () => performance.now(),
|
||||
date = null,
|
||||
idleFps = 0,
|
||||
},
|
||||
) {
|
||||
@@ -187,23 +194,39 @@ export function createCesiumPorts(
|
||||
});
|
||||
liveTick = null;
|
||||
};
|
||||
// The camera's `changed`, measured before any `preUpdate` listener moves
|
||||
// the camera, in a frame that had no clock tick to measure it at.
|
||||
let measureCameraChanged = null;
|
||||
const settleUndrawn = () => void settleTick(false);
|
||||
const tick = () => {
|
||||
measureCameraChanged?.();
|
||||
settleTick(false);
|
||||
// A tick that does not draw settles at its end; one that does, at
|
||||
// preRender, before this runs.
|
||||
atEndOfTick(scene, () => void settleTick(false));
|
||||
atEndOfTick(scene, settleUndrawn);
|
||||
const now = clockNow();
|
||||
dt = (now - tickNow) / 1000;
|
||||
tickNow = now;
|
||||
frames += 1;
|
||||
};
|
||||
// A scene time as epoch ms, worked out again only when the time moves:
|
||||
// the phases of a frame, and the frames of a paused clock, share one.
|
||||
let msJulian = null;
|
||||
let msValue = 0;
|
||||
// What `setTime` reads a time through.
|
||||
const scratchDate = new Date(0);
|
||||
const scratchJulian = new Cesium.JulianDate();
|
||||
const msOf = (time) => {
|
||||
if (msJulian && Cesium.JulianDate.equals(msJulian, time)) return msValue;
|
||||
msValue = Cesium.JulianDate.toDate(time).getTime();
|
||||
msJulian = Cesium.JulianDate.clone(time, msJulian ?? undefined);
|
||||
return msValue;
|
||||
};
|
||||
const onPhase = (phase) => (_scene, time) => {
|
||||
if (frameListeners[phase].size === 0) return;
|
||||
const t = {
|
||||
frame: frames,
|
||||
time: Cesium.JulianDate.toDate(
|
||||
time ?? widget.clock.currentTime,
|
||||
).getTime(),
|
||||
time: msOf(time ?? widget.clock.currentTime),
|
||||
now: tickNow,
|
||||
dt,
|
||||
rendering: true,
|
||||
@@ -245,7 +268,7 @@ export function createCesiumPorts(
|
||||
let controlled = null;
|
||||
const cameraTick = (time) => ({
|
||||
now: tickNow,
|
||||
time: Cesium.JulianDate.toDate(time ?? widget.clock.currentTime).getTime(),
|
||||
time: msOf(time ?? widget.clock.currentTime),
|
||||
});
|
||||
const removers = [
|
||||
scene.preUpdate.addEventListener(tick),
|
||||
@@ -289,24 +312,26 @@ export function createCesiumPorts(
|
||||
idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
|
||||
if (idleFps > 0) applyRate();
|
||||
|
||||
// Pending one-shot renders; disposal settles them rather than leave them
|
||||
// Pending one-shot renders; disposal rejects them rather than leave them
|
||||
// attached to a scene that will not render again.
|
||||
const pendingRenders = new Set();
|
||||
/** Resolves after the next drawn frame; rejects after `timeoutMs`, if given. */
|
||||
/**
|
||||
* Resolves after the next drawn frame; rejects after `timeoutMs`, if
|
||||
* given, and once the renderer is destroyed.
|
||||
*/
|
||||
function nextPostRender({ timeoutMs } = {}) {
|
||||
if (disposed) return Promise.resolve();
|
||||
if (disposed) return Promise.reject(destroyedError());
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer;
|
||||
const settle = (error) => {
|
||||
off();
|
||||
clearTimeout(timer);
|
||||
pendingRenders.delete(done);
|
||||
pendingRenders.delete(settle);
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const done = () => settle();
|
||||
const off = scene.postRender.addEventListener(done);
|
||||
pendingRenders.add(done);
|
||||
const off = scene.postRender.addEventListener(() => settle());
|
||||
pendingRenders.add(settle);
|
||||
if (timeoutMs !== undefined)
|
||||
timer = setTimeout(
|
||||
() => settle(new Error('renderOnce timed out')),
|
||||
@@ -380,9 +405,11 @@ export function createCesiumPorts(
|
||||
*/
|
||||
setTime(ms) {
|
||||
const clock = widget.clock;
|
||||
const time = Cesium.JulianDate.fromDate(new Date(ms));
|
||||
scratchDate.setTime(ms);
|
||||
const time = Cesium.JulianDate.fromDate(scratchDate, scratchJulian);
|
||||
const changed = !Cesium.JulianDate.equals(clock.currentTime, time);
|
||||
clock.currentTime = time;
|
||||
// The clock keeps the time it is given; it ignores an equal one.
|
||||
if (changed) clock.currentTime = Cesium.JulianDate.clone(time);
|
||||
// In `preUpdate` the frame under way draws at it: Cesium stamps the
|
||||
// frame with this object next.
|
||||
if (stampTime) {
|
||||
@@ -391,7 +418,7 @@ export function createCesiumPorts(
|
||||
if (liveTick) liveTick.time = ms;
|
||||
} else if (changed) frame.requestRender('time');
|
||||
},
|
||||
time: () => Cesium.JulianDate.toDate(widget.clock.currentTime).getTime(),
|
||||
time: () => msOf(widget.clock.currentTime),
|
||||
};
|
||||
|
||||
// --- Draw ------------------------------------------------------------------
|
||||
@@ -401,6 +428,7 @@ export function createCesiumPorts(
|
||||
report,
|
||||
capabilities,
|
||||
requestRender: (reason) => frame.requestRender(reason),
|
||||
date,
|
||||
});
|
||||
const { port: draw, sets, tilesets } = drawPart;
|
||||
|
||||
@@ -454,6 +482,7 @@ export function createCesiumPorts(
|
||||
: {}),
|
||||
});
|
||||
const cameraPort = cameraPart.port;
|
||||
measureCameraChanged = cameraPart.measureChanged ?? null;
|
||||
const effectsPart = createCesiumEffects(scene, {
|
||||
capabilities,
|
||||
frame,
|
||||
@@ -482,10 +511,36 @@ export function createCesiumPorts(
|
||||
credentials,
|
||||
});
|
||||
|
||||
async function capture({ type = 'png' } = {}) {
|
||||
scene.render(widget.clock.currentTime);
|
||||
return new Promise((resolve) =>
|
||||
scene.canvas.toBlob(resolve, `image/${type}`),
|
||||
/**
|
||||
* Whether the canvas still holds the last presented frame: a context that
|
||||
* keeps its drawing buffer, once a frame has drawn. Otherwise the frame is
|
||||
* drawn again to be read.
|
||||
*/
|
||||
const frameKept = () =>
|
||||
rendered > 0 &&
|
||||
webglContext(scene)?.getContextAttributes?.()?.preserveDrawingBuffer ===
|
||||
true;
|
||||
|
||||
/**
|
||||
* The last presented frame, encoded: `crop` in CSS pixels, `scale`
|
||||
* relative to the canvas's CSS size, `quality` for JPEG. Read from the
|
||||
* canvas as it is where it keeps that frame, so a capture draws nothing.
|
||||
*/
|
||||
async function capture({ type = 'png', quality, crop, scale = 1 } = {}) {
|
||||
if (disposed) throw destroyedError();
|
||||
if (!frameKept()) scene.render(widget.clock.currentTime);
|
||||
const out = document.createElement('canvas').getContext('2d');
|
||||
copyFrame(out, crop, scale);
|
||||
return new Promise((resolve, reject) =>
|
||||
out.canvas.toBlob(
|
||||
(blob) => {
|
||||
out.canvas.width = out.canvas.height = 0;
|
||||
if (blob) resolve(blob);
|
||||
else reject(new Error('the frame could not be encoded'));
|
||||
},
|
||||
`image/${type}`,
|
||||
quality,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -493,33 +548,24 @@ export function createCesiumPorts(
|
||||
let reader = null;
|
||||
|
||||
/**
|
||||
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
|
||||
* the canvas's CSS size. Read straight off the canvas: the application
|
||||
* and conformance widgets keep their drawing buffers, and a read right
|
||||
* after a draw sees it either way.
|
||||
* Draws the canvas's frame into the 2D context `into`, `crop` in CSS
|
||||
* pixels and `scale` relative to the canvas's CSS size, sized to it.
|
||||
* Returns whether there was a frame to draw.
|
||||
*/
|
||||
function readPixels({ crop, scale = 1 } = {}) {
|
||||
function copyFrame(into, crop, scale = 1) {
|
||||
const canvas = scene.canvas;
|
||||
const cssWidth = canvas.clientWidth || canvas.width;
|
||||
const cssHeight = canvas.clientHeight || canvas.height;
|
||||
const rect = crop ?? { x: 0, y: 0, width: cssWidth, height: cssHeight };
|
||||
const width = Math.max(1, Math.round(rect.width * scale));
|
||||
const height = Math.max(1, Math.round(rect.height * scale));
|
||||
const made =
|
||||
reader ??
|
||||
document
|
||||
.createElement('canvas')
|
||||
.getContext('2d', { willReadFrequently: true });
|
||||
// Disposed ports keep nothing to free.
|
||||
if (!disposed) reader = made;
|
||||
made.canvas.width = width;
|
||||
made.canvas.height = height;
|
||||
// A canvas with no size has drawn nothing: the read is blank.
|
||||
if (!canvas.width || !canvas.height)
|
||||
return made.getImageData(0, 0, width, height);
|
||||
into.canvas.width = width;
|
||||
into.canvas.height = height;
|
||||
// A canvas with no size has drawn nothing: the copy is blank.
|
||||
if (!canvas.width || !canvas.height) return false;
|
||||
const sx = canvas.width / cssWidth;
|
||||
const sy = canvas.height / cssHeight;
|
||||
made.drawImage(
|
||||
into.drawImage(
|
||||
canvas,
|
||||
rect.x * sx,
|
||||
rect.y * sy,
|
||||
@@ -530,7 +576,25 @@ export function createCesiumPorts(
|
||||
width,
|
||||
height,
|
||||
);
|
||||
return made.getImageData(0, 0, width, height);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
|
||||
* the canvas's CSS size. Read straight off the canvas: the application
|
||||
* and conformance widgets keep their drawing buffers, and a read right
|
||||
* after a draw sees it either way.
|
||||
*/
|
||||
function readPixels({ crop, scale = 1 } = {}) {
|
||||
const made =
|
||||
reader ??
|
||||
document
|
||||
.createElement('canvas')
|
||||
.getContext('2d', { willReadFrequently: true });
|
||||
// Disposed ports keep nothing to free.
|
||||
if (!disposed) reader = made;
|
||||
copyFrame(made, crop, scale);
|
||||
return made.getImageData(0, 0, made.canvas.width, made.canvas.height);
|
||||
}
|
||||
|
||||
// A release asked for whose globe trim waits for the next drawn frame.
|
||||
@@ -779,7 +843,7 @@ export function createCesiumPorts(
|
||||
effectsPart.dispose();
|
||||
globePart.dispose();
|
||||
qualityPart.dispose();
|
||||
for (const done of [...pendingRenders]) done();
|
||||
for (const settle of [...pendingRenders]) settle(destroyedError());
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -373,6 +373,7 @@ export function createCesiumQuery({
|
||||
},
|
||||
pickRay(x, y) {
|
||||
const ray = pickRayAt(scene, camera, x, y);
|
||||
if (!ray) return null;
|
||||
return { origin: ecef(ray.origin), direction: ecef(ray.direction) };
|
||||
},
|
||||
project(position) {
|
||||
@@ -387,8 +388,8 @@ export function createCesiumQuery({
|
||||
return s ? { x: s.x, y: s.y } : null;
|
||||
},
|
||||
projectMany(source, out) {
|
||||
const p = new Cesium.Cartesian3();
|
||||
const s = new Cesium.Cartesian2();
|
||||
const p = projectedPoint;
|
||||
const s = projectedWindow;
|
||||
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
|
||||
p.x = source[i];
|
||||
p.y = source[i + 1];
|
||||
|
||||
@@ -274,3 +274,22 @@ test('hiding the sets seen through answers as seeing through their items did, ne
|
||||
ground.dispose();
|
||||
markers.dispose();
|
||||
});
|
||||
|
||||
test('a canvas with no size has no pick ray: null, not a throw', () => {
|
||||
const viewer = fakeViewer();
|
||||
const { scene } = viewer;
|
||||
scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
scene.canvas = { clientWidth: 0, clientHeight: 0 };
|
||||
Object.assign(scene.camera, {
|
||||
frustum: new Cesium.PerspectiveFrustum({ fov: 1, aspectRatio: 1 }),
|
||||
directionWC: new Cesium.Cartesian3(-1, 0, 0),
|
||||
rightWC: new Cesium.Cartesian3(0, 1, 0),
|
||||
upWC: new Cesium.Cartesian3(0, 0, 1),
|
||||
});
|
||||
const query = queryOf(viewer);
|
||||
assert.equal(query.pickRay(0, 0), null);
|
||||
scene.canvas = { clientWidth: 100, clientHeight: 100 };
|
||||
const ray = query.pickRay(50, 50);
|
||||
assert.deepEqual(ray.origin, { x: 2e7, y: 0, z: 0 });
|
||||
assert.ok(Math.abs(ray.direction.x + 1) < 1e-9);
|
||||
});
|
||||
@@ -35,7 +35,8 @@ export const pointerFeedOf = (renderer) => feeds.get(renderer) ?? null;
|
||||
|
||||
/**
|
||||
* @param {{container: HTMLElement, msaa?: number, capabilities?: Iterable<string>,
|
||||
* cameraController?: Function, now?: () => number}} options
|
||||
* cameraController?: import('../contract/camera').CameraControllerFactory,
|
||||
* now?: () => number}} options
|
||||
* `capabilities` limits the renderer to those it lists; `cameraController`
|
||||
* puts the camera port on that controller (`controlledCamera.js`); `now`
|
||||
* is the clock its ticks and pointer events read (`performance.now` by
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
import goldens from '../goldens/camera.json' with { type: 'json' };
|
||||
import {
|
||||
AUSTIN,
|
||||
CAMERA_SCRIPTS,
|
||||
SCRIPT_VIEWPORT,
|
||||
usesInput,
|
||||
@@ -432,6 +433,58 @@ export function cameraChecks() {
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.changed.order',
|
||||
port: 'camera',
|
||||
title:
|
||||
'`changed` is measured before preUpdate; a move made in preUpdate is reported on the next frame',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
try {
|
||||
const at = (height) => ({
|
||||
destination: { ...AUSTIN, height },
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
r.camera.setView(at(2000));
|
||||
const seen = [];
|
||||
let move = null;
|
||||
r.camera.on('changed', () => seen.push('changed'));
|
||||
r.frame.on('preUpdate', () => {
|
||||
seen.push('preUpdate');
|
||||
if (move) r.camera.setView(move);
|
||||
move = null;
|
||||
});
|
||||
// The first measure is the listener's starting point.
|
||||
await h.frame(r);
|
||||
await h.frame(r);
|
||||
seen.length = 0;
|
||||
r.camera.setView(at(8000));
|
||||
await h.frame(r);
|
||||
deepEqual(
|
||||
seen,
|
||||
['changed', 'preUpdate'],
|
||||
'a move made before the frame is reported before preUpdate',
|
||||
);
|
||||
seen.length = 0;
|
||||
move = at(2000);
|
||||
await h.frame(r);
|
||||
deepEqual(
|
||||
seen,
|
||||
['preUpdate'],
|
||||
'a move made in preUpdate is not reported in its own frame',
|
||||
);
|
||||
seen.length = 0;
|
||||
await h.frame(r);
|
||||
deepEqual(
|
||||
seen,
|
||||
['changed', 'preUpdate'],
|
||||
'it is reported as the next frame starts',
|
||||
);
|
||||
} finally {
|
||||
r.destroy();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.follow',
|
||||
port: 'camera',
|
||||
@@ -786,7 +839,7 @@ export function cameraChecks() {
|
||||
const r = await fresh(h);
|
||||
const at = async (height, pitch = -Math.PI / 2) => {
|
||||
r.camera.setView({
|
||||
destination: { lon: -97.74, lat: 30.27, height },
|
||||
destination: { ...AUSTIN, height },
|
||||
orientation: { heading: 0, pitch, roll: 0 },
|
||||
});
|
||||
await h.frame(r);
|
||||
|
||||
@@ -137,6 +137,27 @@ async function listenerRules(r, where, subscribe, fire) {
|
||||
offError();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every call a set takes after it is disposed: each must do nothing. `item`
|
||||
* (null: none) is what `set` and `upsert` are given.
|
||||
*/
|
||||
function lateCalls(set, item) {
|
||||
const list = item ? [item] : [];
|
||||
set.set(list);
|
||||
set.upsert(item ? [{ ...item, id: 'b' }] : []);
|
||||
set.show = true;
|
||||
set.setOptions({ pickable: true, drawOrder: 3 });
|
||||
set.setColumns?.({
|
||||
ids: ['c'],
|
||||
positions: new Float64Array(
|
||||
item?.pos ? [item.pos.x, item.pos.y, item.pos.z] : [0, 0, 0],
|
||||
),
|
||||
});
|
||||
set.remove(['missing']);
|
||||
set.upsert(list);
|
||||
set.dispose();
|
||||
}
|
||||
|
||||
/** A check over a fresh renderer, destroyed afterwards. */
|
||||
/**
|
||||
* The sky with the renderer's look off (`SkySettings`): what is drawn shows
|
||||
@@ -774,6 +795,130 @@ export function portChecks() {
|
||||
b.dispose();
|
||||
},
|
||||
),
|
||||
check(
|
||||
'draw.afterDispose',
|
||||
'a disposed set draws nothing, whatever is called on it after',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r);
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
// A live set beside them, so the picks below can find something.
|
||||
const live = r.draw.points({ id: 'conf:kept' });
|
||||
live.set([{ id: 'kept', pos, pixelSize: 8, color: '#0f0' }]);
|
||||
const point = { id: 'a', pos, pixelSize: 30, color: '#f00' };
|
||||
const icon = { id: 'a', pos, image: DOT, size: [32, 32] };
|
||||
const gone = [
|
||||
[r.draw.points({ id: 'conf:gone:points' }), point],
|
||||
[r.draw.icons({ id: 'conf:gone:icons' }), icon],
|
||||
];
|
||||
for (const [kind, capability] of SET_KINDS)
|
||||
if (!capability || r.capabilities.has(capability))
|
||||
gone.push([r.draw[kind]({ id: `conf:gone:${kind}:empty` }), null]);
|
||||
for (const [set] of gone) set.dispose();
|
||||
for (const [set, item] of gone) lateCalls(set, item);
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
const s = r.query.project(pos);
|
||||
ok(s, 'the point projects');
|
||||
const hits = r.query.drillPick(s.x, s.y);
|
||||
ok(
|
||||
hits.some((hit) => hit.set === 'conf:kept'),
|
||||
'the live set is picked',
|
||||
);
|
||||
ok(
|
||||
hits.every((hit) => !String(hit.set).startsWith('conf:gone')),
|
||||
'nothing of a disposed set is picked',
|
||||
);
|
||||
ok(
|
||||
gone.every(([set]) => set.show === false || set.show === true),
|
||||
'show still reads',
|
||||
);
|
||||
// Its id is free; the old handle does not reach the new set.
|
||||
const again = r.draw.points({ id: 'conf:gone:points' });
|
||||
lateCalls(gone[0][0], point);
|
||||
equal(again.size(), 0, 'the newer set under the id is untouched');
|
||||
again.dispose();
|
||||
live.dispose();
|
||||
},
|
||||
),
|
||||
{
|
||||
id: 'renderer.afterDestroy',
|
||||
port: 'renderer',
|
||||
title: 'once the renderer is destroyed, its sets and new ones do nothing',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const sets = [];
|
||||
try {
|
||||
await overAustin(h, r);
|
||||
for (const [kind, capability] of SET_KINDS)
|
||||
if (!capability || r.capabilities.has(capability))
|
||||
sets.push(r.draw[kind]({ id: `conf:destroyed:${kind}` }));
|
||||
} finally {
|
||||
r.destroy();
|
||||
}
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
const point = { id: 'a', pos, pixelSize: 30, color: '#f00' };
|
||||
const late = r.draw.points({ id: 'conf:destroyed:late' });
|
||||
// What is set on them is not kept, so nothing is drawn of it.
|
||||
for (const set of [sets[1], late]) {
|
||||
set.set([point]);
|
||||
set.upsert([{ ...point, id: 'b' }]);
|
||||
equal(set.size(), 0, `${set.id} keeps nothing set after destroy`);
|
||||
}
|
||||
for (const set of sets) lateCalls(set, set === sets[1] ? point : null);
|
||||
lateCalls(late, point);
|
||||
for (const set of [...sets, late]) set.dispose();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'renderer.afterDestroy.frames',
|
||||
port: 'renderer',
|
||||
title:
|
||||
'once the renderer is destroyed, renderOnce and capture reject, and a renderOnce waiting rejects too',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
let waiting;
|
||||
try {
|
||||
await overAustin(h, r);
|
||||
// Suspended, the loop draws nothing: the renderOnce waits.
|
||||
r.frame.suspend(true);
|
||||
waiting = r.frame.renderOnce().then(
|
||||
() => 'resolved',
|
||||
(error) => error,
|
||||
);
|
||||
} finally {
|
||||
r.destroy();
|
||||
}
|
||||
const destroyed = (error, what) =>
|
||||
ok(
|
||||
error instanceof Error && /destroyed/.test(error.message),
|
||||
`${what} rejects saying the renderer is destroyed (${error})`,
|
||||
);
|
||||
const settledIn = (promise) =>
|
||||
Promise.race([
|
||||
promise,
|
||||
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
|
||||
]);
|
||||
destroyed(await settledIn(waiting), 'a renderOnce waiting at destroy');
|
||||
destroyed(
|
||||
await settledIn(
|
||||
r.frame.renderOnce().then(
|
||||
() => 'resolved',
|
||||
(error) => error,
|
||||
),
|
||||
),
|
||||
'renderOnce',
|
||||
);
|
||||
destroyed(
|
||||
await settledIn(
|
||||
r.capture().then(
|
||||
() => 'resolved',
|
||||
(error) => error,
|
||||
),
|
||||
),
|
||||
'capture',
|
||||
);
|
||||
},
|
||||
},
|
||||
check(
|
||||
'draw.pick',
|
||||
'a drawn icon is picked under its projection with its set, id and meta',
|
||||
@@ -1842,11 +1987,11 @@ export function portChecks() {
|
||||
[kind, image],
|
||||
[`atlas-${kind}`, { atlas: 'conf:images', slot: kind }],
|
||||
]);
|
||||
// Two sets: still icons, and icons that recede (drawn as moving
|
||||
// ones are, where a renderer draws them apart).
|
||||
// Two sets: still icons, and a set that recedes (drawn as moving
|
||||
// icons are, where a renderer draws them apart).
|
||||
const rows = [
|
||||
['still', {}, AUSTIN.lat + 0.004],
|
||||
['receding', { recede: true }, AUSTIN.lat - 0.004],
|
||||
['receding', { recede: {} }, AUSTIN.lat - 0.004],
|
||||
];
|
||||
const at = (i, lat) =>
|
||||
h.toEcef({
|
||||
@@ -1855,14 +2000,13 @@ export function portChecks() {
|
||||
height: 0,
|
||||
});
|
||||
const sets = rows.map(([name, extra, lat]) => {
|
||||
const set = r.draw.icons({ id: `conf:images-${name}` });
|
||||
const set = r.draw.icons({ id: `conf:images-${name}`, ...extra });
|
||||
set.set(
|
||||
images.map(([id, image], i) => ({
|
||||
id,
|
||||
pos: at(i, lat),
|
||||
image,
|
||||
size: [20, 20],
|
||||
...extra,
|
||||
})),
|
||||
);
|
||||
return set;
|
||||
@@ -1884,6 +2028,105 @@ export function portChecks() {
|
||||
for (const set of sets) set.dispose();
|
||||
},
|
||||
),
|
||||
check(
|
||||
'draw.sets.recede',
|
||||
'icon and model sets take `recede` and change it live: their items, near the eye, are drawn and picked whether the set recedes or not',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r);
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
const icons = r.draw.icons({ id: 'conf:recede-icons', recede: {} });
|
||||
icons.set([{ id: 'one', pos, image: DOT, size: [24, 24], focus: 0.5 }]);
|
||||
const models = r.draw.models?.({
|
||||
id: 'conf:recede-models',
|
||||
recede: { alphaFloor: 0.5 },
|
||||
});
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
const s = r.query.project(pos);
|
||||
ok(s, 'the icon projects');
|
||||
const picked = () => r.query.pick(s.x, s.y);
|
||||
deepEqual(
|
||||
[picked()?.set, picked()?.id],
|
||||
['conf:recede-icons', 'one'],
|
||||
'a receding icon near the eye is drawn and picked',
|
||||
);
|
||||
for (const recede of [null, { scaleFloor: 0.6 }, {}]) {
|
||||
icons.setOptions({ recede });
|
||||
models?.setOptions({ recede });
|
||||
await drawn(h, r);
|
||||
equal(
|
||||
picked()?.id,
|
||||
'one',
|
||||
`drawn and picked with recede ${JSON.stringify(recede)}`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
icons.dispose();
|
||||
models?.dispose();
|
||||
}
|
||||
},
|
||||
),
|
||||
check(
|
||||
'draw.sets.recede.models',
|
||||
'a model set that recedes composes each model’s focus as `RecedeSpec` says, and takes a new `recede` live: near the eye a model at focus 1 draws at full strength, at focus 0.25 faded, and a combined floor of 1 brings it back',
|
||||
async (h, r) => {
|
||||
if (!h.assets?.model) return { skip: 'no model asset in this harness' };
|
||||
await overAustin(h, r);
|
||||
const set = r.draw.models({ id: 'conf:recede-models', recede: {} });
|
||||
const ready = [];
|
||||
set.on('ready', (id) => ready.push(id));
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
const model = (focus) => ({
|
||||
id: 'm',
|
||||
pos,
|
||||
url: h.assets.model,
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
minPixelSize: 160,
|
||||
environmentMap: false,
|
||||
shading: 'unlit',
|
||||
tint: '#ff0000',
|
||||
colorBlend: { mode: 'replace' },
|
||||
focus,
|
||||
});
|
||||
try {
|
||||
set.set([model(1)]);
|
||||
for (let i = 0; i < 600 && !ready.length; i++) await drawn(h, r, 1);
|
||||
deepEqual(ready, ['m'], 'ready');
|
||||
const s = r.query.project(pos);
|
||||
// How many pixels of a patch at the model's centre are red.
|
||||
const red = async () => {
|
||||
await drawn(h, r, 3);
|
||||
await settled(r);
|
||||
r.frame.renderNow();
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x) - 4,
|
||||
y: Math.round(s.y) - 4,
|
||||
width: 9,
|
||||
height: 9,
|
||||
},
|
||||
});
|
||||
let n = 0;
|
||||
for (let i = 0; i < image.data.length; i += 4) {
|
||||
const [r0, g, b] = image.data.subarray(i, i + 3);
|
||||
if (r0 > 180 && g < 70 && b < 70) n++;
|
||||
}
|
||||
return n;
|
||||
};
|
||||
ok((await red()) >= 40, 'near the eye, focus 1: full strength');
|
||||
set.upsert([model(0.25)]);
|
||||
ok((await red()) < 10, 'focus 0.25 fades it');
|
||||
set.setOptions({ recede: { combinedAlphaFloor: 1 } });
|
||||
ok((await red()) >= 40, 'a combined floor of 1 holds it, live');
|
||||
equal(r.query.pick(s.x, s.y)?.set, set.id, 'and it is picked');
|
||||
deepEqual(ready, ['m'], 'without loading again');
|
||||
} finally {
|
||||
set.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'models', bareSky: true },
|
||||
),
|
||||
clusterCheck(false),
|
||||
clusterCheck(true),
|
||||
check(
|
||||
@@ -4136,6 +4379,7 @@ export function portChecks() {
|
||||
const seen = [];
|
||||
r.input.on('click', () => seen.push('ambient'));
|
||||
const lease = r.input.claimPointer('tool');
|
||||
equal(lease.owner, 'tool', 'the lease names its owner');
|
||||
for (const type of POINTER_TYPES) await h.pointer(r, type, 640, 360);
|
||||
deepEqual(ambient, ['move', 'up'], 'ambient under a lease');
|
||||
seen.length = 0;
|
||||
@@ -4155,6 +4399,61 @@ export function portChecks() {
|
||||
deepEqual(seen, ['ambient'], 'ambient again');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'input.lease.lost',
|
||||
'the newest claim takes over: the lease it ends is told once, after the new one holds the pointer, and its late release frees nothing; a throwing onLost is reported',
|
||||
async (h, r) => {
|
||||
if (!h.pointer) return { skip: 'no pointer in this harness' };
|
||||
const told = [];
|
||||
// What the ended lease's holder sees from inside its `onLost`.
|
||||
let inside = null;
|
||||
const a = r.input.claimPointer('a', {
|
||||
onLost: () => {
|
||||
told.push('a');
|
||||
inside = { free: r.input.isPointerFree(), current: a.current };
|
||||
},
|
||||
});
|
||||
const heard = [];
|
||||
r.input.on('down', () => heard.push('a'), { lease: a });
|
||||
const b = r.input.claimPointer('b', { onLost: () => told.push('b') });
|
||||
r.input.on('down', () => heard.push('b'), { lease: b });
|
||||
deepEqual(told, ['a'], 'the ended lease is told');
|
||||
deepEqual(
|
||||
inside,
|
||||
{ free: false, current: false },
|
||||
'inside onLost the new lease already holds the pointer and the old one has ended',
|
||||
);
|
||||
ok(!a.current && b.current, 'the newest lease holds the pointer');
|
||||
await h.pointer(r, 'down', 640, 360);
|
||||
await h.pointer(r, 'up', 640, 360);
|
||||
deepEqual(heard, ['b'], 'the newest holder gets the press');
|
||||
a.release();
|
||||
ok(b.current, "the ended lease's release frees nothing");
|
||||
ok(!r.input.isPointerFree(), 'still taken');
|
||||
deepEqual(told, ['a'], 'told once');
|
||||
b.release();
|
||||
deepEqual(told, ['a'], 'a lease its holder releases is not told');
|
||||
ok(r.input.isPointerFree(), 'free again');
|
||||
|
||||
const errors = [];
|
||||
r.on('error', (e) => errors.push(e));
|
||||
r.input.claimPointer('c', {
|
||||
onLost: () => {
|
||||
throw new Error('conformance onLost');
|
||||
},
|
||||
});
|
||||
const d = r.input.claimPointer('d');
|
||||
equal(errors.length, 1, 'a throwing onLost is reported');
|
||||
ok(d.current, 'and the new lease holds the pointer regardless');
|
||||
heard.length = 0;
|
||||
r.input.on('down', () => heard.push('d'), { lease: d });
|
||||
await h.pointer(r, 'down', 640, 360);
|
||||
await h.pointer(r, 'up', 640, 360);
|
||||
deepEqual(heard, ['d'], 'and gets the press');
|
||||
d.release();
|
||||
ok(r.input.isPointerFree(), 'free at the end');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'input.lease.grab',
|
||||
'a lease with grab takes only the presses it grabs; wheel and the rest stay free',
|
||||
@@ -5377,6 +5676,279 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
|
||||
);
|
||||
},
|
||||
),
|
||||
check(
|
||||
'renderer.capture',
|
||||
'capture encodes the last drawn frame as asked: cropped, scaled, its type and quality, drawing none of its own when the frame is kept',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false || typeof createImageBitmap !== 'function')
|
||||
return { skip: 'no encoded pixels to read' };
|
||||
await overAustin(h, r);
|
||||
const set = r.draw.points({ id: 'conf:capture' });
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
set.set([{ id: 'p', pos, pixelSize: 24, color: '#ff0000' }]);
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
const size = async (blob) => {
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
const wh = [bitmap.width, bitmap.height];
|
||||
bitmap.close();
|
||||
return wh;
|
||||
};
|
||||
let frames = 0;
|
||||
const off = r.frame.on('postRender', () => (frames += 1));
|
||||
const full = await r.capture();
|
||||
equal(full.type, 'image/png', 'a PNG by default');
|
||||
deepEqual(
|
||||
await size(full),
|
||||
[SCRIPT_VIEWPORT.width, SCRIPT_VIEWPORT.height],
|
||||
'the canvas’s CSS size',
|
||||
);
|
||||
const crop = { x: 10, y: 20, width: 40, height: 30 };
|
||||
deepEqual(
|
||||
await size(await r.capture({ crop, scale: 0.5 })),
|
||||
[20, 15],
|
||||
'a crop, scaled',
|
||||
);
|
||||
deepEqual(
|
||||
await size(await r.capture({ scale: 0.25 })),
|
||||
[SCRIPT_VIEWPORT.width / 4, SCRIPT_VIEWPORT.height / 4],
|
||||
'scaled',
|
||||
);
|
||||
const low = await r.capture({ type: 'jpeg', quality: 0.05 });
|
||||
const high = await r.capture({ type: 'jpeg', quality: 1 });
|
||||
equal(low.type, 'image/jpeg', 'a JPEG when asked');
|
||||
ok(low.size < high.size, 'a lower quality encodes smaller');
|
||||
// What a crop over the point shows is the point, as drawn.
|
||||
const s = r.query.project(pos);
|
||||
const around = { x: s.x - 4, y: s.y - 4, width: 8, height: 8 };
|
||||
const bitmap = await createImageBitmap(
|
||||
await r.capture({ crop: around }),
|
||||
);
|
||||
const canvas = new OffscreenCanvas(8, 8);
|
||||
const g = canvas.getContext('2d');
|
||||
g.drawImage(bitmap, 0, 0);
|
||||
bitmap.close();
|
||||
const [red, green, blue] = g.getImageData(4, 4, 1, 1).data;
|
||||
ok(
|
||||
red > 200 && green < 60 && blue < 60,
|
||||
`the point is in the crop (${red}, ${green}, ${blue})`,
|
||||
);
|
||||
off();
|
||||
// Where the renderer keeps its frame it reads it; otherwise it may
|
||||
// draw again to read.
|
||||
const gl =
|
||||
r.canvas.getContext?.('webgl2') ?? r.canvas.getContext?.('webgl');
|
||||
if (gl?.getContextAttributes?.()?.preserveDrawingBuffer === true)
|
||||
equal(frames, 0, 'no frame drawn for a capture of a kept frame');
|
||||
set.dispose();
|
||||
},
|
||||
),
|
||||
check(
|
||||
'renderer.resize',
|
||||
'resize follows the container: the lens and the frame read take its new size',
|
||||
async (h, r) => {
|
||||
if (!h.resizeContainer)
|
||||
return { skip: 'the harness cannot resize the container' };
|
||||
await overAustin(h, r);
|
||||
// A new aspect too, so a lens left as it was shows.
|
||||
const size = { width: 480, height: 320 };
|
||||
await h.resizeContainer(r, size);
|
||||
r.resize();
|
||||
await drawn(h, r);
|
||||
near(
|
||||
r.camera.pose().aspectRatio,
|
||||
size.width / size.height,
|
||||
1e-6,
|
||||
'the aspect is the container’s',
|
||||
);
|
||||
const full = r.readPixels({ scale: 0.1 });
|
||||
deepEqual(
|
||||
[full.width, full.height],
|
||||
[size.width / 10, size.height / 10],
|
||||
'the frame is the container’s size',
|
||||
);
|
||||
},
|
||||
),
|
||||
check(
|
||||
'frame.setTargetFps',
|
||||
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
|
||||
(h, r) => {
|
||||
r.frame.setTargetFps(24);
|
||||
equal(r.frame.diagnostics().targetFps, 24, 'capped');
|
||||
r.frame.setTargetFps(0);
|
||||
equal(r.frame.diagnostics().targetFps, 0, 'the display’s rate');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'globe.setTerrain',
|
||||
'setTerrain to the ellipsoid, exaggerated or not, resolves and leaves the globe settling',
|
||||
async (h, r) => {
|
||||
await r.globe.setTerrain({ kind: 'ellipsoid', exaggeration: 2 });
|
||||
await r.globe.setTerrain({ kind: 'ellipsoid' });
|
||||
await overAustin(h, r);
|
||||
await drawn(h, r);
|
||||
const result = await r.whenSettled({ timeoutMs: 10_000 });
|
||||
ok(
|
||||
!result.blockers.includes('terrain'),
|
||||
`the ellipsoid has nothing to load (${result.blockers})`,
|
||||
);
|
||||
},
|
||||
),
|
||||
check(
|
||||
'globe.setPhotoreal',
|
||||
'setPhotoreal(null) turns photoreal off: its status is route none',
|
||||
async (h, r) => {
|
||||
const status = await r.globe.setPhotoreal(null);
|
||||
equal(status.route, 'none', 'off');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'globe.progress',
|
||||
'progress listeners hear counts of what is loading, and their Off ends them',
|
||||
async (h, r) => {
|
||||
const heard = [];
|
||||
const off = r.globe.on('progress', (p) => heard.push(p));
|
||||
equal(typeof off, 'function', 'an Off');
|
||||
await overAustin(h, r);
|
||||
// Something to load: an image over the view.
|
||||
const over = (url) =>
|
||||
r.globe.imagery.add({
|
||||
kind: 'single-image',
|
||||
url,
|
||||
rectangle: {
|
||||
west: AUSTIN.lon - 1,
|
||||
south: AUSTIN.lat - 1,
|
||||
east: AUSTIN.lon + 1,
|
||||
north: AUSTIN.lat + 1,
|
||||
},
|
||||
});
|
||||
const layer = over(PIXEL_PNGS[0]);
|
||||
// Frames until the load is heard, or a while passes: a renderer may
|
||||
// first say nothing loads, before it starts on the image. The image
|
||||
// loads in time of its own, so each frame lets some pass.
|
||||
const loading = (p) =>
|
||||
p.tilesPending + p.imageryPending + p.terrainPending > 0;
|
||||
const until = Date.now() + 10_000;
|
||||
for (let i = 0; !heard.some(loading) && i < 600; i++) {
|
||||
if (Date.now() > until) break;
|
||||
await drawn(h, r, 1);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
ok(heard.some(loading), 'a load is heard');
|
||||
for (const p of heard)
|
||||
for (const key of [
|
||||
'tilesPending',
|
||||
'imageryPending',
|
||||
'terrainPending',
|
||||
])
|
||||
ok(p[key] >= 0, `${key} is a count (${p[key]})`);
|
||||
off();
|
||||
const before = heard.length;
|
||||
layer.remove();
|
||||
const again = over(PIXEL_PNGS[1]);
|
||||
await overAustin(h, r, 9000);
|
||||
await drawn(h, r);
|
||||
equal(heard.length, before, 'none after its Off');
|
||||
again.remove();
|
||||
},
|
||||
),
|
||||
check(
|
||||
'effects.setStyleParams',
|
||||
'a style’s parameters change what it draws',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false) return { skip: 'no pixels to read' };
|
||||
const off = r.effects.defineStyle({
|
||||
id: 'conf:fill',
|
||||
params: [{ key: 'red', min: 0, max: 1, default: 0 }],
|
||||
animated: false,
|
||||
shader: {
|
||||
glsl: `uniform float red;
|
||||
void main() {
|
||||
out_FragColor = vec4(red, 0.0, 0.0, 1.0);
|
||||
}`,
|
||||
wgsl: `@fragment
|
||||
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
|
||||
return vec4f(params.red, 0.0, 0.0, 1.0);
|
||||
}`,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await overAustin(h, r);
|
||||
// Below the eye, in the units `readPixels` crops in.
|
||||
const below = r.query.project(h.toEcef({ ...AUSTIN, height: 0 }));
|
||||
ok(below, 'the ground below projects');
|
||||
const red = async () => {
|
||||
await settled(r);
|
||||
r.frame.renderNow();
|
||||
const px = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(below.x),
|
||||
y: Math.round(below.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
return px.data[0];
|
||||
};
|
||||
r.effects.setStyleIntensity('conf:fill', 1);
|
||||
r.effects.setStyle('conf:fill', { red: 0 });
|
||||
ok((await red()) < 30, 'its default draws black');
|
||||
r.effects.setStyleParams('conf:fill', { red: 1 });
|
||||
ok((await red()) > 225, 'red once its parameter is 1');
|
||||
r.effects.setStyle(null);
|
||||
r.effects.setStyleIntensity('conf:fill', 0);
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
},
|
||||
{ capability: 'styles' },
|
||||
),
|
||||
check(
|
||||
'effects.bloom',
|
||||
'bloom on lists its pass, off drops it; the strength is kept',
|
||||
(h, r) => {
|
||||
const passes = () => r.effects.diagnostics().passes;
|
||||
r.effects.bloom({ enabled: true, strength: 0.4 });
|
||||
ok(passes().includes('bloom'), 'drawn while on');
|
||||
r.effects.bloom({ enabled: false });
|
||||
ok(!passes().includes('bloom'), 'not while off');
|
||||
r.effects.bloom({ enabled: true });
|
||||
ok(passes().includes('bloom'), 'on again at the kept strength');
|
||||
r.effects.bloom({ enabled: false });
|
||||
},
|
||||
{ capability: 'bloom' },
|
||||
),
|
||||
check(
|
||||
'effects.sharpen',
|
||||
'sharpen on lists its pass, off drops it',
|
||||
(h, r) => {
|
||||
const passes = () => r.effects.diagnostics().passes;
|
||||
r.effects.sharpen({ enabled: true, amount: 0.5 });
|
||||
ok(passes().includes('sharpen'), 'drawn while on');
|
||||
r.effects.sharpen({ enabled: false });
|
||||
ok(!passes().includes('sharpen'), 'not while off');
|
||||
},
|
||||
{ capability: 'sharpen' },
|
||||
),
|
||||
check(
|
||||
'quality.probe',
|
||||
'probe says the device, the browser and the knobs',
|
||||
(h, r) => {
|
||||
const probe = r.quality.probe();
|
||||
ok(
|
||||
['webgl1', 'webgl2', 'webgpu'].includes(probe.device.backend),
|
||||
`a backend (${probe.device.backend})`,
|
||||
);
|
||||
ok(probe.device.maxTextureSize > 0, 'a texture size');
|
||||
ok(probe.browser.devicePixelRatio > 0, 'a pixel ratio');
|
||||
equal(typeof probe.browser.touchOnly, 'boolean', 'touch only or not');
|
||||
deepEqual(
|
||||
probe.knobs.map((k) => k.key),
|
||||
r.quality.knobs().map((k) => k.key),
|
||||
'the knobs, as knobs() lists them',
|
||||
);
|
||||
},
|
||||
),
|
||||
check(
|
||||
'renderer.releaseUnused',
|
||||
'releaseUnused keeps what is in view drawn and picked',
|
||||
|
||||
Vendored
+255
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* The renderer conformance suite (`index.js`): every check run against a
|
||||
* renderer through the contract alone, in Node or in a browser page.
|
||||
*/
|
||||
import type {
|
||||
CameraPose,
|
||||
Ecef,
|
||||
Flight,
|
||||
Renderer,
|
||||
ScreenXY,
|
||||
} from '../contract/index';
|
||||
|
||||
export interface ConformanceTolerance {
|
||||
/** Positions and heights. */
|
||||
metres: number;
|
||||
/** Unit vectors (direction, up, right). */
|
||||
unit: number;
|
||||
/** Heading, pitch and roll. */
|
||||
radians: number;
|
||||
/** Screen positions. */
|
||||
pixels: number;
|
||||
/** `changed` events per script. */
|
||||
changedCount: number;
|
||||
}
|
||||
|
||||
/** How to make the renderer under test and drive its clock. */
|
||||
export interface ConformanceHarness {
|
||||
name: string;
|
||||
/** Null when it cannot make a renderer with fewer capabilities. */
|
||||
create(options: {
|
||||
viewport: { width: number; height: number };
|
||||
capabilities?: string[];
|
||||
}): Promise<Renderer | null>;
|
||||
frame(r: Renderer): void | Promise<void>;
|
||||
now(r: Renderer): number;
|
||||
toEcef(p: { lon: number; lat: number; height?: number }): Ecef;
|
||||
tolerance: ConformanceTolerance;
|
||||
/** Flight paths compared frame by frame, or only where flights end. */
|
||||
flightPaths: 'trace' | 'endpoints';
|
||||
/** Synthetic input. */
|
||||
pointer?(
|
||||
r: Renderer,
|
||||
type: string,
|
||||
x: number,
|
||||
y: number,
|
||||
extra?: object,
|
||||
): void | Promise<void>;
|
||||
/** False when the renderer draws only models into its pixels. */
|
||||
pixels?: boolean;
|
||||
/** The camera moves on pointer input sent through `pointer`. */
|
||||
cameraInput?: boolean;
|
||||
scriptHeights?(
|
||||
r: Renderer,
|
||||
fn: (
|
||||
point: { lon: number; lat: number },
|
||||
against?: string,
|
||||
) => number | null,
|
||||
): void;
|
||||
/** Epoch ms a `live` motion clock reads. */
|
||||
wallTime?(r: Renderer): number;
|
||||
/**
|
||||
* Sizes the element the renderer fills, in CSS pixels, for the check that
|
||||
* `resize` follows it. Without it, that check is skipped.
|
||||
*/
|
||||
resizeContainer?(
|
||||
r: Renderer,
|
||||
size: { width: number; height: number },
|
||||
): void | Promise<void>;
|
||||
assets?: {
|
||||
model?: string;
|
||||
missingModel?: string;
|
||||
modelBytes?: () => Promise<Uint8Array>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConformanceCheck {
|
||||
id: string;
|
||||
port: string;
|
||||
title: string;
|
||||
run(h: ConformanceHarness): Promise<{ skip: string } | void>;
|
||||
}
|
||||
|
||||
export interface ConformanceResult {
|
||||
id: string;
|
||||
port: string;
|
||||
title: string;
|
||||
status: 'pass' | 'fail' | 'skip';
|
||||
detail?: string;
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export interface ConformanceReport {
|
||||
harness: string;
|
||||
passed: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
results: ConformanceResult[];
|
||||
}
|
||||
|
||||
/** A camera script: the steps a trace check runs. */
|
||||
export interface CameraScript {
|
||||
name: string;
|
||||
steps: object[];
|
||||
}
|
||||
|
||||
/** A camera script's pointer event. */
|
||||
export interface ScriptPointer {
|
||||
type: 'down' | 'move' | 'up' | 'wheel';
|
||||
position: ScreenXY;
|
||||
endPosition?: ScreenXY;
|
||||
button: 0 | 1 | 2;
|
||||
modifiers: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };
|
||||
wheel?: { deltaY: number; deltaMode: number };
|
||||
}
|
||||
|
||||
/** What a camera script drives. */
|
||||
export interface CameraDriver {
|
||||
command(name: string, args: unknown[]): Flight | void;
|
||||
frame(): void | Promise<void>;
|
||||
/** Counts `changed`; returns a reader. */
|
||||
listen(threshold: number): () => number;
|
||||
pose(): CameraPose;
|
||||
project(position: Ecef): ScreenXY | null;
|
||||
pickEllipsoid(screen: ScreenXY): Ecef | null;
|
||||
pickRay(screen: ScreenXY): object;
|
||||
occluded(position: Ecef): boolean;
|
||||
flying(): boolean;
|
||||
toEcef(position: object): Ecef;
|
||||
pointer?(ev: ScriptPointer): void | Promise<void>;
|
||||
}
|
||||
|
||||
/** A reference scene, built from contract calls only. */
|
||||
export interface ReferenceScene {
|
||||
id: string;
|
||||
family: string;
|
||||
capability: string | null;
|
||||
needs?: string[];
|
||||
build(r: Renderer, ctx: object): Promise<() => void>;
|
||||
views: Array<{ name: string; view: object }>;
|
||||
}
|
||||
|
||||
export const DEFAULT_TOLERANCE: Readonly<ConformanceTolerance>;
|
||||
/** Every check, in run order. */
|
||||
export function conformanceChecks(): ConformanceCheck[];
|
||||
export function runConformance(
|
||||
harness: ConformanceHarness,
|
||||
options?: { only?: (id: string) => boolean },
|
||||
): Promise<ConformanceReport>;
|
||||
|
||||
export const CAMERA_SCRIPTS: ReadonlyArray<CameraScript>;
|
||||
/** The viewport every script runs in, CSS pixels. */
|
||||
export const SCRIPT_VIEWPORT: Readonly<{ width: number; height: number }>;
|
||||
/** Whether a script moves the camera by user input. */
|
||||
export function usesInput(script: CameraScript): boolean;
|
||||
|
||||
export const REFERENCE_SCENES: ReadonlyArray<ReferenceScene>;
|
||||
/** The city scene's poses from orbit down to the street. */
|
||||
export const CALIBRATION_PATH: Readonly<{
|
||||
scene: string;
|
||||
poses: ReadonlyArray<object>;
|
||||
}>;
|
||||
/** Why a renderer and context cannot draw a scene; null when they can. */
|
||||
export function sceneSupport(
|
||||
scene: ReferenceScene,
|
||||
renderer: Renderer,
|
||||
ctx?: { assets?: Record<string, unknown> },
|
||||
): string | null;
|
||||
|
||||
export const VISUAL_TOLERANCE: Readonly<{
|
||||
threshold: number;
|
||||
maxSolidPixels: number;
|
||||
maxMismatchedPixels: number;
|
||||
}>;
|
||||
type Pixels = { width: number; height: number; data: Uint8ClampedArray };
|
||||
export function compareImages(
|
||||
actual: Pixels,
|
||||
expected: Pixels,
|
||||
options?: {
|
||||
threshold?: number;
|
||||
maxSolidPixels?: number;
|
||||
maxMismatchedPixels?: number;
|
||||
diff?: Uint8ClampedArray;
|
||||
},
|
||||
): {
|
||||
match: boolean;
|
||||
diffPixels: number;
|
||||
diffFraction: number;
|
||||
solidPixels: number;
|
||||
mismatchedPixels: number;
|
||||
reason?: string;
|
||||
};
|
||||
/** Draws a scene, then each of its views once the renderer has settled. */
|
||||
export function drawScene(
|
||||
renderer: Renderer,
|
||||
scene: ReferenceScene,
|
||||
ctx: { toEcef: Function; assets?: object },
|
||||
onView: (
|
||||
view: { name: string },
|
||||
capture: Blob,
|
||||
settle: { state: string; blockers: string[] },
|
||||
) => void | Promise<void>,
|
||||
): Promise<void>;
|
||||
/** The file a view's reference image is stored under. */
|
||||
export function referenceName(sceneId: string, viewName: string): string;
|
||||
|
||||
export function contractDriver(
|
||||
renderer: Renderer,
|
||||
hooks: {
|
||||
frame: () => void | Promise<void>;
|
||||
toEcef: (p: object) => Ecef;
|
||||
pointer?: (
|
||||
type: string,
|
||||
x: number,
|
||||
y: number,
|
||||
extra: object,
|
||||
) => void | Promise<void>;
|
||||
},
|
||||
): CameraDriver;
|
||||
export function runCameraScript(
|
||||
driver: CameraDriver,
|
||||
script: CameraScript,
|
||||
): Promise<{ records: object[]; flights: object[] }>;
|
||||
/** The parts of a pose a trace keeps. */
|
||||
export function tracePose(pose: CameraPose): object;
|
||||
|
||||
/** The suite's assertions. */
|
||||
export namespace expect {
|
||||
class ConformanceError extends Error {}
|
||||
function ok(value: unknown, message: string): void;
|
||||
function equal(actual: unknown, expected: unknown, message: string): void;
|
||||
function deepEqual(actual: unknown, expected: unknown, message: string): void;
|
||||
function near(
|
||||
actual: number,
|
||||
expected: number,
|
||||
tolerance: number,
|
||||
message: string,
|
||||
): void;
|
||||
function nearAngle(
|
||||
actual: number,
|
||||
expected: number,
|
||||
tolerance: number,
|
||||
message: string,
|
||||
): void;
|
||||
function nearVec(
|
||||
actual: { x: number; y: number; z: number },
|
||||
expected: { x: number; y: number; z: number },
|
||||
tolerance: number,
|
||||
message: string,
|
||||
): void;
|
||||
function rejects(
|
||||
promiseOrFn: Promise<unknown> | (() => Promise<unknown>),
|
||||
message: string,
|
||||
): Promise<void>;
|
||||
function throws(fn: () => unknown, message: string): void;
|
||||
}
|
||||
@@ -21,7 +21,8 @@
|
||||
* Optional harness members widen what is checked: `pointer(r, type, x, y)`
|
||||
* (synthetic input; with `cameraInput`, the camera scripts' drags and
|
||||
* wheels too), `scriptHeights(r, fn)` (heights from a function),
|
||||
* `wallTime(r)` (the wall clock a `live` motion clock reads), `pixels`
|
||||
* `wallTime(r)` (the wall clock a `live` motion clock reads),
|
||||
* `resizeContainer(r, size)` (sizes the element the renderer fills), `pixels`
|
||||
* (false skips the checks that read drawn pixels),
|
||||
* `assets.model` (a glTF URL). `create` may return null when it cannot
|
||||
* make a renderer with fewer capabilities; those checks are then skipped.
|
||||
@@ -55,6 +56,7 @@ import { portChecks } from './checks/ports.js';
|
||||
* @property {boolean} [cameraInput] The renderer's camera moves on pointer input sent through `pointer` (its own gestures, or a camera controller's): the camera scripts with `input` steps run.
|
||||
* @property {(r: object, fn: (point: {lon: number, lat: number}, against?: string) => number|null) => void} [scriptHeights]
|
||||
* @property {(r: object) => number} [wallTime] Epoch ms the renderer's `live` motion clock reads.
|
||||
* @property {(r: object, size: {width: number, height: number}) => void|Promise<void>} [resizeContainer] Sizes the element the renderer fills, in CSS pixels, for the check that `resize` follows it.
|
||||
* @property {{model?: string, missingModel?: string, modelBytes?: () => Promise<Uint8Array>}} [assets] `modelBytes`: the bytes of a model, for the check that a model given its bytes never fetches its url.
|
||||
*/
|
||||
|
||||
|
||||
Vendored
+77
-2
@@ -30,12 +30,15 @@ import type {
|
||||
GeoRect,
|
||||
HeadingPitchRange,
|
||||
HeadingPitchRoll,
|
||||
LonLat,
|
||||
Off,
|
||||
Position,
|
||||
Release,
|
||||
Sphere,
|
||||
Vec3,
|
||||
} from './common';
|
||||
import type { PointerEv, PointerEventType } from './input';
|
||||
import type { HeightOptions } from './query';
|
||||
|
||||
export interface CameraPose {
|
||||
lon: number;
|
||||
@@ -297,6 +300,7 @@ export interface CameraPort {
|
||||
* reading is valid only for the tick it is read in. `setView` places a
|
||||
* world pose and keeps this frame, so code can re-express an offset in
|
||||
* the follow's own frame, whichever frame that is, and place the eye there.
|
||||
* Read-only, handed again while it holds, as `matrices()` are.
|
||||
*/
|
||||
followFrame?(): Float64Array;
|
||||
readonly controls: CameraControls;
|
||||
@@ -313,7 +317,78 @@ export interface CameraPort {
|
||||
* Column-major, right-handed: `view` takes ECEF to eye space (absolute,
|
||||
* not eye-relative); `projection` takes eye space to clip space with depth
|
||||
* in [-1, 1]. A renderer with an infinite far plane returns the
|
||||
* infinite-far form, and `pose().far` is `Infinity`.
|
||||
* infinite-far form, and `pose().far` is `Infinity`. Read-only: a
|
||||
* renderer may hand the same arrays again while they hold, and hands new
|
||||
* ones once they change (one kept from an earlier frame stays as it was).
|
||||
*/
|
||||
matrices(): { view: Float64Array; projection: Float64Array };
|
||||
matrices(): {
|
||||
readonly view: Float64Array;
|
||||
readonly projection: Float64Array;
|
||||
};
|
||||
}
|
||||
|
||||
/** A camera controller's frame tick: the loop's clock and the scene time. */
|
||||
export interface CameraTick {
|
||||
/** The loop's clock, ms, on the `performance.now()` timeline. */
|
||||
now: number;
|
||||
/** Scene time, epoch ms. */
|
||||
time: number;
|
||||
}
|
||||
|
||||
/** The eye a camera controller writes, in ECEF; `fovy` vertical, radians. */
|
||||
export interface ControllerEye {
|
||||
position: Ecef;
|
||||
direction: Ecef;
|
||||
up: Ecef;
|
||||
right: Ecef;
|
||||
fovy: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera a renderer hands a camera controller: it reads and writes the
|
||||
* eye exactly, says the canvas's CSS size, and lends the query, draw and
|
||||
* frame ports' members the controller needs.
|
||||
*/
|
||||
export interface NativeCamera {
|
||||
pose(): {
|
||||
position: Ecef;
|
||||
direction: Ecef;
|
||||
up: Ecef;
|
||||
near: number;
|
||||
far: number;
|
||||
};
|
||||
setPose(eye: ControllerEye): void;
|
||||
viewport(): { width: number; height: number };
|
||||
sampleHeightNow?(point: LonLat, options?: HeightOptions): number | null;
|
||||
pickPosition?(x: number, y: number): Ecef | null;
|
||||
/** Where the draw port draws an item it moves itself. */
|
||||
itemPosition?(
|
||||
item: { set: string; id: string | number },
|
||||
aheadMs?: number,
|
||||
): Ecef | null;
|
||||
requestRender?(reason: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A camera controller, as an application hands one to a renderer without a
|
||||
* camera of its own (or in place of its own): given the native camera, the
|
||||
* input port's pointer events and the page's keys, it makes the camera port.
|
||||
* The renderer runs `frame.beforeUpdate` before its `preUpdate` listeners
|
||||
* and `frame.afterUpdate` after them, each tick, drawn or not.
|
||||
*/
|
||||
export type CameraControllerFactory = (options: {
|
||||
native: NativeCamera;
|
||||
input?: {
|
||||
on(type: PointerEventType, cb: (event: PointerEv) => void): Off;
|
||||
};
|
||||
report?: (error: unknown) => void;
|
||||
keyTarget?: EventTarget;
|
||||
thresholds?: boolean;
|
||||
}) => {
|
||||
port: CameraPort;
|
||||
frame: {
|
||||
beforeUpdate(tick: CameraTick): void;
|
||||
afterUpdate(tick: CameraTick): void;
|
||||
};
|
||||
destroy(): void;
|
||||
};
|
||||
Vendored
+6
-1
@@ -121,7 +121,12 @@ export type Off = () => void;
|
||||
/** Gives back a hold. Calling it twice is harmless. */
|
||||
export type Release = () => void;
|
||||
|
||||
/** A handle on something the renderer draws. */
|
||||
/**
|
||||
* A handle on something the renderer draws. Once disposed, and once the
|
||||
* renderer is destroyed, it does nothing: its methods neither draw nor
|
||||
* throw, and a set or field asked for after destroy is such a handle.
|
||||
* Disposing it again is harmless.
|
||||
*/
|
||||
export interface Handle {
|
||||
show: boolean;
|
||||
dispose(): void;
|
||||
|
||||
Vendored
+44
-3
@@ -55,6 +55,35 @@ export interface ClusterSpec {
|
||||
icon?: (count: number) => ImageRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* `recede`: a set's items shrink and fade toward the globe's limb, as
|
||||
* `src/render/recession.js` (exported as `render/recession`) works it out,
|
||||
* so the renderer draws exactly those factors. Nearer than `startLimbRatio` of
|
||||
* the eye's distance to the limb an item is drawn as it is; from there it
|
||||
* eases (smoothstep) to `scaleFloor` times its scale and `alphaFloor` haze
|
||||
* at the limb and beyond. All of it eases back to nothing as the eye climbs
|
||||
* from `globeViewBlendStartM` to `globeViewBlendEndM` above the ellipsoid.
|
||||
* An item draws at its alpha times `max(combinedAlphaFloor, focus × haze)`,
|
||||
* that floor holding even while nothing recedes. Icons shrink and fade;
|
||||
* models only fade. Every parameter is optional, the defaults in brackets.
|
||||
*/
|
||||
export interface RecedeSpec {
|
||||
/** Where receding starts, as a share of the limb's distance [0.5]. */
|
||||
startLimbRatio?: number;
|
||||
/** The scale an item reaches at the limb [0.45]; icons only. */
|
||||
scaleFloor?: number;
|
||||
/** The haze an item reaches at the limb [0.35]. */
|
||||
alphaFloor?: number;
|
||||
/** The least `focus × haze` draws with [0.2]. */
|
||||
combinedAlphaFloor?: number;
|
||||
/** Eye height above the ellipsoid where receding starts to ease off, metres [3,500,000]. */
|
||||
globeViewBlendStartM?: number;
|
||||
/** Eye height from which nothing recedes, metres [4,500,000]. */
|
||||
globeViewBlendEndM?: number;
|
||||
/** The radius of the sphere the limb is measured on, metres [6,378,137]. */
|
||||
earthRadiusM?: number;
|
||||
}
|
||||
|
||||
/** Options of a whole set; the mutable ones can change later through `setOptions`. */
|
||||
export interface SetSpec {
|
||||
/**
|
||||
@@ -66,6 +95,11 @@ export interface SetSpec {
|
||||
horizonCull?: boolean;
|
||||
/** `cluster`: screen-space clustering (icons only; see `ClusterSpec`). */
|
||||
cluster?: ClusterSpec | null;
|
||||
/**
|
||||
* Icons and models: the items recede toward the limb (`RecedeSpec`; `{}`
|
||||
* for the defaults). Omitted or `null`: they do not. Changes live.
|
||||
*/
|
||||
recede?: RecedeSpec | null;
|
||||
/**
|
||||
* How the set's items blend with what is drawn. Omitted: opaque parts
|
||||
* opaque with depth writes, items with alpha under 1 alpha-blended without
|
||||
@@ -212,9 +246,10 @@ export interface IconItem extends Placed {
|
||||
imageLod?: { near: ImageRef; switchPx: number };
|
||||
/** A larger invisible pick target, CSS pixels. */
|
||||
pickProxy?: { size: [width: number, height: number] };
|
||||
/** Fade and shrink toward the globe's limb. */
|
||||
recede?: boolean;
|
||||
/** Emphasis factor for a focused item, 1 = none. */
|
||||
/**
|
||||
* Emphasis for a focused item, 0..1, 1 = none: the alpha is multiplied by
|
||||
* it (in a set that recedes, as `RecedeSpec` says).
|
||||
*/
|
||||
focus?: number;
|
||||
}
|
||||
|
||||
@@ -409,6 +444,12 @@ export interface ModelItem extends Placed {
|
||||
* would not hide what lies below it). Can change live.
|
||||
*/
|
||||
clip?: 'belowOrigin';
|
||||
/**
|
||||
* Emphasis for a focused model, 0..1, 1 = none: the tint's alpha is
|
||||
* multiplied by it (in a set that recedes, as `RecedeSpec` says). Can
|
||||
* change live.
|
||||
*/
|
||||
focus?: number;
|
||||
}
|
||||
|
||||
/** A plane showing an image, a video or a canvas. */
|
||||
|
||||
Vendored
+5
-1
@@ -84,7 +84,11 @@ export interface FramePort {
|
||||
* the animation frames the loop runs on.
|
||||
*/
|
||||
renderNow(options?: { ifDue?: boolean }): void;
|
||||
/** Resolves after the next frame has been drawn and presented. */
|
||||
/**
|
||||
* Resolves after the next frame has been drawn and presented. Once the
|
||||
* renderer is destroyed it rejects with a "renderer destroyed" error, and
|
||||
* so does one still waiting when the renderer is destroyed.
|
||||
*/
|
||||
renderOnce(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/** Cap the loop's rate; 0 is the display's rate. */
|
||||
setTargetFps(fps: number): void;
|
||||
|
||||
Vendored
+11
-2
@@ -93,7 +93,12 @@ export interface InputPort {
|
||||
options?: { lease?: Lease | (() => Lease | null) },
|
||||
): Off;
|
||||
/**
|
||||
* Take the pointer for a tool. A new claim ends the previous lease.
|
||||
* Take the pointer for a tool. 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 (its button, a half-drawn
|
||||
* shape). A lease its holder releases, or that has already ended, is never
|
||||
* told, and releasing an ended lease frees nothing. An `onLost` that throws
|
||||
* is reported.
|
||||
* `grab` decides each press from its `down` event, synchronously: true
|
||||
* makes it the tool's, anything else leaves it. A `down` carries no pick,
|
||||
* so `grab` decides from the position, button and modifiers (and the
|
||||
@@ -103,7 +108,11 @@ export interface InputPort {
|
||||
*/
|
||||
claimPointer(
|
||||
owner: string,
|
||||
options?: { grab?: (down: PointerEv) => boolean },
|
||||
options?: {
|
||||
grab?: (down: PointerEv) => boolean;
|
||||
/** Called once when a newer claim ends this lease. */
|
||||
onLost?: () => void;
|
||||
},
|
||||
): Lease;
|
||||
isPointerFree(): boolean;
|
||||
/** Suspend user camera input until released. Holds are counted. */
|
||||
|
||||
Vendored
+2
-1
@@ -82,7 +82,8 @@ export interface QueryPort {
|
||||
pickEllipsoid(x: number, y: number): Ecef | null;
|
||||
/** Where a ray meets the globe surface (not tiles). */
|
||||
pickGlobe(ray: Ray): Ecef | null;
|
||||
pickRay(x: number, y: number): Ray;
|
||||
/** Null while the canvas has no size (hidden, not laid out yet). */
|
||||
pickRay(x: number, y: number): Ray | null;
|
||||
/** Screen position, or null behind the eye (off-screen points still answer). */
|
||||
project(position: Ecef): ScreenXY | null;
|
||||
/**
|
||||
|
||||
Vendored
+14
-6
@@ -104,16 +104,16 @@ export interface CreateOptions {
|
||||
worldDataToken?: string;
|
||||
/** Initial multisampling; quality can change it later. */
|
||||
msaa?: 0 | 2 | 4 | 8;
|
||||
/** Keep the drawing buffer after presenting, for capture. */
|
||||
preserveDrawingBuffer?: boolean;
|
||||
/** Sky applied before the first frame, so nothing draws in the wrong sky. */
|
||||
sky?: Partial<SkySettings>;
|
||||
/** Scene time in epoch ms. The application passes its boot time. */
|
||||
time?: number;
|
||||
/**
|
||||
* The clocks the renderer reads, for flights, inertia, tweens and
|
||||
* `FrameTime.now`: `now` on the `performance.now()` timeline, `date` in
|
||||
* epoch ms. Omitted: the browser's. Tests pass virtual ones.
|
||||
* The clocks the renderer reads, for `FrameTime.now`, the camera's
|
||||
* `moveEnd` wait, input, flights and tweens, and for inertia where it
|
||||
* times that itself (Cesium's keeps Cesium's own timing): `now` on the
|
||||
* `performance.now()` timeline, `date` in epoch ms. Omitted: the
|
||||
* browser's. Tests pass virtual ones.
|
||||
*/
|
||||
clock?: { now(): number; date(): number };
|
||||
/** Aborts creation; the renderer cleans up whatever it had built. */
|
||||
@@ -149,7 +149,10 @@ export interface Renderer {
|
||||
readonly effects: EffectsPort;
|
||||
readonly credits: CreditsPort;
|
||||
readonly quality: QualityPort;
|
||||
/** The last presented frame as an encoded image. */
|
||||
/**
|
||||
* The last presented frame as an encoded image. Once the renderer is
|
||||
* destroyed it rejects with a "renderer destroyed" error.
|
||||
*/
|
||||
capture(options?: CaptureOptions): Promise<Blob>;
|
||||
/**
|
||||
* The last presented frame's pixels, synchronously, for loops that render
|
||||
@@ -175,5 +178,10 @@ export interface Renderer {
|
||||
* a new renderer.
|
||||
*/
|
||||
on(event: 'contextLost' | 'contextRestored', cb: () => void): Off;
|
||||
/**
|
||||
* Lets go of everything. Afterwards handles do nothing (`Handle`), and
|
||||
* `frame.renderOnce` and `capture` reject with a "renderer destroyed"
|
||||
* error, as does a `renderOnce` still waiting.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Who hears each pointer event: the contract's input rules
|
||||
* (`router.js`).
|
||||
*/
|
||||
import type { InputPort, Lease, PointerEv } from '../contract/index';
|
||||
|
||||
/** Who an event went to: one lease's listeners, everyone else, or both. */
|
||||
export interface Recipients {
|
||||
lease: Lease | null;
|
||||
ambient: boolean;
|
||||
}
|
||||
|
||||
export interface InputRouter {
|
||||
/** The input port the router keeps. */
|
||||
port: InputPort;
|
||||
/**
|
||||
* Delivers one event to the listeners it belongs to. `before` runs first
|
||||
* with who it goes to (a renderer's stock behaviours); its error is
|
||||
* reported. A `move` or `up` always reads as going to both.
|
||||
*/
|
||||
dispatch(ev: PointerEv, before?: (to: Recipients) => void): Recipients;
|
||||
/** Live listeners, for leak checks. */
|
||||
listenerCount(): number;
|
||||
/** Ends delivery: no listener runs again, even for the event under way. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createInputRouter(options: {
|
||||
/** Where a listener's or a `grab`'s error goes. */
|
||||
report: (error: unknown) => void;
|
||||
/** The renderer's counted camera-input hold. */
|
||||
suspendCamera: (reason: string) => () => void;
|
||||
/** Stock behaviours beyond `select` and `dblclickFollow`. */
|
||||
behaviours?: string[];
|
||||
/** Told when a behaviour turns off (first hold) or on (last release). */
|
||||
onBehaviour?: (name: string, enabled: boolean) => void;
|
||||
/** Behaviours the renderer cannot do, as `false`: listed, reported disabled. */
|
||||
supported?: Record<string, boolean>;
|
||||
}): InputRouter;
|
||||
@@ -74,6 +74,8 @@ export function createInputRouter({
|
||||
|
||||
/** Each lease's `grab`, or null when it takes every press. */
|
||||
const leaseGrab = new WeakMap();
|
||||
/** Each lease's ending by a newer claim, which hands back its `onLost`. */
|
||||
const endLease = new WeakMap();
|
||||
/**
|
||||
* The presses under way, by button, from their `down`: `owner` is the
|
||||
* lease each went to, or null when it went to everyone else. A press's
|
||||
@@ -96,9 +98,12 @@ export function createInputRouter({
|
||||
};
|
||||
},
|
||||
claimPointer(owner, opts = {}) {
|
||||
if (currentLease) currentLease.release();
|
||||
// The newest claim takes over. The lease it ends is told once, after
|
||||
// this one holds the pointer, so its holder turns itself off.
|
||||
const ended = currentLease ? endLease.get(currentLease)() : null;
|
||||
let released = false;
|
||||
const grab = typeof opts.grab === 'function' ? opts.grab : null;
|
||||
const onLost = typeof opts.onLost === 'function' ? opts.onLost : null;
|
||||
const lease = {
|
||||
owner: String(owner),
|
||||
get current() {
|
||||
@@ -110,8 +115,19 @@ export function createInputRouter({
|
||||
if (currentLease === lease) currentLease = null;
|
||||
},
|
||||
};
|
||||
// Ends it for a newer claim; returns who to tell.
|
||||
endLease.set(lease, () => {
|
||||
lease.release();
|
||||
return onLost;
|
||||
});
|
||||
currentLease = lease;
|
||||
leaseGrab.set(lease, grab);
|
||||
if (ended)
|
||||
try {
|
||||
ended();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
return lease;
|
||||
},
|
||||
isPointerFree: () => currentLease === null,
|
||||
|
||||
@@ -122,3 +122,43 @@ test('dispose ends delivery, even of the event under way', () => {
|
||||
assert.equal(lease.current, false, 'the lease ended');
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
});
|
||||
|
||||
test('a newer claim takes over and tells the lease it ended, once', () => {
|
||||
const { port, dispatch } = router();
|
||||
const lost = [];
|
||||
const a = port.claimPointer('a', { onLost: () => lost.push('a') });
|
||||
const heard = [];
|
||||
port.on('down', () => heard.push('a'), { lease: a });
|
||||
const b = port.claimPointer('b', {
|
||||
onLost: () => lost.push('b'),
|
||||
});
|
||||
port.on('down', () => heard.push('b'), { lease: b });
|
||||
assert.deepEqual(lost, ['a'], 'the old holder is told');
|
||||
assert.equal(a.current, false);
|
||||
assert.equal(b.current, true);
|
||||
dispatch(ev('down'));
|
||||
assert.deepEqual(heard, ['b'], 'the newest holder gets the press');
|
||||
a.release();
|
||||
assert.equal(b.current, true, "the old holder's late release frees nothing");
|
||||
assert.equal(port.isPointerFree(), false);
|
||||
assert.deepEqual(lost, ['a'], 'told once');
|
||||
b.release();
|
||||
assert.deepEqual(lost, ['a'], 'a holder that lets go is not told');
|
||||
assert.equal(port.isPointerFree(), true);
|
||||
});
|
||||
|
||||
test('the ended lease is told after the new one holds; its error is reported', () => {
|
||||
const errors = [];
|
||||
const { port } = router({ report: (error) => errors.push(error) });
|
||||
let seen = null;
|
||||
const a = port.claimPointer('a', {
|
||||
onLost: () => {
|
||||
seen = { free: port.isPointerFree(), current: a.current };
|
||||
throw new Error('onLost');
|
||||
},
|
||||
});
|
||||
const b = port.claimPointer('b');
|
||||
assert.deepEqual(seen, { free: false, current: false });
|
||||
assert.equal(b.current, true);
|
||||
assert.equal(errors.length, 1);
|
||||
});
|
||||
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Where an icon is drawn along its motion segment, and with what course
|
||||
* (`iconMotion.js`): where the renderer draws a moving icon.
|
||||
*/
|
||||
import type {
|
||||
CourseGlide,
|
||||
Ecef,
|
||||
MotionSegment,
|
||||
Position,
|
||||
} from '../contract/index';
|
||||
|
||||
/** Below this turn rate, rad/s, an arc is drawn as a straight line. */
|
||||
export const STRAIGHT_BELOW_RAD_PER_S: number;
|
||||
/** The shortest a lerp runs, ms: one with no length steps. */
|
||||
export const LERP_STEP_MS: number;
|
||||
/** An angle in degrees, wrapped into (-180, 180]. */
|
||||
export function norm180(deg: number): number;
|
||||
/** An angle in degrees, wrapped into [0, 360). */
|
||||
export function norm360(deg: number): number;
|
||||
/** Where `segment` puts an icon at `t` (epoch ms), from its own `pos`. */
|
||||
export function motionPosition(
|
||||
segment: MotionSegment | undefined,
|
||||
pos: Position,
|
||||
t: number,
|
||||
): Ecef;
|
||||
/** How far, degrees in (-180, 180], a glide starts from its segment's course. */
|
||||
export function glideOffset(
|
||||
segment: MotionSegment | undefined,
|
||||
course: number | undefined,
|
||||
glide: CourseGlide,
|
||||
): number;
|
||||
/** The course drawn at `t`, degrees clockwise from north in [0, 360). */
|
||||
export function motionCourse(
|
||||
segment: MotionSegment | undefined,
|
||||
course: number | undefined,
|
||||
t: number,
|
||||
glide?: CourseGlide,
|
||||
): number;
|
||||
/** Where an icon item is drawn at `t` (epoch ms on its set's motion clock). */
|
||||
export function iconPosition(
|
||||
item: { pos: Position; motion?: MotionSegment },
|
||||
t: number,
|
||||
): Ecef;
|
||||
/** The course an icon item is drawn with at `t`. */
|
||||
export function iconCourse(
|
||||
item: { course?: number; motion?: MotionSegment; courseGlide?: CourseGlide },
|
||||
t: number,
|
||||
): number;
|
||||
/** Until when, epoch ms, an item's drawn position or course may change. */
|
||||
export function motionEndsAt(item: {
|
||||
motion?: MotionSegment;
|
||||
courseGlide?: CourseGlide;
|
||||
}): number;
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* The Cesium-free modules the package exports: each
|
||||
* export names a module that imports no engine, has declarations beside it
|
||||
* that say every name it exports and no other, and type-checks when imported
|
||||
* through the package's exports.
|
||||
*/
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import ts from 'typescript';
|
||||
|
||||
const ROOT = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
'../..',
|
||||
);
|
||||
const PKG = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
||||
|
||||
/** The Cesium-free exports, with declarations. */
|
||||
const NEUTRAL = [
|
||||
'./render/contract',
|
||||
'./render/conformance',
|
||||
'./render/input/router',
|
||||
'./render/stub/camera',
|
||||
'./render/stub/viewRectangle',
|
||||
'./render/stub/harness',
|
||||
'./render/motion',
|
||||
'./render/vectorBase',
|
||||
'./render/iconSegment',
|
||||
'./render/recession',
|
||||
'./render/windStreamlines',
|
||||
'./render/weather',
|
||||
'./weather/effects',
|
||||
'./geo/screenCluster',
|
||||
];
|
||||
|
||||
const fileOf = (key) => path.join(ROOT, PKG.exports[key]);
|
||||
const declarationOf = (key) => fileOf(key).replace(/\.js$/, '.d.ts');
|
||||
|
||||
test('each Cesium-free export is declared, beside its module', () => {
|
||||
for (const key of NEUTRAL) {
|
||||
assert.equal(typeof PKG.exports[key], 'string', `${key} is exported`);
|
||||
assert.doesNotThrow(
|
||||
() => readFileSync(declarationOf(key)),
|
||||
`${key} has declarations`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('each one names in its declarations exactly what its module exports', async () => {
|
||||
for (const key of NEUTRAL) {
|
||||
const runtime = Object.keys(await import(pathToFileURL(fileOf(key)).href))
|
||||
.filter((name) => name !== 'default')
|
||||
.sort();
|
||||
const source = ts.createSourceFile(
|
||||
declarationOf(key),
|
||||
readFileSync(declarationOf(key), 'utf8'),
|
||||
ts.ScriptTarget.ES2022,
|
||||
);
|
||||
// Values only: types and interfaces have no runtime name. A module that
|
||||
// re-exports another's declarations (`export *`) is checked through it.
|
||||
if (
|
||||
source.statements.some(
|
||||
(s) => ts.isExportDeclaration(s) && !s.exportClause,
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const declared = [];
|
||||
for (const s of source.statements) {
|
||||
const exported = s.modifiers?.some(
|
||||
(m) => m.kind === ts.SyntaxKind.ExportKeyword,
|
||||
);
|
||||
if (!exported) continue;
|
||||
if (
|
||||
ts.isFunctionDeclaration(s) ||
|
||||
ts.isClassDeclaration(s) ||
|
||||
ts.isModuleDeclaration(s)
|
||||
)
|
||||
declared.push(s.name.text);
|
||||
else if (ts.isVariableStatement(s))
|
||||
for (const d of s.declarationList.declarations)
|
||||
declared.push(d.name.text);
|
||||
}
|
||||
assert.deepEqual([...new Set(declared)].sort(), runtime, key);
|
||||
}
|
||||
});
|
||||
|
||||
test('they type-check under strict TypeScript, imported by their package names', () => {
|
||||
const probe = path.join(ROOT, 'src/render/neutralExports.probe.ts');
|
||||
const lines = NEUTRAL.map(
|
||||
(key, i) =>
|
||||
`import * as m${i} from '${PKG.name}${key.slice(1)}';\nvoid m${i};`,
|
||||
);
|
||||
const host = ts.createCompilerHost({});
|
||||
const read = host.readFile;
|
||||
host.readFile = (file) =>
|
||||
path.resolve(file) === probe ? lines.join('\n') : read(file);
|
||||
const exists = host.fileExists;
|
||||
host.fileExists = (file) => path.resolve(file) === probe || exists(file);
|
||||
const program = ts.createProgram(
|
||||
[probe],
|
||||
{
|
||||
strict: true,
|
||||
noEmit: true,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
module: ts.ModuleKind.ESNext,
|
||||
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
||||
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
|
||||
types: [],
|
||||
allowJs: false,
|
||||
},
|
||||
host,
|
||||
);
|
||||
const problems = ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
|
||||
assert.deepEqual(problems, []);
|
||||
// Each resolved to its declarations, not to an untyped module.
|
||||
for (const key of NEUTRAL)
|
||||
assert.ok(
|
||||
program.getSourceFile(declarationOf(key)),
|
||||
`${key} resolves to its declarations`,
|
||||
);
|
||||
});
|
||||
|
||||
test('none of them reaches Cesium', () => {
|
||||
const engines = /from ['"]cesium['"]/;
|
||||
const seen = new Set();
|
||||
const walk = (file) => {
|
||||
if (seen.has(file)) return;
|
||||
seen.add(file);
|
||||
const text = readFileSync(file, 'utf8');
|
||||
assert.doesNotMatch(text, engines, path.relative(ROOT, file));
|
||||
for (const [, spec] of text.matchAll(
|
||||
/(?:from|import)\s*['"](\.[^'"]+)['"]/g,
|
||||
))
|
||||
walk(path.resolve(path.dirname(file), spec));
|
||||
};
|
||||
for (const key of NEUTRAL) walk(fileOf(key));
|
||||
});
|
||||
|
||||
test('a camera controller written against the contract reads its pointer events', () => {
|
||||
const probe = path.join(ROOT, 'src/render/controllerFactory.probe.ts');
|
||||
const text = `
|
||||
import type { CameraControllerFactory, CameraPort } from '${PKG.name}/render/contract';
|
||||
declare const port: CameraPort;
|
||||
export const controller: CameraControllerFactory = ({ native, input }) => {
|
||||
const off = input?.on('move', (event) => {
|
||||
const [x, y] = [event.position.x, event.position.y];
|
||||
void [x, y, event.type, native.viewport().width];
|
||||
});
|
||||
return {
|
||||
port,
|
||||
frame: { beforeUpdate() {}, afterUpdate() {} },
|
||||
destroy: () => off?.(),
|
||||
};
|
||||
};
|
||||
`;
|
||||
const host = ts.createCompilerHost({});
|
||||
const read = host.readFile;
|
||||
host.readFile = (file) => (path.resolve(file) === probe ? text : read(file));
|
||||
const exists = host.fileExists;
|
||||
host.fileExists = (file) => path.resolve(file) === probe || exists(file);
|
||||
const program = ts.createProgram(
|
||||
[probe],
|
||||
{
|
||||
strict: true,
|
||||
noEmit: true,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
module: ts.ModuleKind.ESNext,
|
||||
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
||||
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
|
||||
types: [],
|
||||
},
|
||||
host,
|
||||
);
|
||||
const problems = ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
|
||||
assert.deepEqual(problems, []);
|
||||
});
|
||||
@@ -11,7 +11,7 @@ const FAR = 100_000;
|
||||
const WIDTH = 64;
|
||||
const HEIGHT = 32;
|
||||
|
||||
/** A depth texture of a frame drawn with three's log depth (near 0): left half a wall 400 m away, right half ground 500 m away. */
|
||||
/** A depth texture of a frame drawn with log depth and no near plane: left half a wall 400 m away, right half ground 500 m away. */
|
||||
function depthSource(gl, { webgl2 = true } = {}) {
|
||||
const texture = gl.createTexture();
|
||||
texture.image = rawDepthImage(WIDTH, HEIGHT, (column) =>
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user