From a10f3a16e15e8f646004c8fa9c4d0c28eae47ac1 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 00:26:51 -0800 Subject: [PATCH] Read Street Level's camera and ground through the renderer's ports The Street Level view maths no longer reads Cesium. The camera's place comes from the camera port's pose; the visible box and the view focus cast the query port's screen rays and meet them with the ground, the WGS84 ellipsoid raised to the ground height, in geo; heights come from the query port; the horizon cull for the marker and the cones tests against an ellipsoid 1,000 m below WGS84 in geo and re-culls on the frame port's pre-render. Ground clicks, the screen-centre aim, the nearest-image point, photo framing, the coverage refresh and the ground re-measure read the same ports and convert positions with geo. geo's ellipsoid functions (toLonLatH, rayEllipsoid and those under them) and horizonFrom take an optional ellipsoid, made with ellipsoidOf or offsetEllipsoid; anything else, a map index included, means WGS84. Tests check them against Cesium on raised and lowered ellipsoids. view, index, cameraFraming, groundClick and selection leave the Cesium allow-list. The Street Level entries are Cesium-free callers of the unbound factories: given a viewer of a caller's own, with no renderer bound, the caller loads ./render/cesium/unbound first. GhostMaps, which uses the horizon cull and is still on the list, loads the camera factory itself. Differences the contract does not let us avoid: - The ground under the camera no longer reads whether the globe is shown (the globe port has no visibility getter). Where 3D tiles answer under the camera they decide, as they did under Google 3D; elsewhere the terrain answers, then the drawn surface below the camera. Over 3D tiles shown on a map with the globe (and under other primitives at the nadir) those now count as ground. - Without depth-texture support the query port answers no heights, the terrain included, so the ground then reads as the ellipsoid. - selection and groundClick still read the click dispatcher's own pick for now; they move to draw-set hits with the coverage lines. --- scripts/package-boundaries.json | 15 ++ src/geo/ellipsoid.js | 78 ++++-- src/geo/geo.test.mjs | 66 +++++ src/geo/horizon.js | 8 +- src/geo/horizon.test.mjs | 32 ++- src/layers/ghostMaps/index.js | 3 + src/layers/streetLevel/cameraFraming.js | 21 +- src/layers/streetLevel/groundClick.js | 15 +- src/layers/streetLevel/groundClick.test.mjs | 23 +- src/layers/streetLevel/index.js | 30 +-- src/layers/streetLevel/index.test.mjs | 6 +- src/layers/streetLevel/lineCoverage.js | 8 +- src/layers/streetLevel/lineCoverage.test.mjs | 10 +- src/layers/streetLevel/marker.test.mjs | 3 + .../providers/mapillary/provider.test.mjs | 6 +- src/layers/streetLevel/selection.js | 11 +- src/layers/streetLevel/sequenceCones.test.mjs | 3 + src/layers/streetLevel/view.js | 229 +++++++++--------- src/layers/streetLevel/view.test.mjs | 132 ++++++---- src/render/cesiumAllowList.json | 5 - src/render/unboundCamera.test.mjs | 4 + src/testSupport/streetLevelFakes.mjs | 119 +++++++-- 22 files changed, 567 insertions(+), 260 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 7da2ed81a..7a2558023 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2507,6 +2507,7 @@ "src/render/cesium/common.js", "src/layers/streetLevel/marker.js", "src/layers/streetLevel/view.js", + "src/geo/horizon.js", "src/layers/streetLevel/uiState.js", "src/layers/streetLevel/pickRouter.js", "src/data/idSwitches.js", @@ -5742,6 +5743,7 @@ "exports": ["./layers/ghostmaps"], "modules": [ "src/layers/ghostMaps/index.js", + "src/geo/index.js", "src/layers/ghostMaps/catalog.js", "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", @@ -5767,6 +5769,9 @@ "src/data/followed.js", "src/layers/streetLevel/tileMath.js", "src/layers/streetLevel/view.js", + "src/geo/ellipsoid.js", + "src/geo/horizon.js", + "src/geo/vector.js", "src/data/inputOwnership.js", "src/data/scenePick.js", "src/input/sensorPick.js", @@ -5774,6 +5779,16 @@ "src/data/pickRegistry.js", "src/input/dispatcher.js", "src/render/cesium/drawHit.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/query.js", + "src/render/cesium/draw.js", + "src/render/cesium/frame.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", diff --git a/src/geo/ellipsoid.js b/src/geo/ellipsoid.js index 6cd912846..2bc8d408e 100644 --- a/src/geo/ellipsoid.js +++ b/src/geo/ellipsoid.js @@ -47,11 +47,45 @@ export const WGS84 = Object.freeze({ }), }); +/** + * An ellipsoid with these radii, in the form `WGS84` has: for code that + * works on a surface other than WGS84 (the ground raised to a height, a + * horizon taken below it). Pass it as the trailing argument of the + * functions that take one. + * @param {{x: number, y: number, z: number}} radii + */ +export function ellipsoidOf({ x, y, z }) { + return Object.freeze({ + radii: Object.freeze({ x, y, z }), + radiiSquared: Object.freeze({ x: x * x, y: y * y, z: z * z }), + oneOverRadii: Object.freeze({ x: 1 / x, y: 1 / y, z: 1 / z }), + oneOverRadiiSquared: Object.freeze({ + x: 1 / (x * x), + y: 1 / (y * y), + z: 1 / (z * z), + }), + }); +} + +/** WGS84 with every radius `metres` longer (shorter, when negative). */ +export function offsetEllipsoid(metres) { + const { x, y, z } = WGS84.radii; + return ellipsoidOf({ x: x + metres, y: y + metres, z: z + metres }); +} + +/** + * The ellipsoid a trailing argument names: one from `ellipsoidOf`, else + * WGS84 (so these functions can still be handed to `map`, whose index + * lands there). + */ +const ellipsoidArg = (ellipsoid) => + ellipsoid?.oneOverRadiiSquared ? ellipsoid : WGS84; + const EPSILON12 = 1e-12; const CENTER_TOLERANCE_SQUARED = 0.1; -export function geodeticSurfaceNormal(p) { - const o = WGS84.oneOverRadiiSquared; +export function geodeticSurfaceNormal(p, ellipsoid) { + const o = ellipsoidArg(ellipsoid).oneOverRadiiSquared; return normalize(vec(p.x * o.x, p.y * o.y, p.z * o.z)); } @@ -77,11 +111,12 @@ export const fromDegrees = (lon, lat, height = 0) => fromRadians(toRadians(lon), toRadians(lat), height); /** The point on the ellipsoid along the geodetic normal, or null at the centre. */ -export function scaleToGeodeticSurface(p) { +export function scaleToGeodeticSurface(p, ellipsoid) { + const e = ellipsoidArg(ellipsoid); const { x: positionX, y: positionY, z: positionZ } = p; - const oneOverRadiiX = WGS84.oneOverRadii.x; - const oneOverRadiiY = WGS84.oneOverRadii.y; - const oneOverRadiiZ = WGS84.oneOverRadii.z; + const oneOverRadiiX = e.oneOverRadii.x; + const oneOverRadiiY = e.oneOverRadii.y; + const oneOverRadiiZ = e.oneOverRadii.z; const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX; const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY; const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ; @@ -91,9 +126,9 @@ export function scaleToGeodeticSurface(p) { if (squaredNorm < CENTER_TOLERANCE_SQUARED) return Number.isFinite(ratio) ? intersection : null; - const oneOverRadiiSquaredX = WGS84.oneOverRadiiSquared.x; - const oneOverRadiiSquaredY = WGS84.oneOverRadiiSquared.y; - const oneOverRadiiSquaredZ = WGS84.oneOverRadiiSquared.z; + const oneOverRadiiSquaredX = e.oneOverRadiiSquared.x; + const oneOverRadiiSquaredY = e.oneOverRadiiSquared.y; + const oneOverRadiiSquaredZ = e.oneOverRadiiSquared.z; const gradient = vec( intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, @@ -130,11 +165,14 @@ export function scaleToGeodeticSurface(p) { ); } -/** ECEF to geodetic `{lon, lat}` radians and `height` metres, or null at the centre. */ -export function toCartographicRadians(p) { - const surface = scaleToGeodeticSurface(p); +/** + * ECEF to geodetic `{lon, lat}` radians and `height` metres, or null at the + * centre; on `ellipsoid` (from `ellipsoidOf`) when given, else WGS84. + */ +export function toCartographicRadians(p, ellipsoid) { + const surface = scaleToGeodeticSurface(p, ellipsoid); if (!surface) return null; - const n = geodeticSurfaceNormal(surface); + const n = geodeticSurfaceNormal(surface, ellipsoid); const h = sub(p, surface); return { lon: Math.atan2(n.y, n.x), @@ -143,21 +181,23 @@ export function toCartographicRadians(p) { }; } -/** ECEF to `{lon, lat}` degrees and `height` metres. */ -export function toLonLatH(p) { - const c = toCartographicRadians(p); +/** ECEF to `{lon, lat}` degrees and `height` metres, on `ellipsoid` as `toCartographicRadians`. */ +export function toLonLatH(p, ellipsoid) { + const c = toCartographicRadians(p, ellipsoid); if (!c) return null; return { lon: toDegrees(c.lon), lat: toDegrees(c.lat), height: c.height }; } /** * Where a ray first meets the ellipsoid ahead of its origin, as Cesium's - * `camera.pickEllipsoid` takes the hit, or null when it misses. + * `camera.pickEllipsoid` takes the hit, or null when it misses; on + * `ellipsoid` (from `ellipsoidOf`) when given, else WGS84. * @param {{origin: {x: number, y: number, z: number}, * direction: {x: number, y: number, z: number}}} ray + * @param {typeof WGS84} [ellipsoid] */ -export function rayEllipsoid(ray) { - const r = WGS84.oneOverRadii; +export function rayEllipsoid(ray, ellipsoid) { + const r = ellipsoidArg(ellipsoid).oneOverRadii; const q = vec(ray.origin.x * r.x, ray.origin.y * r.y, ray.origin.z * r.z); const w = vec( ray.direction.x * r.x, diff --git a/src/geo/geo.test.mjs b/src/geo/geo.test.mjs index 31daebdd7..a502e0f34 100644 --- a/src/geo/geo.test.mjs +++ b/src/geo/geo.test.mjs @@ -6,9 +6,11 @@ import { distance, distanceSquared, eastNorthUp, + ellipsoidOf, fromDegrees, geodeticSurfaceNormal, lerpInto, + offsetEllipsoid, rayEllipsoid, scaleToGeodeticSurface, toCartographicRadians, @@ -245,3 +247,67 @@ test('in-place vector helpers match the default renderer bit for bit', () => { { ...Cesium.Cartesian3.lerp(ca, cb, 0.25, new Cesium.Cartesian3()) }, ); }); + +test('on another ellipsoid, rays and geodetic positions match the default renderer’s', () => { + const rand = random(7); + for (const metres of [1600, -1000, 30]) { + const ours = offsetEllipsoid(metres); + const theirs = new Cesium.Ellipsoid( + Cesium.Ellipsoid.WGS84.radii.x + metres, + Cesium.Ellipsoid.WGS84.radii.y + metres, + Cesium.Ellipsoid.WGS84.radii.z + metres, + ); + for (let i = 0; i < 200; i++) { + const origin = Cesium.Cartesian3.fromDegrees( + rand() * 360 - 180, + rand() * 170 - 85, + 100 + rand() * 2e5, + ); + const target = Cesium.Cartesian3.fromDegrees( + rand() * 360 - 180, + rand() * 170 - 85, + ); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, origin, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const ray = new Cesium.Ray(origin, direction); + const span = Cesium.IntersectionTests.rayEllipsoid(ray, theirs); + const hit = rayEllipsoid({ origin, direction }, ours); + if (!span) { + assert.equal(hit, null); + continue; + } + const expected = Cesium.Ray.getPoint( + ray, + span.start > 0 ? span.start : span.stop, + ); + assert.ok(distance(hit, expected) < 1e-3, `ray ${i} at ${metres} m`); + const carto = Cesium.Cartographic.fromCartesian(expected, theirs); + const deg = toLonLatH(expected, ours); + assert.ok(Math.abs(deg.lon - toDegrees(carto.longitude)) < 1e-9); + assert.ok(Math.abs(deg.lat - toDegrees(carto.latitude)) < 1e-9); + assert.ok(Math.abs(deg.height - carto.height) < 1e-3); + } + } +}); + +test('an ellipsoid argument that is not one (a map index) means WGS84', () => { + const p = fromDegrees(10, 20, 30); + assert.deepEqual(toLonLatH(p, 1), toLonLatH(p)); + assert.deepEqual( + rayEllipsoid( + { origin: { x: 1e7, y: 0, z: 0 }, direction: { x: -1, y: 0, z: 0 } }, + 0, + ), + rayEllipsoid({ + origin: { x: 1e7, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, + }), + ); + assert.deepEqual(ellipsoidOf({ x: 1, y: 2, z: 4 }).oneOverRadiiSquared, { + x: 1, + y: 0.25, + z: 0.0625, + }); +}); diff --git a/src/geo/horizon.js b/src/geo/horizon.js index a9ac89760..9d26d0668 100644 --- a/src/geo/horizon.js +++ b/src/geo/horizon.js @@ -8,10 +8,12 @@ import { WGS84 } from './ellipsoid.js'; /** * A horizon test from `eye` (ECEF): `isPointVisible(p)` is false for a - * point the ellipsoid hides from it. + * point the ellipsoid hides from it. `ellipsoid` (from `ellipsoidOf`) puts + * the horizon on another surface, as the occluder takes one. */ -export function horizonFrom(eye) { - const o = WGS84.oneOverRadii; +export function horizonFrom(eye, ellipsoid) { + // Anything but an ellipsoid (a map index, say) means WGS84. + const o = (ellipsoid?.oneOverRadii ? ellipsoid : WGS84).oneOverRadii; const cx = eye.x * o.x; const cy = eye.y * o.y; const cz = eye.z * o.z; diff --git a/src/geo/horizon.test.mjs b/src/geo/horizon.test.mjs index aa283a1a0..8a2416a9c 100644 --- a/src/geo/horizon.test.mjs +++ b/src/geo/horizon.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import test from 'node:test'; -import { fromDegrees } from './ellipsoid.js'; +import { fromDegrees, offsetEllipsoid } from './ellipsoid.js'; import { horizonFrom } from './horizon.js'; test('the horizon hides what the default renderer’s occluder hides', () => { @@ -31,3 +31,33 @@ test('the horizon hides what the default renderer’s occluder hides', () => { } } }); + +test('a horizon on a lowered ellipsoid hides what the occluder on it hides', () => { + let seed = 11; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const radii = Cesium.Ellipsoid.WGS84.radii; + const lowered = new Cesium.Ellipsoid( + radii.x - 1000, + radii.y - 1000, + radii.z - 1000, + ); + for (let i = 0; i < 30; i++) { + const eye = fromDegrees( + random() * 360 - 180, + random() * 170 - 85, + i === 0 ? -1500 : random() * 2e5 - 500, + ); + const occluder = new Cesium.EllipsoidalOccluder( + lowered, + new Cesium.Cartesian3(eye.x, eye.y, eye.z), + ); + const horizon = horizonFrom(eye, offsetEllipsoid(-1000)); + for (let k = 0; k < 50; k++) { + const p = fromDegrees(random() * 360 - 180, random() * 180 - 90, 0); + assert.equal( + horizon.isPointVisible(p), + occluder.isPointVisible(new Cesium.Cartesian3(p.x, p.y, p.z)), + ); + } + } +}); diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js index 81229696a..ee69a044d 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -15,6 +15,9 @@ import { tn, } from '../../i18n/index.js'; import { createHorizonCull } from '../streetLevel/view.js'; +// The horizon cull reads the camera and frame ports: a viewer of a +// caller's own gets them from the unbound factories this loads. +import '../../render/cesium/camera.js'; import { readGhostMapsKml } from './kml.js'; import { fieldLabel, parseDescriptionFields, wrapCardText } from './records.js'; import { inputFor as defaultInputFor } from '../../input/dispatcher.js'; diff --git a/src/layers/streetLevel/cameraFraming.js b/src/layers/streetLevel/cameraFraming.js index 67f206413..115418a58 100644 --- a/src/layers/streetLevel/cameraFraming.js +++ b/src/layers/streetLevel/cameraFraming.js @@ -1,7 +1,6 @@ -import * as Cesium from 'cesium'; import { plausibleSurfaceHeight, sampledSurfaceHeight } from './view.js'; -import { heightsFor } from '../../queries/heights.js'; -import { cameraOf } from '../../render/cesium/camera.js'; +import { toRadians } from '../../geo/index.js'; +import { cameraOf, findQuery } from '../../render/rendererOf.js'; /** Fly the globe camera once to frame a photo after it opens. */ export function createCameraFraming({ state }) { @@ -29,11 +28,13 @@ export function createCameraFraming({ state }) { * ellipsoid before tiles load, so only a plausible height counts. */ function groundHeightAt(lon, lat, fallback) { - const scene = state.viewer?.scene; - const carto = Cesium.Cartographic.fromDegrees(lon, lat); - let height = sampledSurfaceHeight(scene, carto); - if (height === null && scene) - height = heightsFor(scene).now(carto, { against: 'terrain' }); + const viewer = state.viewer; + const point = { lon, lat }; + let height = sampledSurfaceHeight(viewer, point); + if (height === null && viewer) + height = + findQuery(viewer)?.sampleHeightNow(point, { against: 'terrain' }) ?? + null; if (!plausibleSurfaceHeight(height)) height = fallback; return plausibleSurfaceHeight(height) ? height : 0; } @@ -63,8 +64,8 @@ export function createCameraFraming({ state }) { }, { offset: { - heading: Cesium.Math.toRadians(bearing || 0), - pitch: Cesium.Math.toRadians(-32), + heading: toRadians(bearing || 0), + pitch: toRadians(-32), range: 140, }, durationS: 1.6, diff --git a/src/layers/streetLevel/groundClick.js b/src/layers/streetLevel/groundClick.js index d33791b8a..16e15704f 100644 --- a/src/layers/streetLevel/groundClick.js +++ b/src/layers/streetLevel/groundClick.js @@ -1,11 +1,11 @@ -import * as Cesium from 'cesium'; import { GROUND_CLICK_MAX_HEIGHT_M } from './policy.js'; import { cameraHeightAboveGround } from './view.js'; +import { toLonLatH } from '../../geo/index.js'; /** Whether the camera is low enough for a click on the ground to mean a street. */ export function groundClickHeightOk(viewer) { - if (!viewer?.camera?.positionCartographic) return false; - return cameraHeightAboveGround(viewer) <= GROUND_CLICK_MAX_HEIGHT_M; + const height = cameraHeightAboveGround(viewer); + return height !== null && height <= GROUND_CLICK_MAX_HEIGHT_M; } /** @@ -33,13 +33,10 @@ export function createGroundClick({ state, openNearest, isAvailable }) { .map((entry) => entry.def.id); if (!providerIds.length) return false; const position = scenePick.pickGroundPosition(state.viewer, screenPosition); - const carto = position && Cesium.Cartographic.fromCartesian(position); - if (!carto) return false; + const ground = position && toLonLatH(position); + if (!ground) return false; return openNearest( - { - lon: Cesium.Math.toDegrees(carto.longitude), - lat: Cesium.Math.toDegrees(carto.latitude), - }, + { lon: ground.lon, lat: ground.lat }, { providerIds, frame: false }, ); }; diff --git a/src/layers/streetLevel/groundClick.test.mjs b/src/layers/streetLevel/groundClick.test.mjs index b7cfd2b7e..09d97e5c9 100644 --- a/src/layers/streetLevel/groundClick.test.mjs +++ b/src/layers/streetLevel/groundClick.test.mjs @@ -3,10 +3,16 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { createGroundClick, groundClickHeightOk } from './groundClick.js'; import * as scenePick from '../../data/scenePick.js'; +import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; +import { streetPorts } from '../../testSupport/streetLevelFakes.mjs'; const GROUND = Cesium.Cartesian3.fromDegrees(-121.4944, 38.5816, 10); const TILESET = { isCesium3DTileset: true }; +/** A viewer double bound to the camera and query ports, as the app binds its renderer. */ +const viewerWith = (viewer) => + bindFakeCesiumCamera(viewer, streetPorts(viewer)); + /** * A layer state with providers `{id, on, groundClick, configured, available}`; * `picked` is where the depth buffer lands, `ellipsoid` the fallback hit. @@ -39,7 +45,7 @@ function harness({ ], ), ), - viewer: { + viewer: viewerWith({ scene: { pickPositionSupported: true, pickPosition: () => picked }, camera: { pickEllipsoid: () => ellipsoid, @@ -49,7 +55,7 @@ function harness({ height, ), }, - }, + }), }; const openAtGround = createGroundClick({ state, @@ -120,12 +126,13 @@ test('nothing opens over another layer’s object, the sky, from high up, off it }); test('street zoom is measured above the ground under the camera', () => { - const viewer = (height) => ({ - camera: { - positionCartographic: Cesium.Cartographic.fromDegrees(0, 0, height), - }, - scene: { globe: { getHeight: () => 1500 } }, - }); + const viewer = (height) => + viewerWith({ + camera: { + positionCartographic: Cesium.Cartographic.fromDegrees(0, 0, height), + }, + scene: { globe: { getHeight: () => 1500 } }, + }); // 1,500 m up a plateau, 2,000 m above it: still a street. assert.equal(groundClickHeightOk(viewer(3500)), true); assert.equal(groundClickHeightOk(viewer(5000)), false); diff --git a/src/layers/streetLevel/index.js b/src/layers/streetLevel/index.js index 1f7b0f7f0..7f9dc5a66 100644 --- a/src/layers/streetLevel/index.js +++ b/src/layers/streetLevel/index.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createState } from './state.js'; import { createMarker } from './marker.js'; import { createCameraFraming } from './cameraFraming.js'; @@ -14,7 +13,9 @@ import { keyAlternatives, summarizeCoverage, } from './uiState.js'; -import { groundUnderCamera, viewCentre } from './view.js'; +import { canvasSize, groundUnderCamera, viewCentre } from './view.js'; +import { toLonLatH } from '../../geo/index.js'; +import { findCamera } from '../../render/rendererOf.js'; import { createGroundClick, groundClickHeightOk } from './groundClick.js'; import { msg, t, translateKnown } from '../../i18n/index.js'; import { @@ -38,7 +39,9 @@ const GROUND_RETRY_MS = 1000; * The core owns what they share: the filter and switches, the photo viewer * host, the position marker, the click handler and nearest-image lookups. * Providers own coverage, sequences and their viewer. One source is lit at - * a time. + * a time. It reaches the camera, queries and frames through the renderer's + * ports; given a Cesium viewer with no renderer bound, + * the caller loads the package's `./render/cesium/unbound` export first. * @param {{providers: Array, services?: object}} options */ export function createStreetLevelLayer({ @@ -209,7 +212,7 @@ export function createStreetLevelLayer({ function watchCamera(viewer) { removeCameraListener?.(); removeCameraListener = - viewer?.camera?.moveEnd?.addEventListener(remeasureGround) || null; + (viewer && findCamera(viewer)?.on('moveEnd', remeasureGround)) || null; } const activeEntries = () => @@ -257,21 +260,12 @@ export function createStreetLevelLayer({ /** Ground under the screen centre; null for sky, undefined when it cannot aim. */ function screenCentreGround() { - const canvas = state.viewer?.scene?.canvas; + const { width, height } = canvasSize(state.viewer); const pick = state.services.scenePick?.pickGroundPosition; - if (!pick || !canvas?.clientWidth || !canvas?.clientHeight) - return undefined; - const position = pick(state.viewer, { - x: canvas.clientWidth / 2, - y: canvas.clientHeight / 2, - }); - const carto = position && Cesium.Cartographic.fromCartesian(position); - return carto - ? { - lon: Cesium.Math.toDegrees(carto.longitude), - lat: Cesium.Math.toDegrees(carto.latitude), - } - : null; + if (!pick || !width || !height) return undefined; + const position = pick(state.viewer, { x: width / 2, y: height / 2 }); + const ground = position && toLonLatH(position); + return ground ? { lon: ground.lon, lat: ground.lat } : null; } /** `frame: false` keeps the camera where it is (the user picked the spot). */ diff --git a/src/layers/streetLevel/index.test.mjs b/src/layers/streetLevel/index.test.mjs index 69c77e429..0c80e5d14 100644 --- a/src/layers/streetLevel/index.test.mjs +++ b/src/layers/streetLevel/index.test.mjs @@ -12,6 +12,7 @@ import { fakeMapillarySource, fakePhotoViewer, fakeStreetLevelProvider as fakeProvider, + streetPorts, } from '../../testSupport/streetLevelFakes.mjs'; import { setLocale } from '../../i18n/index.js'; @@ -331,7 +332,7 @@ function fakeViewer() { disableRootEvents: true, onwheel: null, }); - return bindFakeCesiumCamera({ + const viewer = { credits, flights, scene: { @@ -363,7 +364,8 @@ function fakeViewer() { if (at !== -1) credits.splice(at, 1); }, }, - }); + }; + return bindFakeCesiumCamera(viewer, streetPorts(viewer)); } /** A layer over `providers`, initialised and enabled on a stand-in viewer. */ diff --git a/src/layers/streetLevel/lineCoverage.js b/src/layers/streetLevel/lineCoverage.js index bab1af46d..873bfeacf 100644 --- a/src/layers/streetLevel/lineCoverage.js +++ b/src/layers/streetLevel/lineCoverage.js @@ -3,6 +3,7 @@ import { passesImageryFilter } from './filter.js'; import { groundUnderCamera, viewFocus, visibleBbox } from './view.js'; import { tilesForBbox } from './tileMath.js'; import { msg } from '../../i18n/index.js'; +import { findCamera } from '../../render/rendererOf.js'; /** Sequences per primitive: smaller batches build, and show, sooner. */ const SEQUENCE_PRIMITIVE_BATCH = 120; @@ -396,7 +397,7 @@ export function createLineCoverage({ */ function wantedTiles(viewer) { const ground = groundUnderCamera(viewer); - const cameraHeight = viewer.camera?.positionCartographic?.height; + const cameraHeight = findCamera(viewer)?.pose().height; const height = Number.isFinite(cameraHeight) ? cameraHeight - (ground ?? 0) : null; @@ -456,8 +457,9 @@ export function createLineCoverage({ function attach(viewer) { detach(); - const remove = viewer.camera.changed.addEventListener(scheduleRefresh); - const removeEnd = viewer.camera.moveEnd.addEventListener(scheduleRefresh); + const camera = findCamera(viewer); + const remove = camera?.on('changed', scheduleRefresh) ?? (() => {}); + const removeEnd = camera?.on('moveEnd', scheduleRefresh) ?? (() => {}); state.coverage.removeCameraListener = () => { remove(); removeEnd(); diff --git a/src/layers/streetLevel/lineCoverage.test.mjs b/src/layers/streetLevel/lineCoverage.test.mjs index 60bae7eb3..7fec1a348 100644 --- a/src/layers/streetLevel/lineCoverage.test.mjs +++ b/src/layers/streetLevel/lineCoverage.test.mjs @@ -10,7 +10,8 @@ import { import { resolveFilter } from './filter.js'; import { encodeCoverageTile } from './providers/mapillary/coverageFixture.mjs'; import { decodeCoverageTile } from './providers/mapillary/decode.js'; -import { rayCamera } from '../../testSupport/streetLevelFakes.mjs'; +import { rayCamera, streetPorts } from '../../testSupport/streetLevelFakes.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; import { COLORS, COVERAGE_TUNING, @@ -85,7 +86,7 @@ function tileCentre(lon, lat) { /** A viewer looking straight down on a 0.004° square around `view`. */ function fakeViewer(view) { - return { + const viewer = { view, scene: { canvas: { clientWidth: 100, clientHeight: 100 }, @@ -101,6 +102,9 @@ function fakeViewer(view) { height: view.height, }; }, + get positionWC() { + return Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height); + }, pickEllipsoid(point) { return Cesium.Cartesian3.fromDegrees( view.lon - 0.002 + (point.x / 100) * 0.004, @@ -109,6 +113,8 @@ function fakeViewer(view) { }, }, }; + bindRenderer(viewer, streetPorts(viewer, { camera: true })); + return viewer; } /** A source whose tile requests the test resolves, one call at a time. */ diff --git a/src/layers/streetLevel/marker.test.mjs b/src/layers/streetLevel/marker.test.mjs index d0a1e486a..14b46a021 100644 --- a/src/layers/streetLevel/marker.test.mjs +++ b/src/layers/streetLevel/marker.test.mjs @@ -2,6 +2,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import * as Cesium from 'cesium'; import { createMarker } from './marker.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { streetPorts } from '../../testSupport/streetLevelFakes.mjs'; /** A viewer whose camera is 20,000 km over `view`, and its pre-render listeners. */ function setup() { @@ -23,6 +25,7 @@ function setup() { }, }, }; + bindRenderer(viewer, streetPorts(viewer, { camera: true })); const state = { services: {}, viewer, diff --git a/src/layers/streetLevel/providers/mapillary/provider.test.mjs b/src/layers/streetLevel/providers/mapillary/provider.test.mjs index ce2f0bb0c..5c078028e 100644 --- a/src/layers/streetLevel/providers/mapillary/provider.test.mjs +++ b/src/layers/streetLevel/providers/mapillary/provider.test.mjs @@ -9,7 +9,9 @@ import { validateProviders } from '../../registry.js'; import { fakeMapillarySource, rayCamera, + streetPorts, } from '../../../../testSupport/streetLevelFakes.mjs'; +import { bindRenderer } from '../../../../render/rendererOf.js'; function fakeContext(filter = { pano: 'all', sinceMs: null }) { const opened = []; @@ -105,7 +107,7 @@ function streetViewer() { }), { changed: event(), moveEnd: event() }, ); - return { + const viewer = { camera, scene: { canvas: { clientWidth: 100, clientHeight: 100 }, @@ -117,6 +119,8 @@ function streetViewer() { requestRender() {}, }, }; + bindRenderer(viewer, streetPorts(viewer, { camera: true })); + return viewer; } test('coverage asks for no tiles before the key status is known, and none without a key', async (t) => { diff --git a/src/layers/streetLevel/selection.js b/src/layers/streetLevel/selection.js index 82233ccc6..b0c932699 100644 --- a/src/layers/streetLevel/selection.js +++ b/src/layers/streetLevel/selection.js @@ -1,6 +1,6 @@ -import * as Cesium from 'cesium'; import { CLICK_PICK_WINDOW_PX, STREET_LEVEL_LAYER_ID } from './policy.js'; import { inputFor } from '../../input/dispatcher.js'; +import { toLonLatH } from '../../geo/index.js'; /** One click handler for every provider's lines and cones, and the marker. */ export function createSelection({ state, parts }) { @@ -33,13 +33,8 @@ export function createSelection({ state, parts }) { viewer, screenPosition, ); - const carto = position && Cesium.Cartographic.fromCartesian(position); - return carto - ? { - lon: Cesium.Math.toDegrees(carto.longitude), - lat: Cesium.Math.toDegrees(carto.latitude), - } - : null; + const ground = position && toLonLatH(position); + return ground ? { lon: ground.lon, lat: ground.lat } : null; } /** diff --git a/src/layers/streetLevel/sequenceCones.test.mjs b/src/layers/streetLevel/sequenceCones.test.mjs index 0e301cffc..7ec95cfa3 100644 --- a/src/layers/streetLevel/sequenceCones.test.mjs +++ b/src/layers/streetLevel/sequenceCones.test.mjs @@ -3,6 +3,8 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { resolveFilter } from './filter.js'; import { createSequenceCones, thinImages } from './sequenceCones.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { streetPorts } from '../../testSupport/streetLevelFakes.mjs'; const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); @@ -192,6 +194,7 @@ test('cones behind the globe are hidden, and show again from the other side', as }, }, }; + bindRenderer(state.viewer, streetPorts(state.viewer, { camera: true })); sequences.select('A'); // One image under the camera, one near its antipode. source.last('A').resolve([ diff --git a/src/layers/streetLevel/view.js b/src/layers/streetLevel/view.js index 6c687393a..3f295e982 100644 --- a/src/layers/streetLevel/view.js +++ b/src/layers/streetLevel/view.js @@ -1,6 +1,18 @@ -import * as Cesium from 'cesium'; import { wrapLon } from './tileMath.js'; -import { heightsFor } from '../../queries/heights.js'; +import { + offsetEllipsoid, + rayEllipsoid, + toLonLatH, + WGS84, +} from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { distance } from '../../geo/vector.js'; +import { + findCamera, + findFrame, + findQuery, + rendererOf, +} from '../../render/rendererOf.js'; /** Equirectangular metres between {lon, lat} points, the short way round ±180°; street scale. */ export function metresBetween(a, b) { @@ -17,68 +29,85 @@ export function plausibleSurfaceHeight(height) { } /** - * Height (m) of the rendered surface, 3D tiles included, at `carto`; null - * when unsampleable or implausible (`sampleHeight` reads kilometres - * underground before tiles load). + * Height (m) of the rendered surface, 3D tiles included, at `point` + * (`{lon, lat}` degrees); null when unsampleable or implausible + * (`sampleHeight` reads kilometres underground before tiles load). + * `against: 'tiles'` reads the 3D tiles alone. */ -export function sampledSurfaceHeight(scene, carto) { - const height = scene?.sampleHeightSupported - ? heightsFor(scene).now(carto) - : null; +export function sampledSurfaceHeight(viewer, point, { against } = {}) { + const height = + findQuery(viewer)?.sampleHeightNow(point, against ? { against } : {}) ?? + null; return plausibleSurfaceHeight(height) ? height : null; } +/** The camera's pose, or null without one (or with no position). */ +function poseOf(viewer) { + if (!viewer) return null; + const pose = findCamera(viewer)?.pose(); + return pose && Number.isFinite(pose.height) ? pose : null; +} + /** - * Ellipsoidal height (m) of the ground under the camera, or null. Under - * Google 3D (globe hidden) the rendered surface counts, minus any roof above - * the camera. + * Ellipsoidal height (m) of the ground under the camera, or null. Where 3D + * tiles answer under the camera (Google 3D) they decide: their surface, + * minus any roof above the camera, or null while they are still loading + * (they read kilometres underground then). Elsewhere the loaded terrain, + * else the drawn surface below the camera. */ export function groundUnderCamera(viewer) { - const carto = viewer?.camera?.positionCartographic; - const scene = viewer?.scene; - if (!carto || !scene) return null; - const globe = scene.globe; - if (globe && globe.show !== false) { - const ground = heightsFor(scene).now(carto, { against: 'terrain' }); - if (ground !== null) return ground; - } - const sampled = sampledSurfaceHeight(scene, carto); - return sampled !== null && sampled < carto.height ? sampled : null; + const pose = poseOf(viewer); + const query = pose && findQuery(viewer); + if (!query) return null; + const point = { lon: pose.lon, lat: pose.lat }; + const tiles = query.sampleHeightNow(point, { against: 'tiles' }) ?? null; + if (tiles !== null) + return plausibleSurfaceHeight(tiles) && tiles < pose.height ? tiles : null; + const terrain = query.sampleHeightNow(point, { against: 'terrain' }) ?? null; + if (Number.isFinite(terrain)) return terrain; + const surface = sampledSurfaceHeight(viewer, point); + return surface !== null && surface < pose.height ? surface : null; } -/** The ellipsoid `height` metres above `ellipsoid` (the ground at that height). */ -function raisedEllipsoid(ellipsoid, height) { - if (!Number.isFinite(height) || Math.abs(height) < 1) return ellipsoid; - const { x, y, z } = ellipsoid.radii; - return new Cesium.Ellipsoid(x + height, y + height, z + height); +/** The ellipsoid `height` metres above WGS84 (the ground at that height). */ +function raisedEllipsoid(height) { + if (!Number.isFinite(height) || Math.abs(height) < 1) return WGS84; + return offsetEllipsoid(height); +} + +/** The CSS size of the canvas the viewer draws on; zeros without one. */ +export function canvasSize(viewer) { + const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas; + return { + width: canvas?.clientWidth || canvas?.width || 0, + height: canvas?.clientHeight || canvas?.height || 0, + }; } /** - * Where a screen point's ray meets the ground, as a Cartographic, or null. - * `maxRange` (metres from the camera) drops hits near the horizon. + * Where a screen point's ray meets `ellipsoid`, as `{lon, lat}` degrees on + * it, or null. `maxRange` (metres from the camera) drops hits near the + * horizon. */ -function groundHit(camera, point, ellipsoid, maxRange) { - let cartesian = null; +function groundHit(query, x, y, ellipsoid, maxRange) { + let ray = null; try { - cartesian = camera.pickEllipsoid(point, ellipsoid); + ray = query.pickRay(x, y); } catch { - cartesian = null; + ray = null; } - if (!cartesian) return null; - if ( - Number.isFinite(maxRange) && - camera.positionWC && - Cesium.Cartesian3.distance(cartesian, camera.positionWC) > maxRange - ) + const hit = ray?.origin && ray.direction && rayEllipsoid(ray, ellipsoid); + if (!hit) return null; + if (Number.isFinite(maxRange) && distance(hit, ray.origin) > maxRange) return null; - return Cesium.Cartographic.fromCartesian(cartesian, ellipsoid) || null; + return toLonLatH(hit, ellipsoid); } /** Camera height (m) above the ground under it. */ export function cameraHeightAboveGround(viewer) { - const carto = viewer?.camera?.positionCartographic; - if (!carto) return null; - return carto.height - (groundUnderCamera(viewer) ?? 0); + const pose = poseOf(viewer); + if (!pose) return null; + return pose.height - (groundUnderCamera(viewer) ?? 0); } /** Screen rays per side, less one, that `visibleBbox` casts. */ @@ -93,24 +122,22 @@ export function visibleBbox( viewer, { groundHeight = null, maxRange = null } = {}, ) { - const scene = viewer?.scene; - const camera = viewer?.camera; - if (!scene || !camera) return null; - const width = scene.canvas?.clientWidth || scene.canvas?.width || 0; - const height = scene.canvas?.clientHeight || scene.canvas?.height || 0; + const query = viewer && findQuery(viewer); + if (!query || !poseOf(viewer)) return null; + const { width, height } = canvasSize(viewer); const hits = []; if (width > 0 && height > 0) { - const ellipsoid = raisedEllipsoid( - scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84, - groundHeight, - ); - const point = new Cesium.Cartesian2(); + const ellipsoid = raisedEllipsoid(groundHeight); for (let i = 0; i <= BBOX_GRID; i++) { for (let j = 0; j <= BBOX_GRID; j++) { - point.x = (width * i) / BBOX_GRID; - point.y = (height * j) / BBOX_GRID; - const carto = groundHit(camera, point, ellipsoid, maxRange); - if (carto) hits.push(carto); + const hit = groundHit( + query, + (width * i) / BBOX_GRID, + (height * j) / BBOX_GRID, + ellipsoid, + maxRange, + ); + if (hit) hits.push(hit); } } } @@ -119,9 +146,7 @@ export function visibleBbox( let south = Infinity; let east = -Infinity; let north = -Infinity; - for (const carto of hits) { - const lon = Cesium.Math.toDegrees(carto.longitude); - const lat = Cesium.Math.toDegrees(carto.latitude); + for (const { lon, lat } of hits) { west = Math.min(west, lon); east = Math.max(east, lon); south = Math.min(south, lat); @@ -133,8 +158,7 @@ export function visibleBbox( if (east - west > 180) { let west360 = Infinity; let east360 = -Infinity; - for (const carto of hits) { - const lon = Cesium.Math.toDegrees(carto.longitude); + for (const { lon } of hits) { const shifted = lon < 0 ? lon + 360 : lon; west360 = Math.min(west360, shifted); east360 = Math.max(east360, shifted); @@ -151,12 +175,8 @@ export function visibleBbox( /** The point on the ground under the camera, as {lon, lat} degrees. */ export function cameraNadir(viewer) { - const carto = viewer?.camera?.positionCartographic; - if (!carto) return null; - return { - lon: Cesium.Math.toDegrees(carto.longitude), - lat: Cesium.Math.toDegrees(carto.latitude), - }; + const pose = poseOf(viewer); + return pose ? { lon: pose.lon, lat: pose.lat } : null; } /** @@ -168,24 +188,17 @@ export function viewFocus( { groundHeight = null, maxRange = null } = {}, ) { const nadir = cameraNadir(viewer); - const scene = viewer?.scene; - const width = scene?.canvas?.clientWidth || scene?.canvas?.width || 0; - const height = scene?.canvas?.clientHeight || scene?.canvas?.height || 0; - if (!nadir || !width || !height) return nadir; - const hit = groundHit( - viewer.camera, - new Cesium.Cartesian2(width / 2, height / 2), - raisedEllipsoid( - scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84, - groundHeight, - ), + const { width, height } = canvasSize(viewer); + const query = nadir && findQuery(viewer); + if (!nadir || !query || !width || !height) return nadir; + const ahead = groundHit( + query, + width / 2, + height / 2, + raisedEllipsoid(groundHeight), maxRange, ); - if (!hit) return nadir; - const ahead = { - lon: Cesium.Math.toDegrees(hit.longitude), - lat: Cesium.Math.toDegrees(hit.latitude), - }; + if (!ahead) return nadir; return { lon: wrapLon(nadir.lon + wrapLon(ahead.lon - nadir.lon) / 2), lat: (nadir.lat + ahead.lat) / 2, @@ -197,60 +210,60 @@ export function viewFocus( * (NYC −22 m), and an occluder at 0 m would hide the cones around it. */ const HORIZON_CULL_DEPTH_M = 1000; -const HORIZON_CULL_ELLIPSOID = new Cesium.Ellipsoid( - Cesium.Ellipsoid.WGS84.radii.x - HORIZON_CULL_DEPTH_M, - Cesium.Ellipsoid.WGS84.radii.y - HORIZON_CULL_DEPTH_M, - Cesium.Ellipsoid.WGS84.radii.z - HORIZON_CULL_DEPTH_M, -); +const HORIZON_CULL_ELLIPSOID = offsetEllipsoid(-HORIZON_CULL_DEPTH_M); /** - * Hide billboards and points behind the horizon: they skip the depth test, so - * nothing else stops the far side drawing through the globe. Re-culls on - * pre-render after the camera moves; stops when nothing is left to cull. - * @param {{getViewer: () => object|null, items: () => Iterable<{position: object, show: boolean}>, onChange?: () => void}} options + * Hide markers behind the horizon: they skip the depth test, so nothing + * else stops the far side drawing through the globe. Re-culls before a + * frame draws after the camera moves; stops when nothing is left to cull. + * Items are `{position, show}` (`position` ECEF); `onChange` hears the + * items whose `show` it changed. + * @param {{getViewer: () => object|null, items: () => Iterable<{position: {x: number, y: number, z: number}, show: boolean}>, onChange?: (changed: object[]) => void}} options */ export function createHorizonCull({ getViewer, items, onChange }) { - const occluder = new Cesium.EllipsoidalOccluder(HORIZON_CULL_ELLIPSOID); let from = null; let stopListening = null; /** Show what is in front of the horizon, hide the rest; the count seen. */ function cull(list, position) { - occluder.cameraPosition = position; + const horizon = horizonFrom(position, HORIZON_CULL_ELLIPSOID); let seen = 0; - let changed = false; + const changed = []; for (const item of list) { seen++; - const show = occluder.isPointVisible(item.position); + const show = horizon.isPointVisible(item.position); if (item.show !== show) { item.show = show; - changed = true; + changed.push(item); } } - if (changed) onChange?.(); + if (changed.length) onChange?.(changed); return seen; } /** Cull everything from the camera at `position`; the count seen. */ function cullAll(position) { - from = Cesium.Cartesian3.clone(position, from); + from = { x: position.x, y: position.y, z: position.z }; return cull(items(), position); } + const eyeOf = (viewer) => (viewer ? poseOf(viewer)?.position : null) ?? null; + const same = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z; + function onPreRender() { - const position = getViewer()?.camera?.positionWC; - if (!position || (from && Cesium.Cartesian3.equals(from, position))) return; + const position = eyeOf(getViewer()); + if (!position || (from && same(from, position))) return; if (!cullAll(position)) stop(); } /** Cull `added` items (or all) now, then all again whenever the camera moves. */ function update(added) { const viewer = getViewer(); - const position = viewer?.camera?.positionWC; + const position = eyeOf(viewer); if (position && !(added ? cull(added, position) : cullAll(position))) return; stopListening ||= - viewer?.scene?.preRender?.addEventListener(onPreRender) || null; + (viewer && findFrame(viewer)?.on('preRender', onPreRender)) || null; } function stop() { @@ -273,10 +286,6 @@ export function viewCentre(viewer) { if (lon > 180) lon -= 360; return { lat: (bbox[1] + bbox[3]) / 2, lon }; } - const carto = viewer.camera?.positionCartographic; - if (!carto) return null; - return { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; + const pose = poseOf(viewer); + return pose ? { lat: pose.lat, lon: pose.lon } : null; } diff --git a/src/layers/streetLevel/view.test.mjs b/src/layers/streetLevel/view.test.mjs index 8f5a4dd99..4678ca3b0 100644 --- a/src/layers/streetLevel/view.test.mjs +++ b/src/layers/streetLevel/view.test.mjs @@ -10,12 +10,14 @@ import { visibleBbox, } from './view.js'; import { latToTileY, lonToTileX, tilesForBbox } from './tileMath.js'; -import { rayCamera } from '../../testSupport/streetLevelFakes.mjs'; +import { rayCamera, streetPorts } from '../../testSupport/streetLevelFakes.mjs'; +import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; const RAD = Math.PI / 180; /** A viewer 300 m above a street 1,600 m up (Denver-like). */ function viewer({ globeShown, globeHeight }) { - return { + const view = { camera: { positionCartographic: { longitude: -104.99 * RAD, @@ -25,6 +27,7 @@ function viewer({ globeShown, globeHeight }) { }, scene: { globe: { show: globeShown, getHeight: () => globeHeight } }, }; + return bindFakeCesiumCamera(view, streetPorts(view)); } test('a shown globe answers the ground under the camera', () => { @@ -34,22 +37,23 @@ test('a shown globe answers the ground under the camera', () => { ); }); -test('a hidden globe (Google 3D) or a missing sample gives no ground', () => { - // A hidden globe's getHeight is ignored even when it returns a number. +test('without 3D tiles under the camera the terrain answers; a missing sample gives no ground', () => { + // No tiles drawn there: the terrain answers, globe shown or hidden. assert.equal( groundUnderCamera(viewer({ globeShown: false, globeHeight: 0 })), - null, + 0, ); assert.equal( groundUnderCamera(viewer({ globeShown: true, globeHeight: undefined })), null, ); assert.equal(groundUnderCamera({}), null); + assert.equal(groundUnderCamera(null), null); }); /** The Denver viewer with Google 3D: no globe, a sampleable rendered surface. */ function google3d(sample) { - const view = viewer({ globeShown: false, globeHeight: 0 }); + const view = viewer({ globeShown: false, globeHeight: undefined }); view.scene.sampleHeightSupported = true; view.scene.sampleHeight = () => sample; return view; @@ -59,6 +63,22 @@ test('on Google 3D the rendered surface answers the ground under the camera', () assert.equal(groundUnderCamera(google3d(1612)), 1612); }); +test('where the 3D tiles answer, they decide, whatever the terrain says', () => { + const view = google3d(1612); + // A hidden globe's terrain can be stale (or the bare ellipsoid's 0). + view.scene.globe.getHeight = () => 0; + assert.equal(groundUnderCamera(view), 1612); + // A roof above the camera is not the ground, and tiles still loading + // (kilometres underground) are not either: unknown, so measured again. + view.scene.sampleHeight = () => 1950; + assert.equal(groundUnderCamera(view), null); + view.scene.sampleHeight = () => -14_886; + assert.equal(groundUnderCamera(view), null); + // No tiles there at all: the terrain answers. + view.scene.sampleHeight = () => undefined; + assert.equal(groundUnderCamera(view), 0); +}); + test('an implausible or above-camera surface sample gives no ground', () => { // Before tiles stream in, sampleHeight can read kilometres underground. assert.equal(groundUnderCamera(google3d(-14_886)), null); @@ -70,17 +90,29 @@ test('an implausible or above-camera surface sample gives no ground', () => { /** A camera whose screen rays land on a grid of lon/lat points. */ function gridViewer(lons, lats) { const points = []; - for (const lat of lats) - for (const lon of lons) - points.push(Cesium.Cartesian3.fromDegrees(lon, lat)); + for (const lat of lats) for (const lon of lons) points.push([lon, lat]); let next = 0; - return { - scene: { canvas: { clientWidth: 100, clientHeight: 100 }, globe: {} }, + const viewer = {}; + bindRenderer(viewer, { + canvas: { clientWidth: 100, clientHeight: 100 }, camera: { - pickEllipsoid: () => points[next++ % points.length], - positionCartographic: { longitude: 0, latitude: 0, height: 1000 }, + pose: () => ({ lon: 0, lat: 0, height: 1000 }), }, - }; + query: { + // Straight down onto the next grid point, from 1 km above it. + pickRay() { + const [lon, lat] = points[next++ % points.length]; + const origin = Cesium.Cartesian3.fromDegrees(lon, lat, 1000); + const ground = Cesium.Cartesian3.fromDegrees(lon, lat); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(ground, origin, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + return { origin, direction }; + }, + }, + }); + return viewer; } test('a view across the date line is a narrow box with west > east', () => { @@ -97,7 +129,7 @@ test('an ordinary view keeps west < east', () => { /** A pinhole viewer `agl` m above ground `ground` m up, looking north. */ function pinhole({ lon, lat, ground, agl, pitch, w = 1600, h = 900 }) { - return { + const view = { scene: { canvas: { clientWidth: w, clientHeight: h }, globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 }, @@ -111,6 +143,7 @@ function pinhole({ lon, lat, ground, agl, pitch, w = 1600, h = 900 }) { height: h, }), }; + return bindFakeCesiumCamera(view, streetPorts(view)); } test('a tilted street view over high ground boxes the streets it looks at, not the horizon', () => { @@ -236,49 +269,49 @@ test('metresBetween measures the short way round the date line', () => { /** * A horizon cull over `items` for a camera the test moves, with the frame's - * pre-render listeners and a count of the points tested against the horizon. + * pre-render listeners and a count of the camera poses read. */ function cullHarness(t, items) { - const visible = t.mock.method( - Cesium.EllipsoidalOccluder.prototype, - 'isPointVisible', - ); const preRender = new Set(); - const camera = { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e7) }; - const viewer = { - camera, - scene: { - preRender: { - addEventListener(listener) { - preRender.add(listener); - return () => preRender.delete(listener); - }, + let eye = Cesium.Cartesian3.fromDegrees(0, 0, 1e7); + let poses = 0; + const viewer = {}; + bindRenderer(viewer, { + camera: { + pose: () => { + poses++; + return { lon: 0, lat: 0, height: 1e7, position: { ...eye } }; }, }, - }; + frame: { + on(phase, listener) { + assert.equal(phase, 'preRender'); + preRender.add(listener); + return () => preRender.delete(listener); + }, + }, + }); + // Items handed to a cull pass: what a still camera must not test again. + const tested = { count: 0 }; let changes = 0; const cull = createHorizonCull({ getViewer: () => viewer, - items: () => items, + items: () => { + tested.count += items.length; + return items; + }, onChange: () => changes++, }); return { cull, preRender, - tested: () => visible.mock.callCount(), + poses: () => poses, + tested: () => tested.count, changes: () => changes, frame: () => { for (const listener of [...preRender]) listener(); }, - // Moved in place, as Cesium updates positionWC. - moveTo: (lon, lat) => - Cesium.Cartesian3.fromDegrees( - lon, - lat, - 1e7, - undefined, - camera.positionWC, - ), + moveTo: (lon, lat) => (eye = Cesium.Cartesian3.fromDegrees(lon, lat, 1e7)), }; } @@ -337,11 +370,20 @@ function cullFrom(camera, points) { position: Cesium.Cartesian3.fromDegrees(lon, lat, height), show: true, })); + const viewer = {}; + bindRenderer(viewer, { + camera: { + pose: () => ({ + lon: camera[0], + lat: camera[1], + height: camera[2], + position: Cesium.Cartesian3.fromDegrees(...camera), + }), + }, + frame: { on: () => () => {} }, + }); const horizon = createHorizonCull({ - getViewer: () => ({ - camera: { positionWC: Cesium.Cartesian3.fromDegrees(...camera) }, - scene: { preRender: { addEventListener: () => () => {} } }, - }), + getViewer: () => viewer, items: () => items, }); horizon.update(); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index bdd24bf38..3c44335b3 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -86,14 +86,9 @@ "src/layers/satellites/state.js", "src/layers/satellites/testing.js", "src/layers/satellites/tracking.js", - "src/layers/streetLevel/cameraFraming.js", - "src/layers/streetLevel/groundClick.js", - "src/layers/streetLevel/index.js", "src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/marker.js", - "src/layers/streetLevel/selection.js", "src/layers/streetLevel/sequenceCones.js", - "src/layers/streetLevel/view.js", "src/layers/traffic/animation.js", "src/layers/traffic/lifecycle.js", "src/layers/traffic/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 5d2d2bd47..a4fa2cd0d 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -79,6 +79,10 @@ const DRAW_FROM_CALLER = new Set([ './layers/submarine-cables', './layers/alpr', './layers/vessels', + './layers/street-level', + './layers/street-level/mapillary', + './layers/street-level/kartaview', + './layers/street-level/panoramax', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/testSupport/streetLevelFakes.mjs b/src/testSupport/streetLevelFakes.mjs index ccdbc2019..5337c0d4c 100644 --- a/src/testSupport/streetLevelFakes.mjs +++ b/src/testSupport/streetLevelFakes.mjs @@ -191,7 +191,7 @@ export function fakeCesiumViewer({ view = false } = {}) { }, }, ); - return bindFakeCesiumCamera({ + const viewer = { credits, flights, scene: { @@ -212,7 +212,8 @@ export function fakeCesiumViewer({ view = false } = {}) { if (at !== -1) credits.splice(at, 1); }, }, - }); + }; + return bindFakeCesiumCamera(viewer, streetPorts(viewer)); } /** @@ -249,23 +250,27 @@ export function rayCamera({ const halfY = Math.tan((fovY / 2) * RAD); const halfX = fovX == null ? halfY * (width / height) : Math.tan((fovX / 2) * RAD); + /** The ray through a screen point, as the query port's `pickRay`. */ + function pickRay(x, y) { + const sx = ((2 * x) / width - 1) * halfX; + const sy = (1 - (2 * y) / height) * halfY; + const local = [0, 1, 2].map((i) => forward[i] + sx * right[i] + sy * up[i]); + const direction = Cesium.Cartesian3.normalize( + Cesium.Matrix4.multiplyByPointAsVector( + frame, + new Cesium.Cartesian3(...local), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + return { origin: position, direction }; + } return { positionWC: position, positionCartographic: Cesium.Cartographic.fromDegrees(lon, lat, altitude), + pickRay, pickEllipsoid(point, ellipsoid = Cesium.Ellipsoid.WGS84) { - const sx = ((2 * point.x) / width - 1) * halfX; - const sy = (1 - (2 * point.y) / height) * halfY; - const local = [0, 1, 2].map( - (i) => forward[i] + sx * right[i] + sy * up[i], - ); - const direction = Cesium.Cartesian3.normalize( - Cesium.Matrix4.multiplyByPointAsVector( - frame, - new Cesium.Cartesian3(...local), - new Cesium.Cartesian3(), - ), - new Cesium.Cartesian3(), - ); + const { direction } = pickRay(point.x, point.y); const ray = new Cesium.Ray(position, direction); const hit = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid); return hit ? Cesium.Ray.getPoint(ray, hit.start) : undefined; @@ -273,6 +278,87 @@ export function rayCamera({ }; } +/** + * The query, frame and canvas a Street Level layer reads, answered from a + * Cesium-shaped viewer double: rays from its camera's `pickRay` (else + * through what its `pickEllipsoid` hits), heights from its scene's + * `sampleHeight` (3D tiles: only while its globe is hidden) and its + * globe's `getHeight` (terrain), and pre-render from its scene's + * `preRender`. `draw` adds a draw port. For `bindFakeCesiumCamera`'s + * `ports`. + * @param {object} viewer + * @param {{draw?: object}} [options] + */ +export function streetPorts(viewer, { draw, camera = false } = {}) { + const finite = (height) => (Number.isFinite(height) ? height : null); + const cartographic = ({ lon, lat }) => ({ + longitude: lon * RAD, + latitude: lat * RAD, + height: 0, + }); + return { + get canvas() { + return viewer.scene?.canvas; + }, + query: { + pickRay(x, y) { + const camera = viewer.camera ?? {}; + if (camera.pickRay) return camera.pickRay(x, y); + const hit = camera.pickEllipsoid?.({ x, y }); + const origin = camera.positionWC; + if (!hit || !origin) return null; + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(hit, origin, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + return { origin, direction }; + }, + sampleHeightNow(point, { against = 'surface' } = {}) { + const scene = viewer.scene ?? {}; + if (against === 'terrain') + return finite(scene.globe?.getHeight?.(cartographic(point))); + if (!scene.sampleHeightSupported) return null; + if (against === 'tiles' && scene.globe?.show !== false) return null; + return finite(scene.sampleHeight?.(cartographic(point))); + }, + }, + frame: { + on(phase, cb) { + const event = viewer.scene?.[phase]; + return event?.addEventListener?.(cb) ?? (() => {}); + }, + }, + ...(draw ? { draw } : {}), + ...(camera ? { camera: liveCamera(viewer) } : {}), + }; +} + +/** + * A camera port over whatever camera double `viewer.camera` is when asked + * (tests swap it): its pose from `positionCartographic` and `positionWC`, + * its events from the double's own `changed` and `moveEnd`. + */ +export function liveCamera(viewer) { + return { + pose() { + const camera = viewer.camera ?? {}; + const p = camera.positionWC; + const c = + camera.positionCartographic ?? + (p && Cesium.Cartographic.fromCartesian(p)); + return { + lon: c ? c.longitude / RAD : NaN, + lat: c ? c.latitude / RAD : NaN, + height: c ? c.height : NaN, + position: p ? { x: p.x, y: p.y, z: p.z } : null, + }; + }, + on(event, cb) { + return viewer.camera?.[event]?.addEventListener?.(cb) ?? (() => {}); + }, + }; +} + /** The centre of the tile holding a point at zoom `z`, so a small view is one tile. */ export function tileCentre(lon, lat, z = 14) { const x = lonToTileX(lon, z); @@ -325,7 +411,7 @@ export function coverageViewer(view, t) { }, }; }; - return { + const viewer = { view, scene: { canvas: { clientWidth: 100, clientHeight: 100 }, @@ -360,4 +446,5 @@ export function coverageViewer(view, t) { computeViewRectangle: () => undefined, }, }; + return bindFakeCesiumCamera(viewer, streetPorts(viewer)); }