From df1143485a21ffb3dabb219525d7cb11142912c6 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Fri, 6 Nov 2026 20:34:54 -0800 Subject: [PATCH] Draw the context rim through the renderer's draw port The Contacts layer's 250 km rim is now an outline-only ellipse in a draw set of its own, taken from drawOf(viewer) when it is first drawn: the same colour, height and radius, moved only after the subject travels 250 m, cleared with the subject and disposed with the layer. A rim drawn on another viewer is redrawn on the current one. The Cesium draw port draws the outlines of ellipses it does not clamp as the entities did, with an outline geometry. The layer's positions are plain ECEF from src/geo rather than Cesium objects, the compass reads the camera through its port's pose, and its flights go through cameraOf from the renderer bridge. Its four files leave the Cesium allow-list; a caller handing the layer a viewer of its own loads ./render/cesium/unbound first, as for earthquakes. --- src/data/militaryAwareness.test.mjs | 3 +- src/layers/awareness/anchor.test.mjs | 11 +- .../awareness/directionOverlay.test.mjs | 26 +-- src/layers/awareness/focus.js | 17 +- src/layers/awareness/index.js | 9 +- src/layers/awareness/lifecycle.js | 1 + src/layers/awareness/rendering.js | 161 ++++++++++-------- src/layers/awareness/state.js | 14 -- src/layers/awareness/subject.js | 41 +++-- src/render/cesium/draw.js | 56 ++++-- src/render/cesium/draw.test.mjs | 68 ++++++++ src/render/cesiumAllowList.json | 4 - src/render/unboundCamera.test.mjs | 1 + src/testSupport/fakeCameraPort.mjs | 14 +- 14 files changed, 272 insertions(+), 154 deletions(-) diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index ec401b3c9..e19c34bf9 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -49,6 +49,7 @@ import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js'; import { withEntityRecord } from './entityRecords.js'; import { framePortFor } from '../testSupport/fakeFramePort.mjs'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; const militaryAwarenessSource = readLayerSource( new URL('./militaryAwareness.js', import.meta.url), @@ -184,7 +185,7 @@ function installAwarenessRuntime({ }, container: new FakeElement(), }; - bindFakeCesiumCamera(viewer); + bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }); const layers = new Map( AWARENESS_DEPENDENCIES.map((layerId) => [ layerId, diff --git a/src/layers/awareness/anchor.test.mjs b/src/layers/awareness/anchor.test.mjs index 0f29fc331..0e0c9101f 100644 --- a/src/layers/awareness/anchor.test.mjs +++ b/src/layers/awareness/anchor.test.mjs @@ -43,7 +43,11 @@ test('passive Contacts releases its installation anchor and subject refresh cann const subject = createSubject({ state, services, parts }); subject.refreshSelectedSubject(); assert.equal(anchors.length, 1); - assert.ok(anchors[0] instanceof Cesium.Cartesian3); + assert.deepEqual( + { ...anchors[0] }, + { x: position.x, y: position.y, z: position.z }, + ); + assert.notEqual(anchors[0], position, 'a copy, not the subject’s own'); controls.setParams({ passive: true }); assert.equal(anchors.at(-1), null); const released = anchors.length; @@ -57,5 +61,8 @@ test('passive Contacts releases its installation anchor and subject refresh cann controls.setParams({ passive: false }); assert.equal(activations, 1); subject.refreshSelectedSubject(); - assert.ok(anchors.at(-1) instanceof Cesium.Cartesian3); + assert.deepEqual( + { ...anchors.at(-1) }, + { x: position.x, y: position.y, z: position.z }, + ); }); diff --git a/src/layers/awareness/directionOverlay.test.mjs b/src/layers/awareness/directionOverlay.test.mjs index 283c5e286..49989ad1c 100644 --- a/src/layers/awareness/directionOverlay.test.mjs +++ b/src/layers/awareness/directionOverlay.test.mjs @@ -11,22 +11,24 @@ import { useAwarenessDirectionStore } from '../../ui/stores/awarenessDirection.j import AwarenessDirection from '../../ui/views/panels/AwarenessDirection.vue'; import { createState } from './state.js'; import { createRendering } from './rendering.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; /** The rendering part over a subject with one military contact due east. */ function overlay(screenAngle) { const state = createState({ services: {} }); const container = document.body.appendChild(document.createElement('div')); const subject = Cesium.Cartesian3.fromDegrees(0, 0, 1000); + const camera = fakeCameraPort({ + pose: { heading: 0, right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } }, + }); + const viewer = { + container, + scene: { canvas: { clientWidth: 800, clientHeight: 600 } }, + }; + bindRenderer(viewer, { camera: camera.port }); Object.assign(state, { - viewer: { - container, - scene: { canvas: { clientWidth: 800, clientHeight: 600 } }, - camera: { - heading: 0, - rightWC: new Cesium.Cartesian3(0, 1, 0), - upWC: new Cesium.Cartesian3(0, 0, 1), - }, - }, + viewer, enabled: true, subject: { position: subject, layerId: 'military' }, results: { @@ -65,7 +67,7 @@ function overlay(screenAngle) { }, parts: {}, }); - return { state, container, rendering }; + return { state, container, rendering, camera }; } test('the overlay publishes the compass and the nearest contact bearings', () => { @@ -108,14 +110,14 @@ test('an unstable frame keeps the last stable bearing, until the overlay is remo { angle: 2, opacity: 0.5, stable: false }, ]; const previous = []; - const { state, rendering } = overlay((x, y, last) => { + const { state, rendering, camera } = overlay((x, y, last) => { previous.push(last); return answers.shift() ?? { angle: last ?? 0, opacity: 1, stable: true }; }); rendering.updateDirectionOverlay(); assert.equal(state.directionAngles[0], 1); // The heading turns, so the next frame recomputes the contact. - state.viewer.camera.heading = 0.1; + camera.setPose({ heading: 0.1 }); rendering.updateDirectionOverlay(); assert.equal(previous[1], 1, 'the unstable frame is given the last angle'); assert.equal(state.directionAngles[0], 1, 'and does not replace it'); diff --git a/src/layers/awareness/focus.js b/src/layers/awareness/focus.js index 448658775..0e32ec79f 100644 --- a/src/layers/awareness/focus.js +++ b/src/layers/awareness/focus.js @@ -1,6 +1,6 @@ -import * as Cesium from 'cesium'; import { VESSEL_FOCUS_RADIUS_M } from './policy.js'; -import { cameraOf } from '../../render/cesium/camera.js'; +import { cameraOf } from '../../render/rendererOf.js'; +import { clone, distance } from '../../geo/index.js'; export function createFocus({ state: layerState, services, parts, source }) { const flightsLayer = services.flights; @@ -75,7 +75,7 @@ export function createFocus({ state: layerState, services, parts, source }) { layerId, id: String(known.id || known.mmsi), label: known.label || known.name || known.callsign || String(id), - position: Cesium.Cartesian3.clone(known.position), + position: clone(known.position), }); return true; } @@ -107,7 +107,7 @@ export function createFocus({ state: layerState, services, parts, source }) { /** * Pick the observed candidate closest to the current view. This is intentionally * a navigation preference, not a risk, capability, or affiliation calculation. - * @param {Array<{position: Cesium.Cartesian3}>} candidates Observed candidates. + * @param {Array<{position: {x: number, y: number, z: number}}>} candidates Observed candidates. * @returns {Object|null} The best currently observable candidate. */ @@ -121,13 +121,10 @@ export function createFocus({ state: layerState, services, parts, source }) { let closestDistance = Infinity; for (const candidate of candidates) { if (!candidate?.position) continue; - const distance = Cesium.Cartesian3.distance( - cameraPosition, - candidate.position, - ); - if (Number.isFinite(distance) && distance < closestDistance) { + const metres = distance(cameraPosition, candidate.position); + if (Number.isFinite(metres) && metres < closestDistance) { closest = candidate; - closestDistance = distance; + closestDistance = metres; } } return closest; diff --git a/src/layers/awareness/index.js b/src/layers/awareness/index.js index 2efa7424d..6136d9d7c 100644 --- a/src/layers/awareness/index.js +++ b/src/layers/awareness/index.js @@ -13,7 +13,14 @@ import { createControls } from './controls.js'; import { createIngestion } from './ingestion.js'; import { createState } from './state.js'; -/** Construct one layer with its own scene state and supplied application services. */ +/** + * Construct one layer with its own scene state and supplied application services. + * + * Its context rim is a renderer draw set (`drawOf(viewer)`) and its flights + * go through `cameraOf`. Given a Cesium viewer with no + * renderer bound, the caller loads the package's `./render/cesium/unbound` + * export first. + */ export function createAwarenessLayer({ services, source }) { const state = createState({ services }); const parts = {}; diff --git a/src/layers/awareness/lifecycle.js b/src/layers/awareness/lifecycle.js index 925a3a9ca..139d35576 100644 --- a/src/layers/awareness/lifecycle.js +++ b/src/layers/awareness/lifecycle.js @@ -231,6 +231,7 @@ export function createLifecycle({ detachRuntimeListeners(); parts.panel.clearPanel(); parts.rendering.removeDirectionOverlay(); + parts.rendering.disposeVisual(); layerState.subjectListener = null; layerState.contextListener = null; layerState.clearListener = null; diff --git a/src/layers/awareness/rendering.js b/src/layers/awareness/rendering.js index f65def213..7e7d0751b 100644 --- a/src/layers/awareness/rendering.js +++ b/src/layers/awareness/rendering.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; import { createCyberSonarSampler, @@ -12,6 +11,21 @@ import { import { bearingBetweenCoordinates } from '../../cockpitMath.js'; import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js'; import { formatAwarenessDirection } from './presentation.js'; +import { drawOf, findCamera } from '../../render/rendererOf.js'; +import { + PI_OVER_TWO, + distance, + dot, + fromDegrees, + normalize, + sub, + toDegrees, + toLonLatH, + toRadians, +} from '../../geo/index.js'; + +/** Each instance's rim set id is its own. */ +let instances = 0; export function createRendering({ state: layerState, @@ -21,6 +35,9 @@ export function createRendering({ }) { const { getKeyholeGeometry, celestialScreenAngle } = services.geometry; const { governorRequestRender } = services.render; + const rimSetId = `awareness:${++instances}:rim`; + /** The context rim's draw set, and the viewer it draws on. */ + let rim = null; const CARDINALS = [ ['N', 0], @@ -146,9 +163,9 @@ export function createRendering({ 120, Math.min(geometry.radius - 48, geometry.radius * 0.66), ); - const cameraHeading = layerState.viewer.camera.heading || 0; - const headingDeg = - (Math.round(Cesium.Math.toDegrees(cameraHeading)) + 360) % 360; + const pose = findCamera(layerState.viewer)?.pose(); + const cameraHeading = pose?.heading || 0; + const headingDeg = (Math.round(toDegrees(cameraHeading)) + 360) % 360; const ring = { left: `${geometry.centerX - compassRadius}px`, top: `${geometry.centerY - compassRadius}px`, @@ -164,8 +181,8 @@ export function createRendering({ top: `${geometry.centerY - compassRadius + 39}px`, }; const labels = root.labels.map((label) => { - const bearing = Cesium.Math.toRadians(label.bearing); - const angle = bearing - cameraHeading - Cesium.Math.PI_OVER_TWO; + const bearing = toRadians(label.bearing); + const angle = bearing - cameraHeading - PI_OVER_TWO; const labelRadius = compassRadius - 17; return { ...label, @@ -193,19 +210,15 @@ export function createRendering({ marker.hidden = true; continue; } - const direction = Cesium.Cartesian3.subtract( - item.position, - layerState.subject.position, - layerState.DIRECTION_SCRATCH[index], - ); - if (Cesium.Cartesian3.magnitudeSquared(direction) < 1) { + const offset = sub(item.position, layerState.subject.position); + if (dot(offset, offset) < 1 || !pose) { marker.hidden = true; continue; } - Cesium.Cartesian3.normalize(direction, direction); + const direction = normalize(offset); const projection = celestialScreenAngle( - Cesium.Cartesian3.dot(direction, layerState.viewer.camera.rightWC), - Cesium.Cartesian3.dot(direction, layerState.viewer.camera.upWC), + dot(direction, pose.right), + dot(direction, pose.up), layerState.directionAngles[index], ); if (projection.stable) @@ -233,23 +246,15 @@ export function createRendering({ transform: `translate(-50%, -50%) translate(${-Math.cos(projection.angle) * 56}px, ${-Math.sin(projection.angle) * 56}px)`, }; const label = formatAwarenessLabel(item); - const subjectCartographic = Cesium.Cartographic.fromCartesian( - layerState.subject.position, - undefined, - layerState.SUBJECT_CARTOGRAPHIC_SCRATCH, - ); - const targetCartographic = Cesium.Cartographic.fromCartesian( - item.position, - undefined, - layerState.TARGET_CARTOGRAPHIC_SCRATCH[index], - ); + const subjectLocation = toLonLatH(layerState.subject.position); + const targetLocation = toLonLatH(item.position); const bearing = - subjectCartographic && targetCartographic + subjectLocation && targetLocation ? bearingBetweenCoordinates( - Cesium.Math.toDegrees(subjectCartographic.latitude), - Cesium.Math.toDegrees(subjectCartographic.longitude), - Cesium.Math.toDegrees(targetCartographic.latitude), - Cesium.Math.toDegrees(targetCartographic.longitude), + subjectLocation.lat, + subjectLocation.lon, + targetLocation.lat, + targetLocation.lon, ) : null; const bearingText = Number.isFinite(bearing) @@ -272,65 +277,72 @@ export function createRendering({ } function clearVisual() { - if (layerState.visual?.entities && layerState.viewer) { - for (const entity of layerState.visual.entities) - layerState.viewer.entities.remove(entity); + if (layerState.visual && rim) { + rim.set.clear(); // Idle mode renders only on request; a removed ring must not linger. governorRequestRender('awareness-visual'); } layerState.visual = null; } + /** Let the rim's draw set go, as the layer is destroyed. */ + function disposeVisual() { + clearVisual(); + rim?.set.dispose(); + rim = null; + } + + /** The rim's draw set on the current viewer, made on first use. */ + function rimSet() { + if (rim?.viewer !== layerState.viewer) { + rim?.set.dispose(); + rim = { + viewer: layerState.viewer, + set: drawOf(layerState.viewer).shapes({ id: rimSetId }), + }; + } + return rim.set; + } + + /** The awareness radius as an outlined ellipse around the subject's ground point. */ + function rimItem(lon, lat) { + return { + id: 'rim', + geometry: { + kind: 'ellipse', + center: { lon, lat, height: CONTEXT_RIM_HEIGHT_M }, + semiMajor: AWARENESS_RADIUS_M, + semiMinor: AWARENESS_RADIUS_M, + }, + fill: null, + outline: [0x62 / 255, 0xb5 / 255, 1, 0.72], + outlineOnly: true, + height: 'absolute', + }; + } + function renderVisual(subject) { if (!layerState.viewer || !subject?.position) return; - const cartographic = Cesium.Cartographic.fromCartesian(subject.position); - if (!cartographic) return; - const groundCenter = Cesium.Cartesian3.fromRadians( - cartographic.longitude, - cartographic.latitude, - 0, - ); + const location = toLonLatH(subject.position); + if (!location) return; + const { lon, lat } = location; + const groundCenter = fromDegrees(lon, lat, 0); const key = `${subject.layerId}:${subject.id}`; - if (layerState.visual?.key === key) { - // Large ellipse geometry is more reliable as a ConstantPositionProperty. - // Move it only after a meaningful displacement so live tracking does not - // churn ten large geometries for sub-pixel motion every 750 ms. - if ( - Cesium.Cartesian3.distance(layerState.visual.center, groundCenter) >= - 250 - ) { - for (const entity of layerState.visual.entities) - entity.position.setValue(groundCenter); - Cesium.Cartesian3.clone(groundCenter, layerState.visual.center); + // A rim drawn on another viewer (the layer re-initialized) is redrawn. + if (layerState.visual?.key === key && rim?.viewer === layerState.viewer) { + // Move the large ring only after a meaningful displacement so live + // tracking does not rebuild it for sub-pixel motion every 750 ms. + if (distance(layerState.visual.center, groundCenter) >= 250) { + rimSet().set([rimItem(lon, lat)]); + layerState.visual.center = groundCenter; // Content actually changed — buy exactly one frame instead of holding. governorRequestRender('awareness-visual'); } return; } clearVisual(); - - const entities = []; - - entities.push( - layerState.viewer.entities.add({ - position: groundCenter, - ellipse: { - semiMajorAxis: AWARENESS_RADIUS_M, - semiMinorAxis: AWARENESS_RADIUS_M, - fill: false, - outline: true, - outlineColor: - Cesium.Color.fromCssColorString('#62b5ff').withAlpha(0.72), - height: CONTEXT_RIM_HEIGHT_M, - }, - }), - ); - - layerState.visual = { - key, - entities, - center: Cesium.Cartesian3.clone(groundCenter), - }; + rimSet().set([rimItem(lon, lat)]); + layerState.visual = { key, center: groundCenter }; governorRequestRender('awareness-visual'); } return { @@ -342,6 +354,7 @@ export function createRendering({ cancelDirectionOverlayUpdate, updateDirectionOverlay, clearVisual, + disposeVisual, renderVisual, }; } diff --git a/src/layers/awareness/state.js b/src/layers/awareness/state.js index 5fd8bb912..3a35e107f 100644 --- a/src/layers/awareness/state.js +++ b/src/layers/awareness/state.js @@ -1,20 +1,6 @@ -import * as Cesium from 'cesium'; - export function createState({ services }) { const state = {}; - state.DIRECTION_SCRATCH = Array.from( - { length: 3 }, - () => new Cesium.Cartesian3(), - ); - - state.SUBJECT_CARTOGRAPHIC_SCRATCH = new Cesium.Cartographic(); - - state.TARGET_CARTOGRAPHIC_SCRATCH = Array.from( - { length: 3 }, - () => new Cesium.Cartographic(), - ); - Object.assign(state, { viewer: null, dataManager: null, diff --git a/src/layers/awareness/subject.js b/src/layers/awareness/subject.js index 732cc4bc1..5f9867502 100644 --- a/src/layers/awareness/subject.js +++ b/src/layers/awareness/subject.js @@ -3,8 +3,8 @@ import { AWARENESS_RADIUS_M, AWARENESS_RELATIONSHIP, } from '../../data/militaryAwarenessEngine.js'; -import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; +import { clone, distance, fromDegrees } from '../../geo/index.js'; import { AWARENESS_QUERY_LIMIT, SOURCE_LABEL, @@ -25,6 +25,8 @@ function localizeCoverageLabel(label) { return label; } +/** @typedef {import('../../render/contract/common').Ecef} Ecef */ + export function createSubject({ state: layerState, services, parts, source }) { const aisLiveVesselsLayer = services.vessels; const militaryInstallationsLayer = services.installations; @@ -184,10 +186,10 @@ export function createSubject({ state: layerState, services, parts, source }) { } /** - * Resolve the source-owned aircraft that currently owns Cesium tracking. + * Resolve the source-owned aircraft that currently owns the follow camera. * Both flight layers may briefly retain local state during a cross-layer * handoff, so the viewer's normalized tracked identity is the tie-breaker. - * @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null} + * @returns {{layerId: string, id: string, label: string, position: Ecef}|null} * Detached awareness subject, or null when no flight owns the follow camera. */ @@ -232,7 +234,7 @@ export function createSubject({ state: layerState, services, parts, source }) { subject, parts.history.historySourceItem(subject), ), - position: Cesium.Cartesian3.clone(subject.position), + position: clone(subject.position), }); layerState.navigationIndex = layerState.navigationHistory.length - 1; } @@ -247,10 +249,10 @@ export function createSubject({ state: layerState, services, parts, source }) { * Resolve the currently displayed position for a selected live subject. Flight * tracking owns the motion callback, so awareness consumes its cached display * position instead of creating a second tracker or extrapolation path. - * @param {{layerId: string, id: string, position: Cesium.Cartesian3}} subject Current subject. + * @param {{layerId: string, id: string, position: Ecef}} subject Current subject. * @param {object} [options] Position materialization controls. * @param {boolean} [options.allowCollectionMaterialization=true] Whether a layer-wide fallback may run. - * @returns {Cesium.Cartesian3|null} A cloned live position when one is available. + * @returns {Ecef|null} A cloned live position when one is available. */ function resolveSubjectPosition( @@ -263,7 +265,7 @@ export function createSubject({ state: layerState, services, parts, source }) { const trackedPosition = followed?.displayPosition?.(); if (trackedPosition) { return { - position: Cesium.Cartesian3.clone(trackedPosition), + position: clone(trackedPosition), // Only the follow camera's own contact proves presence this way; a // different tracked entity says nothing about this subject. presence: @@ -277,7 +279,7 @@ export function createSubject({ state: layerState, services, parts, source }) { // awareness position instead of allocating/scanning up to 1,000 contacts. if (!allowCollectionMaterialization) { return { - position: Cesium.Cartesian3.clone(subject.position), + position: clone(subject.position), presence: SUBJECT_PRESENCE.UNCHECKED, }; } @@ -292,7 +294,7 @@ export function createSubject({ state: layerState, services, parts, source }) { if (subject.layerId === 'ais-live-vessels') { if (!allowCollectionMaterialization) { return { - position: Cesium.Cartesian3.clone(subject.position), + position: clone(subject.position), presence: SUBJECT_PRESENCE.UNCHECKED, }; } @@ -305,7 +307,7 @@ export function createSubject({ state: layerState, services, parts, source }) { // Mapped installations come from static geometry, not a live feed: there is // nothing to be culled from. return { - position: Cesium.Cartesian3.clone(subject.position), + position: clone(subject.position), presence: SUBJECT_PRESENCE.LIVE, }; } @@ -319,10 +321,10 @@ export function createSubject({ state: layerState, services, parts, source }) { * ~11k contacts against a 1,000-row cap, so "not in the rows" is not "gone". * The rows are only consulted for a fresher position — a contact past the cap * keeps its last known position while still reading as present. - * @param {{id: string, position: Cesium.Cartesian3}} subject Current subject. - * @param {Array<{id: string, position: Cesium.Cartesian3}>} rows Live collection rows. + * @param {{id: string, position: Ecef}} subject Current subject. + * @param {Array<{id: string, position: Ecef}>} rows Live collection rows. * @param {{hasContact?: function}} layer The owning source layer. - * @returns {{position: Cesium.Cartesian3, presence: string}} Position plus presence verdict. + * @returns {{position: Ecef, presence: string}} Position plus presence verdict. */ function collectionSubjectPosition(subject, rows, layer) { @@ -340,8 +342,8 @@ export function createSubject({ state: layerState, services, parts, source }) { : SUBJECT_PRESENCE.UNCHECKED; return { position: current?.position - ? Cesium.Cartesian3.clone(current.position) - : Cesium.Cartesian3.clone(subject.position), + ? clone(current.position) + : clone(subject.position), presence, }; } @@ -402,7 +404,7 @@ export function createSubject({ state: layerState, services, parts, source }) { const labelChanged = nextLabel !== layerState.subject.label; layerState.subject = { ...layerState.subject, position, label: nextLabel }; const movementM = layerState.lastEvaluatedPosition - ? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position) + ? distance(layerState.lastEvaluatedPosition, position) : Infinity; if ( !parts.model.awarenessRefreshRequired({ @@ -426,10 +428,7 @@ export function createSubject({ state: layerState, services, parts, source }) { } layerState.results = evaluateSubject(layerState.subject, sources); layerState.sourceRevision = nextSourceRevision; - layerState.lastEvaluatedPosition = Cesium.Cartesian3.clone( - position, - layerState.lastEvaluatedPosition, - ); + layerState.lastEvaluatedPosition = clone(position); for (const cohort of layerState.results.cohorts) { const maxPage = Math.max( 0, @@ -461,7 +460,7 @@ export function createSubject({ state: layerState, services, parts, source }) { id: record.properties?.mmsi || record.id, label: record.label || record.id, memberNames: record.properties?.memberNames || [], - position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0), + position: fromDegrees(longitude, latitude, 0), }; } diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 9b77098bb..23d332a7f 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -706,17 +706,23 @@ export function createCesiumDraw({ scene, report }) { ring: outer, }; } - case 'ellipse': - return { - fill: new Cesium.EllipseGeometry({ - center: toCartesian(g.center), - semiMajorAxis: g.semiMajor, - semiMinorAxis: g.semiMinor, - rotation: g.rotation ?? 0, - height: heightOf(g.center), - extrudedHeight, - }), + case 'ellipse': { + const ellipse = { + center: toCartesian(g.center), + semiMajorAxis: g.semiMajor, + semiMinorAxis: g.semiMinor, + rotation: g.rotation ?? 0, + height: heightOf(g.center), + extrudedHeight, }; + return { + fill: new Cesium.EllipseGeometry(ellipse), + // Its outline is an outline geometry, as the entities' ellipses draw it. + outline: item.outline + ? new Cesium.EllipseOutlineGeometry(ellipse) + : undefined, + }; + } case 'rectangle': return { fill: new Cesium.RectangleGeometry({ @@ -878,7 +884,35 @@ export function createCesiumDraw({ scene, report }) { }), ); } - if (item.outline && shape.ring) + if (item.outline && shape.outline) { + const color = toColor(item.outline); + host.add( + new Cesium.Primitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry: shape.outline, + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), + }, + id, + }), + appearance: new Cesium.PerInstanceColorAppearance({ + flat: true, + translucent: color.alpha < 1, + renderState: { + // Clamped to what the context draws, as entities do. + lineWidth: + typeof scene.clampLineWidth === 'function' + ? scene.clampLineWidth(item.outlineWidth ?? 1) + : Math.min( + item.outlineWidth ?? 1, + scene.maximumAliasedLineWidth ?? 1, + ), + }, + }), + asynchronous: false, + }), + ); + } else if (item.outline && shape.ring) outlines.add({ positions: [...shape.ring, shape.ring[0]], width: item.outlineWidth ?? 1, diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 9ba356c15..b8cc01aec 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -931,3 +931,71 @@ test('the fires layer draws its heat cells as ground fills through the Cesium dr layer.destroy(viewer); assert.equal(grounds().length, 0); }); + +test('the context layer draws its rim as an outlined ellipse on a viewer of its own', async () => { + const { createRendering } = + await import('../../layers/awareness/rendering.js'); + const { createState } = await import('../../layers/awareness/state.js'); + const { scene } = drawOver(); + const state = createState({ services: {} }); + state.viewer = { scene }; + const rendering = createRendering({ + state, + services: { + geometry: {}, + render: { governorRequestRender() {} }, + }, + parts: {}, + }); + const subject = (lon) => ({ + layerId: 'military', + id: 'a', + position: Cesium.Cartesian3.fromDegrees(lon, 0, 9000), + }); + rendering.renderVisual(subject(0)); + const outlineOf = () => { + const [host] = scene.added; + const primitives = []; + for (let i = 0; i < host.length; i++) primitives.push(host.get(i)); + const outline = primitives.find( + (p) => + p instanceof Cesium.Primitive && + p.geometryInstances.geometry instanceof Cesium.EllipseOutlineGeometry, + ); + assert.ok(outline, 'an outline geometry, as the entity drew'); + assert.ok( + !primitives.some( + (p) => + p instanceof Cesium.Primitive && + p.geometryInstances.geometry instanceof Cesium.EllipseGeometry, + ), + 'and no fill', + ); + return outline; + }; + const outline = outlineOf(); + const { geometry, attributes } = outline.geometryInstances; + assert.equal(geometry._semiMajorAxis, 250_000); + assert.equal(geometry._height, 2_500); + const center = Cesium.Cartographic.fromCartesian(geometry._center); + assert.ok(Math.abs(center.longitude) < 1e-9); + assert.deepEqual( + [...attributes.color.value], + [0x62, 0xb5, 0xff, Math.round(0.72 * 255)], + ); + // Small moves keep the ring; one past 250 m moves it. + rendering.renderVisual(subject(0.001)); + assert.equal(outlineOf(), outline); + rendering.renderVisual(subject(0.01)); + assert.notEqual(outlineOf(), outline); + // Re-initialized on another viewer, the same subject's rim moves there. + const other = drawOver().scene; + state.viewer = { scene: other }; + rendering.renderVisual(subject(0.01)); + assert.equal(scene.added.length, 0, 'gone from the old viewer'); + assert.equal(other.added.length, 1, 'drawn on the new one'); + rendering.clearVisual(); + assert.equal(other.added[0].length, 1, 'only the empty polyline collection'); + rendering.disposeVisual(); + assert.equal(other.added.length, 0); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index d01749e65..ae6dfd8ce 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -45,10 +45,6 @@ "src/layers/alpr/overlay.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", - "src/layers/awareness/focus.js", - "src/layers/awareness/rendering.js", - "src/layers/awareness/state.js", - "src/layers/awareness/subject.js", "src/layers/cctv/cards.js", "src/layers/cctv/geometry.js", "src/layers/cctv/geometryQueue.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index c321e3215..974a48b02 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -69,6 +69,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/bikeshare', './layers/gnss', './layers/perimeters', + './layers/awareness', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/testSupport/fakeCameraPort.mjs b/src/testSupport/fakeCameraPort.mjs index d4e834cd7..03c8478fa 100644 --- a/src/testSupport/fakeCameraPort.mjs +++ b/src/testSupport/fakeCameraPort.mjs @@ -74,13 +74,15 @@ export function fakeCameraPort({ pose = {}, viewRectangle = null } = {}) { * `roll`) and events come from the fake's own `changed`, `moveStart` and * `moveEnd`. A fake with `trackedEntityChanged` and `entities` follows * through the port, as the renderer does. Its credits are the renderer's - * credits port over the fake's `creditDisplay`, if it has one. Binding a - * viewer twice keeps the first. Returns the viewer. + * credits port over the fake's `creditDisplay`, if it has one; `ports` + * adds other ports (a fake draw port, say). Binding a viewer twice keeps the + * first. Returns the viewer. * @template {{camera: object}} V * @param {V} viewer + * @param {object} [ports] * @returns {V} */ -export function bindFakeCesiumCamera(viewer) { +export function bindFakeCesiumCamera(viewer, ports = {}) { if (rendererOf(viewer)) return viewer; const fake = viewer.camera; const noEvent = { addEventListener: () => () => {} }; @@ -173,6 +175,10 @@ export function bindFakeCesiumCamera(viewer) { }, }, }); - bindRenderer(viewer, { camera: port, credits: fakeCesiumCredits(viewer) }); + bindRenderer(viewer, { + ...ports, + camera: port, + credits: fakeCesiumCredits(viewer), + }); return viewer; }