mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-05 02:44:02 +00:00
Traffic roads come from OpenFreeMap vector tiles, or TomTom flow tiles with a key (Hybrid by default). Military areas use OpenFreeMap polygons with a bundled worldwide name index; wide views show named points. ALPR reads an hourly OpenStreetMap extract. Cockpit place context and country, state and US county outlines use bundled Natural Earth and US Census data. Overpass is used only when an operator configures their own endpoint. Also: camera arrivals no longer land below ground, keyless terrain retries on 429, bounded relation geometry for configured Overpass, one shared OpenStreetMap credit, and separate tile and API transports for embedders. Co-authored-by: theGaryLarson <[email protected]> Co-authored-by: Milan Khanal <[email protected]>
This commit is contained in:
200 files changed
+26665
-1977
No files matched your search
@@ -0,0 +1,82 @@
|
||||
/** One cancellable consumer of the shared terrain service, coalesced by floor cell. */
|
||||
export function createAlprFloorResolver(ground) {
|
||||
const pending = new Map();
|
||||
const queued = new Map();
|
||||
let owner = null;
|
||||
let running = false;
|
||||
|
||||
async function pump(controller) {
|
||||
try {
|
||||
while (queued.size && !controller.signal.aborted) {
|
||||
const batch = [...queued.values()].slice(0, 64);
|
||||
for (const cell of batch) queued.delete(cell.key);
|
||||
try {
|
||||
await ground.resolveGroundFloorCells(
|
||||
batch.map(({ lat, lon }) => ({ lat, lon })),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
} catch {
|
||||
// Missing floors remain clamped; cancellation must not publish later.
|
||||
}
|
||||
for (const cell of batch) {
|
||||
if (pending.get(cell.key) === cell) pending.delete(cell.key);
|
||||
cell.finish();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (owner === controller) running = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolve(points) {
|
||||
if (typeof ground.resolveGroundFloorCells !== 'function')
|
||||
return Promise.resolve();
|
||||
owner ??= new AbortController();
|
||||
const waits = [];
|
||||
for (const point of points) {
|
||||
const lat = Number(point.lat.toFixed(3));
|
||||
const lon = Number(point.lon.toFixed(3));
|
||||
const key = `${lat},${lon}`;
|
||||
let cell = pending.get(key);
|
||||
if (!cell) {
|
||||
let finish;
|
||||
const promise = new Promise((done) => {
|
||||
finish = done;
|
||||
});
|
||||
cell = { key, lat, lon, promise, finish };
|
||||
pending.set(key, cell);
|
||||
queued.set(key, cell);
|
||||
}
|
||||
waits.push(cell.promise);
|
||||
}
|
||||
if (!running && queued.size) {
|
||||
running = true;
|
||||
void pump(owner);
|
||||
}
|
||||
return Promise.all(waits);
|
||||
}
|
||||
|
||||
async function prepare(points) {
|
||||
let timer;
|
||||
try {
|
||||
await Promise.race([
|
||||
resolve(points),
|
||||
new Promise((done) => {
|
||||
timer = setTimeout(done, ground.FLOOR_RESOLVE_DEADLINE_MS ?? 1200);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
owner?.abort();
|
||||
owner = null;
|
||||
running = false;
|
||||
for (const cell of pending.values()) cell.finish();
|
||||
pending.clear();
|
||||
queued.clear();
|
||||
}
|
||||
return { resolve, prepare, cancel };
|
||||
}
|
||||
+107
-33
@@ -1,3 +1,4 @@
|
||||
import { isUnavailableCapability } from '../../sources/capability.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
LAYER_ID,
|
||||
@@ -21,7 +22,9 @@ import { createAlprPresentation } from './presentation.js';
|
||||
/**
|
||||
* Own one layer's requests, records, display and viewer subscriptions.
|
||||
* A source fetches a bounded box with an AbortSignal and resolves
|
||||
* { records, stale, saturated }. Records use stable string ids and latitude /
|
||||
* { records, stale, saturated }, optionally with `coverage` (the bounds its
|
||||
* records fully cover, reused for later views inside it) and `zoom` (their
|
||||
* tile precision; `source.detailZoom(box)` names the zoom a view needs). Records use stable string ids and latitude /
|
||||
* longitude in degrees; optional directionDeg is a compass bearing [0, 360).
|
||||
* Manufacturer, operator and cameraType are optional display fields.
|
||||
* Source label and attribution { name, description, text, href } identify the
|
||||
@@ -67,6 +70,12 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
debounceTimer: null,
|
||||
/** Snapped box of the last successful query; a view still inside it reuses its records. */
|
||||
lastQueryBox: null,
|
||||
/** Extract zoom of the accepted records (null for sources without tiles). */
|
||||
lastQueryZoom: null,
|
||||
/** Increments whenever the displayed camera set changes (QA stability probe). */
|
||||
renderRevision: 0,
|
||||
/** Cameras in view beyond the render cap. */
|
||||
renderSaturated: false,
|
||||
};
|
||||
const {
|
||||
initOverlay,
|
||||
@@ -81,6 +90,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
clearSelection,
|
||||
updateSelectedAnchor,
|
||||
installInteraction,
|
||||
prepareFloors,
|
||||
} = createAlprPresentation({ state, services, source });
|
||||
|
||||
function setAlprStatus(status, error = null) {
|
||||
@@ -109,10 +119,34 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
if (resetBackoff) state.retryDelayMs = 0;
|
||||
}
|
||||
|
||||
/** Whether accepted records already answer `box` without a request. */
|
||||
function canReuse(box) {
|
||||
const detailZoom = source.detailZoom?.(box) ?? null;
|
||||
return Boolean(
|
||||
state.lastQueryBox &&
|
||||
boxContains(state.lastQueryBox, box) &&
|
||||
(state.lastQueryZoom == null ||
|
||||
detailZoom == null ||
|
||||
state.lastQueryZoom >= detailZoom - 1) &&
|
||||
state.lastUpdate &&
|
||||
Date.now() - state.lastUpdate < QUERY_REUSE_MS &&
|
||||
!state.stale &&
|
||||
state.status !== 'unavailable',
|
||||
);
|
||||
}
|
||||
|
||||
function scheduleLoad() {
|
||||
if (!state.enabled) return;
|
||||
clearUnavailableRetry({ resetBackoff: false });
|
||||
clearTimeout(state.debounceTimer);
|
||||
// A view the accepted tiles already cover is a local filter: show it now.
|
||||
// Only a view that needs a request waits out the debounce.
|
||||
const box = viewportBox(state.viewer);
|
||||
if (box && canReuse(box)) {
|
||||
state.debounceTimer = null;
|
||||
loadCameras();
|
||||
return;
|
||||
}
|
||||
state.debounceTimer = setTimeout(() => {
|
||||
state.debounceTimer = null;
|
||||
loadCameras();
|
||||
@@ -142,14 +176,9 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
// request still in flight was for a viewport the user has since left, so it
|
||||
// is aborted rather than allowed to replace the records that already cover
|
||||
// this view. Failed queries never replace the last successful box.
|
||||
if (
|
||||
state.lastQueryBox &&
|
||||
boxContains(state.lastQueryBox, box) &&
|
||||
state.lastUpdate &&
|
||||
Date.now() - state.lastUpdate < QUERY_REUSE_MS &&
|
||||
!state.stale &&
|
||||
state.status !== 'unavailable'
|
||||
) {
|
||||
// Reuse also needs the accepted records to be precise enough for this view:
|
||||
// one zoom coarser than the view would pick is a few metres, never more.
|
||||
if (canReuse(box)) {
|
||||
if (state.abort) {
|
||||
state.abort.abort();
|
||||
state.abort = null;
|
||||
@@ -165,7 +194,8 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
}
|
||||
// A move inside an in-flight query must not abort and restart that query.
|
||||
if (state.abort && boxContains(state.pendingQueryBox, box)) {
|
||||
renderRecords();
|
||||
// The accepted records may cover only part of the new view. Re-filtering
|
||||
// them during floor preparation creates an intermediate marker set.
|
||||
return;
|
||||
}
|
||||
const queryBox = snapAlprBox(box);
|
||||
@@ -176,7 +206,8 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
state.loading = true;
|
||||
state.retrying = state.status === 'unavailable' || state.retryDelayMs > 0;
|
||||
setAlprStatus('loading');
|
||||
renderRecords();
|
||||
// Keep the current markers until the new view's records land, so a still
|
||||
// camera sees one update instead of old records re-filtered, then new ones.
|
||||
try {
|
||||
const snapshot = await source.fetch(queryBox, requestAbort.signal);
|
||||
if (
|
||||
@@ -185,16 +216,43 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
!state.enabled
|
||||
)
|
||||
return;
|
||||
if (snapshot.zoomIn) {
|
||||
state.records = [];
|
||||
state.recordById.clear();
|
||||
state.noCoverage = false;
|
||||
state.lastQueryBox = null;
|
||||
state.lastQueryZoom = null;
|
||||
clearUnavailableRetry();
|
||||
renderRecords();
|
||||
setAlprStatus('zoom-in');
|
||||
return;
|
||||
}
|
||||
const { records, stale, saturated } = validateAlprSnapshot(snapshot);
|
||||
// Resolve marker floors (bounded wait, warm cells answer at once) so new
|
||||
// markers are placed on the floor instead of clamped then moved.
|
||||
await prepareFloors(records);
|
||||
if (
|
||||
requestAbort.signal.aborted ||
|
||||
state.abort !== requestAbort ||
|
||||
!state.enabled
|
||||
)
|
||||
return;
|
||||
state.noCoverage = snapshot.noCoverage === true;
|
||||
state.records = records;
|
||||
state.recordById = new Map(records.map((r) => [r.id, r]));
|
||||
state.lastUpdate = Date.now();
|
||||
state.stale = stale;
|
||||
// Saturated when the QUERY truncated OR the render cap would hide cameras:
|
||||
// either way the view holds more than the screen shows, and the user must
|
||||
// be told rather than left with a count that disagrees with the map.
|
||||
state.saturated = saturated || records.length > MAX_RENDERED;
|
||||
state.lastQueryBox = queryBox;
|
||||
// Saturated when the QUERY truncated; the render cap is judged against
|
||||
// the cameras in view (renderSaturated). Either way the row says so.
|
||||
state.saturated = saturated;
|
||||
// The fetched tiles cover more than the view: pans inside them are free.
|
||||
state.lastQueryBox =
|
||||
snapshot.coverage && boxContains(snapshot.coverage, queryBox)
|
||||
? snapshot.coverage
|
||||
: queryBox;
|
||||
state.lastQueryZoom = Number.isInteger(snapshot.zoom)
|
||||
? snapshot.zoom
|
||||
: null;
|
||||
clearUnavailableRetry();
|
||||
// Stale and saturated are independent facts; a cached response that also
|
||||
// hit the cap must still warn about coverage, not just about freshness.
|
||||
@@ -219,7 +277,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
'unavailable',
|
||||
error?.message || 'Camera source temporarily unavailable',
|
||||
);
|
||||
scheduleUnavailableRetry();
|
||||
if (!isUnavailableCapability(error)) scheduleUnavailableRetry();
|
||||
} finally {
|
||||
if (state.abort === requestAbort) {
|
||||
state.abort = null;
|
||||
@@ -282,6 +340,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
return loadCameras();
|
||||
},
|
||||
destroy(viewer = state.viewer) {
|
||||
source.destroy?.();
|
||||
this.disable();
|
||||
destroyOverlay();
|
||||
state.moveEndRemove?.();
|
||||
@@ -299,6 +358,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
state.records = [];
|
||||
state.recordById = new Map();
|
||||
state.lastQueryBox = null;
|
||||
state.lastQueryZoom = null;
|
||||
state.lastUpdate = null;
|
||||
state.error = null;
|
||||
state.status = 'idle';
|
||||
@@ -335,12 +395,21 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
getStats() {
|
||||
return {
|
||||
count: state.dataSource?.entities.values.length || 0,
|
||||
countLabel: state.enabled
|
||||
? `${state.dataSource?.entities.values.length || 0} nearby`
|
||||
: '',
|
||||
countLabel:
|
||||
state.enabled && !state.noCoverage && state.status !== 'zoom-in'
|
||||
? `${state.dataSource?.entities.values.length || 0} nearby${
|
||||
Number.isInteger(state.onScreen)
|
||||
? ` · ${state.onScreen} on screen`
|
||||
: ''
|
||||
}`
|
||||
: '',
|
||||
noCoverage: Boolean(state.noCoverage),
|
||||
lastUpdate: state.lastUpdate,
|
||||
stale: state.stale,
|
||||
saturated: state.saturated,
|
||||
saturated: state.saturated || state.renderSaturated,
|
||||
renderRevision: state.renderRevision,
|
||||
onScreen: state.onScreen ?? null,
|
||||
shown: state.dataSource?.entities.values.length || 0,
|
||||
error: state.error,
|
||||
status: state.status,
|
||||
loading: state.loading,
|
||||
@@ -353,17 +422,22 @@ export function createAlprCamerasLayer({ source, services } = {}) {
|
||||
? state.retrying
|
||||
? 'retrying mapped ALPR cameras'
|
||||
: 'loading mapped ALPR cameras'
|
||||
: state.status === 'zoom-in'
|
||||
? 'Zoom in to load mapped cameras'
|
||||
: [
|
||||
state.stale ? 'Showing cached locations' : '',
|
||||
state.saturated ? 'Coverage limited — zoom in' : '',
|
||||
state.status === 'empty'
|
||||
? 'No mapped cameras returned — coverage is incomplete'
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
: state.noCoverage
|
||||
? 'No ALPR data for this area — US and Canada only'
|
||||
: state.status === 'zoom-in'
|
||||
? 'Zoom in to load mapped cameras'
|
||||
: [
|
||||
state.stale ? 'Showing cached locations' : '',
|
||||
state.saturated || state.renderSaturated
|
||||
? 'Coverage limited — zoom in'
|
||||
: '',
|
||||
state.status === 'empty' ? 'No ALPR data for this area' : '',
|
||||
state.status === 'ready' && state.onScreen === 0
|
||||
? 'None on screen — nearby cameras are outside the view'
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -384,4 +458,4 @@ export {
|
||||
QUERY_SNAP_DEGREES,
|
||||
QUERY_REUSE_MS,
|
||||
} from './policy.js';
|
||||
export { createOverpassAlprSource } from './source.js';
|
||||
export { createOverpassAlprSource, createAlprTileSource } from './source.js';
|
||||
+178
-32
@@ -3,18 +3,28 @@ import {
|
||||
MAX_CANVAS_FRUSTUMS,
|
||||
MARKER_ICON_SIZE,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
ANCHOR_SAMPLES_PER_PAINT,
|
||||
SURFACE_BELOW_FLOOR_M,
|
||||
SURFACE_ABOVE_FLOOR_M,
|
||||
SURFACE_SAMPLES_PER_PAINT,
|
||||
} from './policy.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
BRACKETS_IMAGE,
|
||||
directionWedgePositions,
|
||||
markerScale,
|
||||
paintDirectionWedge,
|
||||
validAlprGroundHeight,
|
||||
} from './visuals.js';
|
||||
|
||||
/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */
|
||||
export function createAlprOverlay({ state, services }) {
|
||||
export function createAlprOverlay({
|
||||
state,
|
||||
services,
|
||||
onSurfaceChange = () => {},
|
||||
}) {
|
||||
let lane,
|
||||
removeMapListener,
|
||||
retryTimer,
|
||||
@@ -22,14 +32,21 @@ export function createAlprOverlay({ state, services }) {
|
||||
let records = [],
|
||||
hits = [],
|
||||
images = [],
|
||||
destroyed = false;
|
||||
let surfaceRegime;
|
||||
destroyed = false,
|
||||
lastCamera = null;
|
||||
const requestPaint = () => {
|
||||
if (!destroyed && state.enabled) lane?.requestPaint();
|
||||
};
|
||||
|
||||
function nativeVisible(entity, visible) {
|
||||
if (!entity) return;
|
||||
canvasOwned(entity, !visible);
|
||||
setShown(entity, visible);
|
||||
}
|
||||
|
||||
/** Swap a marker between its native look and a faint canvas pick target. */
|
||||
function canvasOwned(entity, owned) {
|
||||
const visible = !owned;
|
||||
const billboard = entity.billboard;
|
||||
// Keep a faint native pick target under the canvas badge so sibling layer
|
||||
// handlers recognize ALPR ownership instead of treating the click as empty.
|
||||
@@ -55,7 +72,15 @@ export function createAlprOverlay({ state, services }) {
|
||||
entity.gevAlprNativeAppearance = null;
|
||||
entity.gevAlprPickPosition = null;
|
||||
}
|
||||
billboard.show = visible;
|
||||
}
|
||||
|
||||
// Assign only on change: each Entity property write mints a new property
|
||||
// and raises definitionChanged, which paint used to do for every overlay
|
||||
// camera on every frame.
|
||||
function setShown(entity, visible) {
|
||||
if (entity.gevAlprShown === visible) return;
|
||||
entity.gevAlprShown = visible;
|
||||
entity.billboard.show = visible;
|
||||
if (entity.polyline) entity.polyline.show = visible;
|
||||
if (entity.polygon) entity.polygon.show = visible;
|
||||
}
|
||||
@@ -72,15 +97,25 @@ export function createAlprOverlay({ state, services }) {
|
||||
requestPaint();
|
||||
}
|
||||
|
||||
function anchorFor(record, entity) {
|
||||
function anchorFor(record, entity, budget) {
|
||||
if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition;
|
||||
const scene = state.viewer.scene;
|
||||
const location = Cesium.Cartographic.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
);
|
||||
// A floor-placed marker anchors where its native badge sits; only a
|
||||
// marker still waiting for its floor samples the rendered surface, and
|
||||
// each paint samples a few at most (each sample is a depth render).
|
||||
let height;
|
||||
if (scene.sampleHeightSupported) {
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
|
||||
else if (scene.sampleHeightSupported) {
|
||||
if (budget.samples <= 0) return null;
|
||||
budget.samples -= 1;
|
||||
try {
|
||||
height = scene.sampleHeight(location, [entity]);
|
||||
} catch {
|
||||
@@ -89,19 +124,107 @@ export function createAlprOverlay({ state, services }) {
|
||||
}
|
||||
if (!validAlprGroundHeight(height) && scene.globe.show)
|
||||
height = scene.globe.getHeight?.(location);
|
||||
if (!validAlprGroundHeight(height))
|
||||
height = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
if (!validAlprGroundHeight(height)) return null;
|
||||
setAnchor(record, entity, height);
|
||||
return entity.gevAlprCanvasPosition;
|
||||
}
|
||||
|
||||
function floorHeightAt(latitude, longitude) {
|
||||
const floor = services.groundFloor.cachedGroundFloor(latitude, longitude);
|
||||
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
|
||||
}
|
||||
|
||||
function setAnchor(record, entity, height) {
|
||||
entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
height,
|
||||
);
|
||||
entity.gevAlprWedge = directionWedgePositions(record, height);
|
||||
return entity.gevAlprCanvasPosition;
|
||||
entity.gevAlprWedge = directionWedgePositions(
|
||||
record,
|
||||
height,
|
||||
floorHeightAt,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the visible photoreal tiles (or globe) have finished streaming. */
|
||||
function surfaceSettled(scene) {
|
||||
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
if (primitive?.show && primitive.tilesLoaded === false) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace floor anchors with the rendered surface under each overlay camera.
|
||||
* Floors come from ~111 m cells, so on a slope a badge could float or sink
|
||||
* by tens of metres. Runs only while the camera is still and tiles have
|
||||
* settled, a few depth samples per paint, and each anchor at most once;
|
||||
* samples far outside the floor prior (a roof or a streaming tile) are
|
||||
* rejected. Returns whether anchors remain to check.
|
||||
*/
|
||||
function refineAnchors(budget) {
|
||||
const camera = state.viewer.camera;
|
||||
const scene = state.viewer.scene;
|
||||
const still =
|
||||
lastCamera &&
|
||||
camera.positionWC &&
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.positionWC,
|
||||
lastCamera.position,
|
||||
0,
|
||||
0.05,
|
||||
) &&
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.directionWC,
|
||||
lastCamera.direction,
|
||||
0,
|
||||
1e-6,
|
||||
);
|
||||
if (camera.positionWC && camera.directionWC)
|
||||
lastCamera = {
|
||||
position: Cesium.Cartesian3.clone(camera.positionWC),
|
||||
direction: Cesium.Cartesian3.clone(camera.directionWC),
|
||||
};
|
||||
if (!scene.sampleHeightSupported) return false;
|
||||
let pending = false;
|
||||
for (const record of records) {
|
||||
const entity = state.dataSource.entities.getById(record.id);
|
||||
const anchor = entity?.gevAlprCanvasPosition;
|
||||
if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue;
|
||||
if (!still || !surfaceSettled(scene) || budget.samples <= 0) {
|
||||
pending = true;
|
||||
continue;
|
||||
}
|
||||
budget.samples -= 1;
|
||||
let sample;
|
||||
try {
|
||||
sample = scene.sampleHeight(
|
||||
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude),
|
||||
[entity],
|
||||
);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
const current = Cesium.Cartographic.fromCartesian(anchor).height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
const accepted =
|
||||
validAlprGroundHeight(sample) &&
|
||||
(!validAlprGroundHeight(floor) ||
|
||||
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
|
||||
sample <= floor + SURFACE_ABOVE_FLOOR_M));
|
||||
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
|
||||
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M);
|
||||
entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition;
|
||||
if (entity.id === state.selectedId)
|
||||
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
function paint({ ctx, width, height, keyhole, occluder }) {
|
||||
@@ -109,6 +232,7 @@ export function createAlprOverlay({ state, services }) {
|
||||
if (!state.enabled || destroyed) return;
|
||||
let unresolved = false;
|
||||
const painted = [];
|
||||
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
|
||||
for (const record of records) {
|
||||
const entity = state.dataSource.entities.getById(record.id);
|
||||
if (!entity) continue;
|
||||
@@ -122,23 +246,32 @@ export function createAlprOverlay({ state, services }) {
|
||||
nativeVisible(entity, true);
|
||||
continue;
|
||||
}
|
||||
const anchor = anchorFor(record, entity);
|
||||
const anchor = anchorFor(record, entity, budget);
|
||||
if (!anchor) {
|
||||
nativeVisible(entity, true);
|
||||
unresolved = true;
|
||||
continue;
|
||||
}
|
||||
nativeVisible(entity, false);
|
||||
if (occluder && !occluder.isPointVisible(anchor)) continue;
|
||||
canvasOwned(entity, true);
|
||||
if (occluder && !occluder.isPointVisible(anchor)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const scene = state.viewer.scene;
|
||||
const origin = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
anchor,
|
||||
);
|
||||
if (!origin) continue;
|
||||
if (!origin) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const alpha =
|
||||
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
|
||||
if (!(alpha > 0)) continue;
|
||||
if (!(alpha > 0)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const wedge = entity.gevAlprWedge;
|
||||
if (wedge) {
|
||||
const left = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
@@ -161,15 +294,27 @@ export function createAlprOverlay({ state, services }) {
|
||||
origin.x > width + 60 ||
|
||||
origin.y < -60 ||
|
||||
origin.y > height + 60
|
||||
)
|
||||
) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
entity.billboard.show = true;
|
||||
painted.push({ record, origin, selected, image, alpha });
|
||||
}
|
||||
setShown(entity, true);
|
||||
painted.push({
|
||||
record,
|
||||
origin,
|
||||
selected,
|
||||
image,
|
||||
alpha,
|
||||
scale: markerScale(
|
||||
Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor),
|
||||
),
|
||||
});
|
||||
if (selected) entity.gevAlprDisplayPosition = anchor;
|
||||
}
|
||||
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
|
||||
for (const { record, origin, selected, image, alpha } of painted) {
|
||||
const size = selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE;
|
||||
for (const { record, origin, selected, image, alpha, scale } of painted) {
|
||||
const size =
|
||||
(selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE) * scale;
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
ctx.drawImage(
|
||||
@@ -190,7 +335,10 @@ export function createAlprOverlay({ state, services }) {
|
||||
ctx.restore();
|
||||
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
|
||||
}
|
||||
if (unresolved && !retryTimer && Date.now() < retryUntil) {
|
||||
const refining = refineAnchors({
|
||||
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
|
||||
});
|
||||
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
requestPaint();
|
||||
@@ -201,6 +349,12 @@ export function createAlprOverlay({ state, services }) {
|
||||
return {
|
||||
init() {
|
||||
destroyed = false;
|
||||
removeMapListener = services.overlays?.subscribeMapStack?.((event) => {
|
||||
if (event.detail?.status !== 'ready' || !state.enabled) return;
|
||||
// Same-regime provider changes also invalidate absolute placements.
|
||||
onSurfaceChange();
|
||||
resetAnchors();
|
||||
});
|
||||
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
|
||||
return;
|
||||
lane = services.overlays.registerPaintLane('selected', paint, {
|
||||
@@ -214,14 +368,6 @@ export function createAlprOverlay({ state, services }) {
|
||||
image.src = src;
|
||||
return image;
|
||||
});
|
||||
surfaceRegime = state.viewer.scene.globe.show;
|
||||
removeMapListener = services.overlays.subscribeMapStack?.((event) => {
|
||||
if (event.detail?.status !== 'ready') return;
|
||||
const next = state.viewer.scene.globe.show;
|
||||
if (next === surfaceRegime) return;
|
||||
surfaceRegime = next;
|
||||
resetAnchors();
|
||||
});
|
||||
},
|
||||
sync(visible) {
|
||||
if (!lane) return;
|
||||
|
||||
@@ -2,9 +2,13 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createAlprOverlay } from './overlay.js';
|
||||
import { directionWedgePositions, alprLabelDetails } from './visuals.js';
|
||||
import {
|
||||
directionWedgePositions,
|
||||
alprLabelDetails,
|
||||
markerScale,
|
||||
} from './visuals.js';
|
||||
|
||||
function harness(t, count = 2) {
|
||||
function harness(t, count = 2, { floor = null } = {}) {
|
||||
const previousImage = globalThis.Image;
|
||||
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
globalThis.Image = class {
|
||||
@@ -43,7 +47,7 @@ function harness(t, count = 2) {
|
||||
const overlay = createAlprOverlay({
|
||||
state,
|
||||
services: {
|
||||
groundFloor: { cachedGroundFloor: () => null },
|
||||
groundFloor: { cachedGroundFloor: () => floor },
|
||||
overlays: {
|
||||
registerPaintLane(_lane, painter) {
|
||||
paint = painter;
|
||||
@@ -190,6 +194,20 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
|
||||
assert.equal(h.draw.length, 0);
|
||||
});
|
||||
|
||||
test('repeated paints of a still view never rewrite marker properties', (t) => {
|
||||
// Each Entity write raises definitionChanged; paint used to hide then show
|
||||
// every overlay camera's native marker on every frame.
|
||||
const h = harness(t, 3);
|
||||
h.overlay.sync(h.records);
|
||||
h.paint();
|
||||
let changes = 0;
|
||||
for (const entity of h.entities.values)
|
||||
entity.definitionChanged.addEventListener(() => changes++);
|
||||
for (let i = 0; i < 5; i++) h.paint();
|
||||
assert.equal(changes, 0);
|
||||
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
|
||||
});
|
||||
|
||||
test('adapter labels never claim a custom source is public OSM data', () => {
|
||||
assert.deepEqual(
|
||||
alprLabelDetails(
|
||||
@@ -199,3 +217,49 @@ test('adapter labels never claim a custom source is public OSM data', () => {
|
||||
['Source: Custom directory', 'VENDOR'],
|
||||
);
|
||||
});
|
||||
|
||||
test('overlay glyphs and native badges shrink alike with distance', () => {
|
||||
assert.equal(markerScale(100), 1.15);
|
||||
assert.equal(markerScale(40_000), 0.45);
|
||||
assert.equal(markerScale(90_000), 0.45);
|
||||
assert.ok(Math.abs(markerScale(20_250) - 0.8) < 1e-9);
|
||||
});
|
||||
|
||||
test('a still view replaces floor anchors with the rendered surface, within the floor window', (t) => {
|
||||
// Floors come from ~111 m cells; on a slope a badge floated above the mesh.
|
||||
const h = harness(t, 2, { floor: 150 });
|
||||
const scene = h.state.viewer.scene;
|
||||
const camera = h.state.viewer.camera;
|
||||
camera.directionWC = Cesium.Cartesian3.UNIT_X;
|
||||
scene.sampleHeightSupported = true;
|
||||
scene.primitives = { length: 0, get: () => null };
|
||||
let samples = 0;
|
||||
scene.sampleHeight = (carto) => {
|
||||
samples++;
|
||||
return Cesium.Math.toDegrees(carto.latitude) > 30.00005 ? 400 : 172;
|
||||
};
|
||||
h.overlay.sync(h.records);
|
||||
h.paint();
|
||||
const height = (id) =>
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
h.entities.getById(id).gevAlprCanvasPosition,
|
||||
).height;
|
||||
assert.equal(
|
||||
samples,
|
||||
0,
|
||||
'no depth samples while the camera may still be moving',
|
||||
);
|
||||
assert.ok(Math.abs(height('camera:0') - 151.5) < 0.01, 'floor anchor first');
|
||||
h.paint();
|
||||
assert.ok(
|
||||
Math.abs(height('camera:0') - 173.5) < 0.01,
|
||||
'rendered surface once still',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(height('camera:1') - 151.5) < 0.01,
|
||||
'a rooftop-height sample is rejected',
|
||||
);
|
||||
const taken = samples;
|
||||
h.paint();
|
||||
assert.equal(samples, taken, 'each anchor is checked once');
|
||||
});
|
||||
+42
-21
@@ -1,33 +1,37 @@
|
||||
/**
|
||||
* @file Community-mapped automatic license plate reader (ALPR) camera layer.
|
||||
*
|
||||
* Data source: OpenStreetMap contributors, including the DeFlock community
|
||||
* (`man_made=surveillance` + `surveillance:type=ALPR`) — see
|
||||
* https://wiki.openstreetmap.org/wiki/Tag:surveillance:type=ALPR and
|
||||
* https://deflock.org. OSM data remains ODbL 1.0, separate from the MIT code.
|
||||
* Fetched viewport-bounded through the existing generic
|
||||
* `/api/overpass` proxy (same one `traffic.js` and `militaryInstallations.js`
|
||||
* use) — no new server route needed for a single narrow tag pair.
|
||||
*
|
||||
* This is mapped surveillance infrastructure, not a live camera feed: no
|
||||
* plate records, no vendor accounts, nothing beyond what a contributor chose
|
||||
* to publish to OSM. Coverage and tag accuracy are not guaranteed.
|
||||
*
|
||||
* @module data/alprCameras
|
||||
* Community-mapped OpenStreetMap ALPR locations, via hourly US/Canada detail
|
||||
* tiles. OSM data remains ODbL, separate from the application code. These are
|
||||
* mapped locations, not footage, plate records or evidence of current activity.
|
||||
*/
|
||||
|
||||
export const LAYER_ID = 'alpr-cameras';
|
||||
|
||||
export const OVERPASS_URL = '/api/overpass';
|
||||
|
||||
export const REQUEST_DEBOUNCE_MS = 500;
|
||||
export const REQUEST_DEBOUNCE_MS = 300;
|
||||
|
||||
/** Keep public Overpass queries city-scale, never globe-wide. */
|
||||
/** Keep camera acquisition city-scale, never globe-wide. */
|
||||
export const MAX_VIEWPORT_DEGREES = 3;
|
||||
|
||||
/** Overpass `out body N;` cap — also detects possibly truncated coverage. */
|
||||
/** Camera record cap; reaching it reports limited coverage. */
|
||||
export const QUERY_LIMIT = 1500;
|
||||
|
||||
/**
|
||||
* The extract carries full camera attributes from z9 (z0-8 are geometry-only
|
||||
* heat tiles). Each view uses the finest zoom from z12 down to z9 that fits
|
||||
* DETAIL_MAX_TILES, so a whole city loads from a few z9/z10 tiles and a
|
||||
* neighbourhood from z12 (about 2 m position precision).
|
||||
*/
|
||||
export const DETAIL_MIN_ZOOM = 9;
|
||||
export const DETAIL_MAX_ZOOM = 12;
|
||||
export const DETAIL_MAX_TILES = 16;
|
||||
|
||||
/** Decoded records kept per accepted tile coverage (memory bound, not a render cap). */
|
||||
export const SOURCE_RECORD_LIMIT = 6000;
|
||||
|
||||
/** Best-precision coordinates remembered per camera across zoom changes. */
|
||||
export const PRECISION_CACHE_LIMIT = 20000;
|
||||
|
||||
/** Render cap. Kept at or above QUERY_LIMIT on purpose: if it ever sat below
|
||||
* it, cameras between the two would be silently dropped while `saturated`
|
||||
* stayed false and `count` still reported them — a lie about coverage. */
|
||||
@@ -40,20 +44,37 @@ export const DIRECTION_CONE_HALF_ANGLE_DEG = 20;
|
||||
export const EARTH_MEAN_RADIUS_M = 6371008.8;
|
||||
|
||||
/** Query boxes are snapped outward to this grid so nearby camera moves reuse
|
||||
* one Overpass request body (the shared proxy keys its cache and in-flight
|
||||
* dedupe by the exact body) instead of each becoming a distinct upstream fetch. */
|
||||
* one accepted viewport snapshot rather than rebuilding records on every pan. */
|
||||
export const QUERY_SNAP_DEGREES = 0.05;
|
||||
|
||||
/** A view still fully inside the last snapped query box reuses those records
|
||||
* for this long before asking Overpass again. */
|
||||
* for this long before selecting tiles again. */
|
||||
export const QUERY_REUSE_MS = 10 * 60 * 1000;
|
||||
|
||||
/** Vendor-neutral camera badge palette, with coral selection. */
|
||||
export const ALPR_COLOR = '#52d4ff';
|
||||
export const ALPR_SELECTED_COLOR = '#ff6474';
|
||||
export const MARKER_ICON_SIZE = 38;
|
||||
/** Badge scale by camera distance (near m, scale, far m, scale), shared by
|
||||
* native badges and overlay glyphs so both shrink alike in city-wide views. */
|
||||
export const MARKER_SCALE_BY_DISTANCE = Object.freeze([
|
||||
500, 1.15, 40_000, 0.45,
|
||||
]);
|
||||
export const SELECTED_MARKER_ICON_SIZE = 60;
|
||||
export const MAX_CANVAS_FRUSTUMS = 64;
|
||||
|
||||
/** Metres a floor-placed marker sits above its resolved ground cell. */
|
||||
export const MARKER_FLOOR_LIFT_M = 1.5;
|
||||
|
||||
/** Rendered-surface samples one overlay paint may take (each is a depth render). */
|
||||
export const ANCHOR_SAMPLES_PER_PAINT = 4;
|
||||
|
||||
/** Accepted rendered-surface window around a floor cell (a cut or an embankment
|
||||
* sits within it; a rooftop or an unstreamed tile usually does not). */
|
||||
export const SURFACE_BELOW_FLOOR_M = 30;
|
||||
/** Rendered-surface refinements per paint while the camera is still. */
|
||||
export const SURFACE_SAMPLES_PER_PAINT = 2;
|
||||
export const SURFACE_ABOVE_FLOOR_M = 40;
|
||||
|
||||
/** OSM attribution may collapse after five seconds; full credit stays in Data attribution. */
|
||||
export const CREDIT_DISPLAY_MS = 5000;
|
||||
+244
-51
@@ -9,15 +9,17 @@ import {
|
||||
MARKER_ICON_SIZE,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
CREDIT_DISPLAY_MS,
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
MARKER_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
import { boxContains } from './model.js';
|
||||
import { createAlprFloorResolver } from './floors.js';
|
||||
import { createAlprOverlay } from './overlay.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
alprDisplayId,
|
||||
alprLabelDetails,
|
||||
directionWedgePositions,
|
||||
validAlprGroundHeight,
|
||||
} from './visuals.js';
|
||||
|
||||
@@ -32,9 +34,198 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
} = services.context;
|
||||
|
||||
const { cachedGroundFloor } = services.groundFloor;
|
||||
const overlay = createAlprOverlay({ state, services });
|
||||
const overlay = createAlprOverlay({
|
||||
state,
|
||||
services,
|
||||
onSurfaceChange: refreshMarkerPlacements,
|
||||
});
|
||||
let visibleRecords = [];
|
||||
let selectionStartedAt = 0;
|
||||
/** Markers still clamped while their floor cell resolves (id -> entity). */
|
||||
const clampedMarkers = new Map();
|
||||
let floorResolve = null;
|
||||
const floors = createAlprFloorResolver(services.groundFloor);
|
||||
|
||||
/**
|
||||
* Marker placement from the cached ground floor (validated mesh or DEM, the
|
||||
* ellipsoidal datum every layer shares). Ground clamping on photoreal tiles
|
||||
* re-samples every clamped marker whenever a tile streams in, which made a
|
||||
* whole-city view stutter while zooming, so it is only the placeholder for
|
||||
* a cell that has not resolved yet.
|
||||
* @param {{latitude:number, longitude:number}} record Camera.
|
||||
* @returns {{position: Cesium.Cartesian3, clamped: boolean}} Placement.
|
||||
*/
|
||||
function markerPlacement(record) {
|
||||
const floor = cachedGroundFloor(record.latitude, record.longitude);
|
||||
const clamped = !validAlprGroundHeight(floor);
|
||||
return {
|
||||
clamped,
|
||||
position: Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
clamped ? 0 : floor + MARKER_FLOOR_LIFT_M,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Records the current view would display (viewport box, nearest first when capped). */
|
||||
function viewRecords(records) {
|
||||
const box = viewportBox(state.viewer);
|
||||
if (!box) return { box, visible: [], capped: false };
|
||||
let visible = records.filter((record) =>
|
||||
boxContains(box, {
|
||||
south: record.latitude,
|
||||
north: record.latitude,
|
||||
west: record.longitude,
|
||||
east: record.longitude,
|
||||
}),
|
||||
);
|
||||
const capped = visible.length > MAX_RENDERED;
|
||||
if (capped) {
|
||||
const lat = (box.south + box.north) / 2;
|
||||
const lon = (box.west + box.east) / 2;
|
||||
const scale = Math.cos((lat * Math.PI) / 180);
|
||||
const distance = (record) =>
|
||||
(record.latitude - lat) ** 2 + ((record.longitude - lon) * scale) ** 2;
|
||||
visible = visible
|
||||
.map((record) => ({ record, d: distance(record) }))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
.slice(0, MAX_RENDERED)
|
||||
.map((item) => item.record);
|
||||
}
|
||||
return { box, visible, capped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the floor cells of the records this view will display, waiting at
|
||||
* most the ground service's bounded deadline. Never throws.
|
||||
* @param {Array<object>} records Candidate records.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function prepareFloors(records) {
|
||||
const resolve = services.groundFloor.resolveGroundFloorCells;
|
||||
if (typeof resolve !== 'function') return;
|
||||
const cold = viewRecords(records)
|
||||
.visible.filter(
|
||||
(record) =>
|
||||
!validAlprGroundHeight(
|
||||
cachedGroundFloor(record.latitude, record.longitude),
|
||||
),
|
||||
)
|
||||
.map((record) => ({ lat: record.latitude, lon: record.longitude }));
|
||||
if (!cold.length) return;
|
||||
try {
|
||||
await floors.prepare(cold);
|
||||
} catch {
|
||||
/* markers fall back to clamping until their floors resolve */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loaded cameras that project inside the canvas and in front of the globe.
|
||||
* "Nearby" spans twice the camera-to-ground range, so a view can hold
|
||||
* cameras while none is on screen; the row then says so rather than
|
||||
* leaving the user to wait for markers. Runs once per render pass.
|
||||
* @returns {number|null} Count, or null without a scene to project into.
|
||||
*/
|
||||
function countOnScreen() {
|
||||
const scene = state.viewer?.scene;
|
||||
const canvas = scene?.canvas;
|
||||
const width = canvas?.clientWidth || canvas?.width;
|
||||
const height = canvas?.clientHeight || canvas?.height;
|
||||
const camera = state.viewer?.camera;
|
||||
if (!scene || !width || !height || !camera?.positionWC) return null;
|
||||
const occluder = new Cesium.EllipsoidalOccluder(
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
camera.positionWC,
|
||||
);
|
||||
let count = 0;
|
||||
try {
|
||||
for (const entity of state.dataSource.entities.values) {
|
||||
const position = entity.position?.getValue?.(Cesium.JulianDate.now());
|
||||
if (!position || !occluder.isPointVisible(position)) continue;
|
||||
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
);
|
||||
if (
|
||||
point &&
|
||||
point.x >= 0 &&
|
||||
point.x <= width &&
|
||||
point.y >= 0 &&
|
||||
point.y <= height
|
||||
)
|
||||
count += 1;
|
||||
}
|
||||
} catch {
|
||||
// A scene without a usable frame (startup, teardown) cannot answer.
|
||||
return null;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Write a marker position, respecting the overlay's pick-target swap. */
|
||||
function setMarkerPosition(entity, position, clamped) {
|
||||
const heightReference = clamped
|
||||
? Cesium.HeightReference.CLAMP_TO_GROUND
|
||||
: Cesium.HeightReference.NONE;
|
||||
const saved = entity.gevAlprNativeAppearance;
|
||||
if (saved) {
|
||||
saved.position = position;
|
||||
saved.heightReference = heightReference;
|
||||
} else {
|
||||
entity.position = position;
|
||||
entity.billboard.heightReference = heightReference;
|
||||
}
|
||||
entity.gevAlprClamped = clamped;
|
||||
}
|
||||
|
||||
/** Refresh all native placements, including the appearances held by the canvas. */
|
||||
function refreshMarkerPlacements() {
|
||||
if (!state.enabled || !state.dataSource) return;
|
||||
clampedMarkers.clear();
|
||||
for (const entity of state.dataSource.entities.values) {
|
||||
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
|
||||
setMarkerPosition(entity, position, clamped);
|
||||
if (clamped) clampedMarkers.set(entity.id, entity);
|
||||
}
|
||||
resolveClampedFloors();
|
||||
governorRequestRender('alpr-surface');
|
||||
}
|
||||
|
||||
/** Resolve floors for clamped markers once, then place them in place. */
|
||||
function resolveClampedFloors() {
|
||||
const resolve = services.groundFloor.resolveGroundFloorCells;
|
||||
if (floorResolve || !clampedMarkers.size || typeof resolve !== 'function')
|
||||
return;
|
||||
const batch = [...clampedMarkers.values()];
|
||||
const request = Promise.resolve(
|
||||
floors.resolve(
|
||||
batch.map((entity) => ({
|
||||
lat: entity.gevAlprRecord.latitude,
|
||||
lon: entity.gevAlprRecord.longitude,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
if (floorResolve !== request) return;
|
||||
floorResolve = null;
|
||||
if (!state.enabled || !state.dataSource) return;
|
||||
let moved = false;
|
||||
for (const entity of batch) {
|
||||
if (clampedMarkers.get(entity.id) !== entity) continue;
|
||||
clampedMarkers.delete(entity.id);
|
||||
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
|
||||
if (clamped) continue;
|
||||
setMarkerPosition(entity, position, false);
|
||||
moved = true;
|
||||
}
|
||||
if (moved) governorRequestRender('alpr-floor');
|
||||
// Cells that never resolved stay clamped; later renders retry them.
|
||||
});
|
||||
floorResolve = request;
|
||||
}
|
||||
|
||||
function updateAppearance(entity, selected) {
|
||||
const color = Cesium.Color.fromCssColorString(
|
||||
@@ -44,12 +235,6 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
entity.billboard.width = entity.billboard.height = selected
|
||||
? SELECTED_MARKER_ICON_SIZE
|
||||
: MARKER_ICON_SIZE;
|
||||
if (entity.polyline) {
|
||||
entity.polyline.width = selected ? 3 : 1.75;
|
||||
entity.polyline.material = color.withAlpha(selected ? 0.98 : 0.82);
|
||||
}
|
||||
if (entity.polygon)
|
||||
entity.polygon.material = color.withAlpha(selected ? 0.8 : 0.2);
|
||||
if (entity.gevLabelModel) {
|
||||
entity.gevLabelModel.accent = color.toCssColorString();
|
||||
entity.gevLabelModel.leaderAnimationStartedAt = selected
|
||||
@@ -118,13 +303,18 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
}
|
||||
|
||||
function clearRendered() {
|
||||
hideOnMapCredit();
|
||||
floors.cancel();
|
||||
floorResolve = null;
|
||||
overlay.clear();
|
||||
visibleRecords = [];
|
||||
clampedMarkers.clear();
|
||||
if (state.dataSource?.entities) state.dataSource.entities.removeAll();
|
||||
removeEntityContextsForLayer(LAYER_ID);
|
||||
}
|
||||
|
||||
function hideOnMapCredit() {
|
||||
services.credits?.hideOsmCredit?.(state.viewer, LAYER_ID);
|
||||
clearTimeout(state.creditTimer);
|
||||
state.creditTimer = null;
|
||||
if (state.credit)
|
||||
@@ -133,6 +323,14 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
}
|
||||
|
||||
function presentOnMapCredit() {
|
||||
if (
|
||||
state.enabled &&
|
||||
source.attribution?.name === 'OpenStreetMap' &&
|
||||
services.credits?.showOsmCredit
|
||||
) {
|
||||
services.credits.showOsmCredit(state.viewer, LAYER_ID);
|
||||
return;
|
||||
}
|
||||
if (!state.enabled || state.creditPresented || !state.credit) return;
|
||||
state.creditPresented = true;
|
||||
state.viewer.creditDisplay?.addStaticCredit(state.credit);
|
||||
@@ -142,19 +340,10 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
|
||||
function renderRecords() {
|
||||
const selectedContext = getSelectedEntityContext();
|
||||
const box = viewportBox(state.viewer);
|
||||
const visible = box
|
||||
? state.records
|
||||
.filter((record) =>
|
||||
boxContains(box, {
|
||||
south: record.latitude,
|
||||
north: record.latitude,
|
||||
west: record.longitude,
|
||||
east: record.longitude,
|
||||
}),
|
||||
)
|
||||
.slice(0, MAX_RENDERED)
|
||||
: [];
|
||||
// Over the render cap, keep the cameras nearest the view centre and say
|
||||
// coverage is limited rather than dropping an arbitrary subset.
|
||||
const { visible, capped } = viewRecords(state.records);
|
||||
state.renderSaturated = capped;
|
||||
visibleRecords = visible;
|
||||
// A refresh may retain its own selection, never reclaim one cleared or
|
||||
// replaced by an aircraft, another layer, or a voice action.
|
||||
@@ -168,8 +357,14 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
}
|
||||
governorRequestRender('alpr-render');
|
||||
const visibleIds = new Set(visible.map((record) => record.id));
|
||||
let changed = false;
|
||||
state.dataSource.entities.suspendEvents();
|
||||
for (const entity of [...state.dataSource.entities.values]) {
|
||||
if (!visibleIds.has(entity.id)) state.dataSource.entities.remove(entity);
|
||||
if (!visibleIds.has(entity.id)) {
|
||||
state.dataSource.entities.remove(entity);
|
||||
clampedMarkers.delete(entity.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds });
|
||||
for (const record of visible) {
|
||||
@@ -180,10 +375,11 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
}
|
||||
const color = markerColor();
|
||||
const selected = record.id === state.selectedId;
|
||||
const position = Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
);
|
||||
const { position, clamped } = markerPlacement(record);
|
||||
// Direction wedges are painted by the overlay for the nearest cameras.
|
||||
// Native ground-clamped wedges (a ground polyline plus a classification
|
||||
// polygon per camera) cost ~40 ms per frame for 200 downtown cameras on
|
||||
// photoreal tiles, so markers stay billboards only.
|
||||
const entityDef = {
|
||||
id: record.id,
|
||||
position,
|
||||
@@ -191,38 +387,30 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
image: selected ? SELECTED_IMAGE : MARKER_IMAGE,
|
||||
width: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
|
||||
height: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
heightReference: clamped
|
||||
? Cesium.HeightReference.CLAMP_TO_GROUND
|
||||
: Cesium.HeightReference.NONE,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
scaleByDistance: new Cesium.NearFarScalar(350, 1.15, 4_000_000, 0.48),
|
||||
// City-wide views hold hundreds of badges; let them shrink.
|
||||
scaleByDistance: new Cesium.NearFarScalar(
|
||||
...MARKER_SCALE_BY_DISTANCE,
|
||||
),
|
||||
},
|
||||
};
|
||||
const wedge = directionWedgePositions(record);
|
||||
if (wedge) {
|
||||
entityDef.polyline = {
|
||||
positions: [wedge[1], position, wedge[2]],
|
||||
width: selected ? 3 : 1.75,
|
||||
material: color.withAlpha(0.82),
|
||||
clampToGround: true,
|
||||
};
|
||||
entityDef.polygon = {
|
||||
hierarchy: wedge,
|
||||
material: color.withAlpha(0.2),
|
||||
height: 0,
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
classificationType: Cesium.ClassificationType.BOTH,
|
||||
};
|
||||
}
|
||||
let entity = existing;
|
||||
// Keep the Cesium entity and its ground-clamping subscription while its
|
||||
// geometry is unchanged. Updating metadata must not rebuild the marker.
|
||||
const previous = entity?.gevAlprRecord;
|
||||
if (!entity) entity = state.dataSource.entities.add(entityDef);
|
||||
else {
|
||||
if (!entity) {
|
||||
entity = state.dataSource.entities.add(entityDef);
|
||||
entity.gevAlprClamped = clamped;
|
||||
changed = true;
|
||||
} else {
|
||||
if (
|
||||
previous.latitude !== record.latitude ||
|
||||
previous.longitude !== record.longitude
|
||||
) {
|
||||
entity.position = position;
|
||||
setMarkerPosition(entity, position, clamped);
|
||||
entity.gevAlprCanvasPosition = null;
|
||||
entity.gevAlprDisplayPosition = null;
|
||||
}
|
||||
@@ -231,8 +419,6 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
previous.longitude !== record.longitude ||
|
||||
previous.directionDeg !== record.directionDeg
|
||||
) {
|
||||
entity.polyline = entityDef.polyline;
|
||||
entity.polygon = entityDef.polygon;
|
||||
entity.gevAlprCanvasPosition = null;
|
||||
entity.gevAlprWedge = null;
|
||||
}
|
||||
@@ -281,6 +467,12 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
},
|
||||
});
|
||||
}
|
||||
state.dataSource.entities.resumeEvents();
|
||||
if (changed) state.renderRevision += 1;
|
||||
state.onScreen = countOnScreen();
|
||||
for (const entity of state.dataSource.entities.values)
|
||||
if (entity.gevAlprClamped) clampedMarkers.set(entity.id, entity);
|
||||
resolveClampedFloors();
|
||||
const selectedEntity = state.selectedId
|
||||
? state.dataSource.entities.getById(state.selectedId)
|
||||
: null;
|
||||
@@ -288,9 +480,9 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
updateSelectedAnchor();
|
||||
overlay.sync(visible);
|
||||
if (selectedEntity) services.overlays?.refreshReadout?.(selectedEntity);
|
||||
// Start only when mapped data is actually displayed, not while an upstream
|
||||
// request or a zoom-in prompt could consume the five-second introduction.
|
||||
// Keep the on-map credit tied to displayed data, not loading or zoom prompts.
|
||||
if (visible.length) presentOnMapCredit();
|
||||
else hideOnMapCredit();
|
||||
}
|
||||
|
||||
function focusNearest() {
|
||||
@@ -458,5 +650,6 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
clearSelection,
|
||||
updateSelectedAnchor,
|
||||
installInteraction,
|
||||
prepareFloors,
|
||||
};
|
||||
}
|
||||
+191
-2
@@ -1,10 +1,199 @@
|
||||
import { tilesForBounds, tileToBBox } from '../../data/tomtomTiles.js';
|
||||
import {
|
||||
OVERPASS_URL,
|
||||
QUERY_LIMIT,
|
||||
MAX_VIEWPORT_DEGREES,
|
||||
QUERY_SNAP_DEGREES,
|
||||
QUERY_LIMIT,
|
||||
DETAIL_MIN_ZOOM,
|
||||
DETAIL_MAX_ZOOM,
|
||||
DETAIL_MAX_TILES,
|
||||
SOURCE_RECORD_LIMIT,
|
||||
PRECISION_CACHE_LIMIT,
|
||||
} from './policy.js';
|
||||
import {
|
||||
createVectorTileSource,
|
||||
validTileBounds,
|
||||
} from '../../sources/vectorTiles.js';
|
||||
import { buildOverpassQuery, normalizeAlprNode } from './records.js';
|
||||
import { decodeAlprTile } from './tileRecords.js';
|
||||
|
||||
/**
|
||||
* Finest attributed extract zoom whose tiles for `box` fit the per-view cap,
|
||||
* or null when even z9 would not (the layer asks the user to zoom in).
|
||||
* @param {{south:number, west:number, north:number, east:number}} box View box.
|
||||
* @returns {number|null} Tile zoom.
|
||||
*/
|
||||
export function alprDetailZoom(box) {
|
||||
for (let zoom = DETAIL_MAX_ZOOM; zoom >= DETAIL_MIN_ZOOM; zoom--)
|
||||
if (
|
||||
tilesForBounds(box, zoom, { maxTiles: DETAIL_MAX_TILES + 1 }).length <=
|
||||
DETAIL_MAX_TILES
|
||||
)
|
||||
return zoom;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tile coordinates are quantized per zoom (about 19 m at z9, 2 m at z12).
|
||||
* Remember each camera's finest position so zooming out never nudges a marker
|
||||
* that a closer view already placed precisely. Bounded, oldest first.
|
||||
* @param {number} [limit] Cameras remembered.
|
||||
* @returns {{apply: (record: object, zoom: number) => object, clear: () => void,
|
||||
* size: () => number}} Cache.
|
||||
*/
|
||||
export function createAlprPrecisionCache(limit = PRECISION_CACHE_LIMIT) {
|
||||
const known = new Map();
|
||||
return {
|
||||
apply(record, zoom) {
|
||||
const finer = known.get(record.id);
|
||||
if (finer && finer.zoom > zoom)
|
||||
return finer.latitude === record.latitude &&
|
||||
finer.longitude === record.longitude
|
||||
? record
|
||||
: { ...record, latitude: finer.latitude, longitude: finer.longitude };
|
||||
known.delete(record.id);
|
||||
known.set(record.id, {
|
||||
zoom,
|
||||
latitude: record.latitude,
|
||||
longitude: record.longitude,
|
||||
});
|
||||
while (known.size > limit) known.delete(known.keys().next().value);
|
||||
return record;
|
||||
},
|
||||
clear: () => known.clear(),
|
||||
size: () => known.size,
|
||||
};
|
||||
}
|
||||
|
||||
/** Construct the viewport-bounded OpenStreetMap hourly extract adapter. */
|
||||
export function createAlprTileSource({
|
||||
tileFetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
const sources = ['us', 'ca'].map((country) =>
|
||||
createVectorTileSource({
|
||||
tileJsonUrl: `https://tiles.dontgetflocked.com/cameras-${country}-hourly.json`,
|
||||
allowedOrigin: 'https://tiles.dontgetflocked.com',
|
||||
decode: decodeAlprTile,
|
||||
fetchImpl: tileFetchImpl,
|
||||
maxTiles: DETAIL_MAX_TILES,
|
||||
ttlMs: 60 * 60 * 1000,
|
||||
}),
|
||||
);
|
||||
const precision = createAlprPrecisionCache();
|
||||
const precise = precision.apply;
|
||||
return {
|
||||
/**
|
||||
* Read the camera records for every extract tile covering `box`.
|
||||
* @param {{south:number, west:number, north:number, east:number}} box View box.
|
||||
* @param {AbortSignal} [signal] Cancellation.
|
||||
* @returns {Promise<{records: Array<object>, stale: boolean, saturated: boolean,
|
||||
* noCoverage?: boolean, zoomIn?: boolean, coverage?: object, zoom?: number}>}
|
||||
* Records inside the fetched tiles; `coverage` is those tiles' bounds.
|
||||
*/
|
||||
async fetch(box, signal) {
|
||||
if (
|
||||
!validTileBounds(box) ||
|
||||
box.north - box.south >
|
||||
MAX_VIEWPORT_DEGREES + 2 * QUERY_SNAP_DEGREES + 1e-9 ||
|
||||
box.east - box.west >
|
||||
MAX_VIEWPORT_DEGREES + 2 * QUERY_SNAP_DEGREES + 1e-9
|
||||
)
|
||||
throw new TypeError('ALPR requires a bounded city viewport');
|
||||
signal?.throwIfAborted();
|
||||
// Fast geographic rejection; the exact extract extents below refine coverage.
|
||||
if (box.east < -180 || box.west > -50 || box.north < 17 || box.south > 84)
|
||||
return {
|
||||
records: [],
|
||||
stale: false,
|
||||
saturated: false,
|
||||
noCoverage: true,
|
||||
};
|
||||
const zoom = alprDetailZoom(box);
|
||||
if (zoom === null)
|
||||
return { records: [], stale: false, saturated: false, zoomIn: true };
|
||||
const tiles = tilesForBounds(box, zoom, {
|
||||
maxTiles: DETAIL_MAX_TILES + 1,
|
||||
});
|
||||
const tileBounds = tiles.map((tile) => tileToBBox(zoom, tile.x, tile.y));
|
||||
const coverage = {
|
||||
south: Math.min(...tileBounds.map((b) => b.south)),
|
||||
west: Math.min(...tileBounds.map((b) => b.west)),
|
||||
north: Math.max(...tileBounds.map((b) => b.north)),
|
||||
east: Math.max(...tileBounds.map((b) => b.east)),
|
||||
};
|
||||
const records = new Map();
|
||||
let covered = false,
|
||||
partial = false;
|
||||
for (const [index, source] of sources.entries()) {
|
||||
if (
|
||||
index === 1 &&
|
||||
(box.north < 41 ||
|
||||
box.south > 84 ||
|
||||
box.east < -142 ||
|
||||
box.west > -52)
|
||||
)
|
||||
continue;
|
||||
const metadata = await source.getMetadata(signal);
|
||||
const [west, south, east, north] = metadata.bounds || [];
|
||||
if (![west, south, east, north].every(Number.isFinite))
|
||||
throw new Error('Camera coverage unavailable');
|
||||
if (
|
||||
box.east < west ||
|
||||
box.west > east ||
|
||||
box.north < south ||
|
||||
box.south > north
|
||||
)
|
||||
continue;
|
||||
covered = true;
|
||||
const result = await source.fetchBounds(box, { zoom, signal });
|
||||
partial ||= result.partial;
|
||||
for (const record of result.tiles.flat())
|
||||
records.set(record.id, precise(record, zoom));
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
let list = [...records.values()];
|
||||
const truncated = list.length > SOURCE_RECORD_LIMIT;
|
||||
if (truncated) {
|
||||
// Keep the cameras nearest the view centre when a dense metro overflows.
|
||||
const lat = (box.south + box.north) / 2;
|
||||
const lon = (box.west + box.east) / 2;
|
||||
const scale = Math.cos((lat * Math.PI) / 180);
|
||||
list = list
|
||||
.map((record) => ({
|
||||
record,
|
||||
d:
|
||||
(record.latitude - lat) ** 2 +
|
||||
((record.longitude - lon) * scale) ** 2,
|
||||
}))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
.slice(0, SOURCE_RECORD_LIMIT)
|
||||
.map((item) => item.record);
|
||||
}
|
||||
return {
|
||||
records: list,
|
||||
stale: false,
|
||||
saturated: partial || truncated,
|
||||
noCoverage: !covered,
|
||||
// A partial or truncated read does not cover its tiles; reuse only the box.
|
||||
coverage: partial || truncated ? { ...box } : coverage,
|
||||
zoom,
|
||||
};
|
||||
},
|
||||
detailZoom: alprDetailZoom,
|
||||
destroy() {
|
||||
for (const source of sources) source.clear();
|
||||
precision.clear();
|
||||
},
|
||||
label: 'OpenStreetMap · community mapped',
|
||||
attribution: {
|
||||
name: 'OpenStreetMap',
|
||||
description: '© OpenStreetMap contributors, ODbL',
|
||||
text: '© OpenStreetMap contributors, ODbL',
|
||||
href: 'https://www.openstreetmap.org/copyright',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Construct the bounded OSM request adapter without starting a request. */
|
||||
export function createOverpassAlprSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
@@ -75,7 +264,7 @@ export function createOverpassAlprSource({
|
||||
attribution: {
|
||||
name: 'OpenStreetMap',
|
||||
description: 'OpenStreetMap contributors (ODbL 1.0; community mapped)',
|
||||
text: '© OpenStreetMap',
|
||||
text: '© OpenStreetMap contributors',
|
||||
href: 'https://www.openstreetmap.org/copyright',
|
||||
},
|
||||
};
|
||||
|
||||
+211
-38
@@ -1,12 +1,19 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createOverpassAlprSource } from './source.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
alprDetailZoom,
|
||||
createAlprPrecisionCache,
|
||||
createAlprTileSource,
|
||||
createOverpassAlprSource,
|
||||
buildOverpassQuery,
|
||||
} from './source.js';
|
||||
import { validateAlprSnapshot, alprCreditMarkup } from './model.js';
|
||||
const box = { south: 30, west: -98, north: 30.1, east: -97.9 };
|
||||
test('the source rejects invalid and unbounded queries before fetching', async () => {
|
||||
let calls = 0;
|
||||
const source = createOverpassAlprSource({
|
||||
fetchImpl() {
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl() {
|
||||
calls++;
|
||||
},
|
||||
});
|
||||
@@ -21,55 +28,77 @@ test('the source rejects invalid and unbounded queries before fetching', async (
|
||||
}
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
test('cancellation during body parsing rejects even when the transport ignores it', async () => {
|
||||
const fixture = readFileSync(
|
||||
new URL(
|
||||
'../../data/fixtures/osm-alpr-austin-11-467-843.pbf',
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const metadata = (country) => ({
|
||||
tiles: [
|
||||
`https://tiles.dontgetflocked.com/cameras-${country}-hourly/{z}/{x}/{y}.mvt`,
|
||||
],
|
||||
bounds: country === 'ca' ? [-124, 42, -63, 54] : [-160, 17, -64, 59],
|
||||
});
|
||||
const austin = { south: 30.2, north: 30.35, west: -97.85, east: -97.65 };
|
||||
|
||||
test('cancellation while reading TileJSON is preserved even if fetch ignores it', async () => {
|
||||
const abort = new AbortController();
|
||||
const source = createOverpassAlprSource({
|
||||
fetchImpl: async () => ({
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: async () => ({
|
||||
ok: true,
|
||||
headers: new Headers(),
|
||||
json: async () => {
|
||||
async text() {
|
||||
abort.abort();
|
||||
return { elements: [] };
|
||||
return JSON.stringify(metadata('us'));
|
||||
},
|
||||
}),
|
||||
});
|
||||
await assert.rejects(source.fetch(box, abort.signal), { name: 'AbortError' });
|
||||
await assert.rejects(source.fetch(austin, abort.signal), {
|
||||
name: 'AbortError',
|
||||
});
|
||||
});
|
||||
|
||||
test('Overpass normalization returns camera records and preserves limited/stale coverage', async () => {
|
||||
const source = createOverpassAlprSource({
|
||||
fetchImpl: async () => ({
|
||||
ok: true,
|
||||
headers: new Headers({ 'x-overpass-cache': 'STALE' }),
|
||||
json: async () => ({
|
||||
elements: [
|
||||
{
|
||||
type: 'node',
|
||||
id: 12,
|
||||
lat: 30,
|
||||
lon: -98,
|
||||
tags: {
|
||||
'surveillance:type': 'camera;ALPR',
|
||||
'camera:direction': '90',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
test('extract detail tiles map OSM records and repeated pans reuse decoded tiles', async () => {
|
||||
const calls = [];
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: async (url) => {
|
||||
calls.push(url);
|
||||
return url.endsWith('.json')
|
||||
? Response.json(metadata(url.includes('-ca-') ? 'ca' : 'us'))
|
||||
: new Response(fixture);
|
||||
},
|
||||
});
|
||||
const snapshot = await source.fetch(box);
|
||||
assert.equal(snapshot.records[0].id, 'alpr:12');
|
||||
assert.equal(snapshot.records[0].latitude, 30);
|
||||
assert.equal(snapshot.records[0].directionDeg, 90);
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.saturated, false);
|
||||
const snapshot = await source.fetch(austin);
|
||||
assert.ok(snapshot.records.length > 0);
|
||||
const record = snapshot.records[0];
|
||||
assert.match(record.id, /^alpr:/);
|
||||
assert.equal(record.manufacturer, 'Flock Safety');
|
||||
assert.equal(record.lastVerified, null);
|
||||
assert.ok(record.osmTimestamp);
|
||||
assert.equal(snapshot.stale, false);
|
||||
assert.equal('elements' in snapshot, false);
|
||||
const fetched = calls.length;
|
||||
await source.fetch(austin);
|
||||
assert.equal(calls.length, fetched);
|
||||
assert.ok(calls.every((url) => !url.includes('overpass')));
|
||||
assert.doesNotMatch(JSON.stringify(source.attribution), /flock/i);
|
||||
});
|
||||
|
||||
test('outside extract coverage is an explicit no-data state without Overpass', async () => {
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: () => assert.fail('no network expected in Europe'),
|
||||
});
|
||||
assert.deepEqual(
|
||||
await source.fetch({ south: 51, north: 51.1, west: 0, east: 0.1 }),
|
||||
{ records: [], stale: false, saturated: false, noCoverage: true },
|
||||
);
|
||||
});
|
||||
|
||||
test('an unsuccessful source response releases its body before reporting an error', async () => {
|
||||
let cancelled = 0;
|
||||
const source = createOverpassAlprSource({
|
||||
fetchImpl: async () => ({
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: async () => ({
|
||||
ok: false,
|
||||
status: 429,
|
||||
body: {
|
||||
@@ -79,7 +108,7 @@ test('an unsuccessful source response releases its body before reporting an erro
|
||||
},
|
||||
}),
|
||||
});
|
||||
await assert.rejects(source.fetch(box), /rate-limited/);
|
||||
await assert.rejects(source.fetch(box), /unavailable/);
|
||||
assert.equal(cancelled, 1);
|
||||
});
|
||||
|
||||
@@ -115,3 +144,147 @@ test('provider attribution escapes markup and rejects executable links', () => {
|
||||
assert.ok(html.includes('?a=1&b=2'));
|
||||
assert.ok(!html.includes('<img'));
|
||||
});
|
||||
|
||||
test('wide detail view returns zoom guidance before any fetch and can retry a smaller view', async () => {
|
||||
let calls = 0;
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: async () => {
|
||||
calls++;
|
||||
return Response.json({
|
||||
tiles: ['https://tiles.dontgetflocked.com/{z}/{x}/{y}.pbf'],
|
||||
bounds: [-180, 17, -50, 84],
|
||||
});
|
||||
},
|
||||
});
|
||||
const wide = await source.fetch({
|
||||
south: 29,
|
||||
north: 32,
|
||||
west: -99,
|
||||
east: -96,
|
||||
});
|
||||
assert.equal(wide.zoomIn, true);
|
||||
assert.equal(calls, 0);
|
||||
await source
|
||||
.fetch({ south: 30.267, north: 30.268, west: -97.744, east: -97.743 })
|
||||
.catch(() => {});
|
||||
assert.ok(calls > 0);
|
||||
});
|
||||
|
||||
test('each view reads the finest attributed extract zoom that fits 16 tiles', () => {
|
||||
// Field report: a z11-only read refused whole-city views. Attributed detail
|
||||
// exists from z9, so a city reads a few z9/z10 tiles and a street z12.
|
||||
assert.equal(
|
||||
alprDetailZoom({ south: 30.29, north: 30.31, west: -97.78, east: -97.75 }),
|
||||
12,
|
||||
);
|
||||
assert.equal(
|
||||
alprDetailZoom({ south: 30.17, north: 30.36, west: -97.85, east: -97.63 }),
|
||||
12,
|
||||
);
|
||||
assert.equal(
|
||||
alprDetailZoom({ south: 29.7, north: 30.7, west: -98.25, east: -97.25 }),
|
||||
10,
|
||||
);
|
||||
assert.equal(
|
||||
alprDetailZoom({ south: 29.2, north: 31.2, west: -98.75, east: -96.75 }),
|
||||
9,
|
||||
);
|
||||
assert.equal(
|
||||
alprDetailZoom({ south: 29, north: 32, west: -99, east: -96 }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('a whole-city view loads cameras and reports the tiles it covers', async () => {
|
||||
const urls = [];
|
||||
const source = createAlprTileSource({
|
||||
tileFetchImpl: async (url) => {
|
||||
urls.push(url);
|
||||
return url.endsWith('.json')
|
||||
? Response.json(metadata(url.includes('-ca-') ? 'ca' : 'us'))
|
||||
: new Response(fixture);
|
||||
},
|
||||
});
|
||||
const city = { south: 29.95, north: 30.55, west: -98.05, east: -97.45 };
|
||||
const snapshot = await source.fetch(city);
|
||||
assert.equal(snapshot.zoomIn, undefined);
|
||||
assert.equal(snapshot.zoom, 10);
|
||||
assert.ok(snapshot.records.length > 0);
|
||||
assert.ok(urls.some((url) => url.includes('/10/')));
|
||||
for (const key of ['south', 'west'])
|
||||
assert.ok(snapshot.coverage[key] <= city[key]);
|
||||
for (const key of ['north', 'east'])
|
||||
assert.ok(snapshot.coverage[key] >= city[key]);
|
||||
});
|
||||
|
||||
test('coarser tiles never move a camera a finer tile already placed', () => {
|
||||
const cache = createAlprPrecisionCache(2);
|
||||
const fine = {
|
||||
id: 'alpr:1',
|
||||
latitude: 30.30001,
|
||||
longitude: -97.76001,
|
||||
operator: 'A',
|
||||
};
|
||||
assert.equal(cache.apply(fine, 12), fine);
|
||||
const coarse = {
|
||||
...fine,
|
||||
latitude: 30.3001,
|
||||
longitude: -97.7602,
|
||||
operator: 'B',
|
||||
};
|
||||
const kept = cache.apply(coarse, 9);
|
||||
assert.equal(kept.latitude, fine.latitude);
|
||||
assert.equal(kept.longitude, fine.longitude);
|
||||
assert.equal(kept.operator, 'B', 'attributes still refresh');
|
||||
const finer = { ...fine, latitude: 30.300012 };
|
||||
assert.equal(cache.apply(finer, 13), finer);
|
||||
cache.apply({ id: 'alpr:2', latitude: 1, longitude: 1 }, 12);
|
||||
cache.apply({ id: 'alpr:3', latitude: 1, longitude: 1 }, 12);
|
||||
assert.equal(cache.size(), 2, 'bounded');
|
||||
});
|
||||
|
||||
test('the explicit Overpass factory posts the unchanged query to its API transport', async () => {
|
||||
const calls = [];
|
||||
const source = createOverpassAlprSource({
|
||||
fetchImpl: async (url, options) => {
|
||||
calls.push({ url, options });
|
||||
return Response.json({
|
||||
elements: [
|
||||
{
|
||||
type: 'node',
|
||||
id: 42,
|
||||
lat: 30.05,
|
||||
lon: -97.95,
|
||||
tags: { 'surveillance:type': 'ALPR', operator: 'Test' },
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
const result = await source.fetch(box);
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].url, '/api/overpass');
|
||||
assert.equal(calls[0].options.method, 'POST');
|
||||
assert.equal(
|
||||
new URLSearchParams(calls[0].options.body).get('data'),
|
||||
buildOverpassQuery(box.south, box.west, box.north, box.east),
|
||||
);
|
||||
});
|
||||
|
||||
test('the tile adapter never passes public URLs through an injected API transport', async (t) => {
|
||||
const urls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
urls.push(url);
|
||||
return url.endsWith('.json')
|
||||
? Response.json(metadata('us'))
|
||||
: new Response(fixture);
|
||||
});
|
||||
const source = createAlprTileSource({
|
||||
fetchImpl: () => assert.fail('API transport must not receive tile URLs'),
|
||||
});
|
||||
const result = await source.fetch(austin);
|
||||
assert.ok(result.records.length);
|
||||
assert.ok(urls.length > 1);
|
||||
assert.ok(urls.every((url) => url.startsWith('https://tiles.')));
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { PbfReader } from 'pbf';
|
||||
import { VectorTile } from '@mapbox/vector-tile';
|
||||
import { normalizeAlprNode } from './records.js';
|
||||
|
||||
/** Map extract attributes without treating an OSM edit date as a field verification. */
|
||||
export function normalizeAlprTileFeature(feature) {
|
||||
const p = feature?.properties || {};
|
||||
if (feature?.geometry?.type !== 'Point' || p.osmType !== 'node') return null;
|
||||
const [lon, lat] = feature.geometry.coordinates;
|
||||
const record = normalizeAlprNode({
|
||||
type: 'node',
|
||||
id: Number(p.osmId),
|
||||
lat,
|
||||
lon,
|
||||
tags: {
|
||||
'surveillance:type': 'ALPR',
|
||||
operator: p.operator,
|
||||
manufacturer: p.brand,
|
||||
'camera:type': p.cameraType,
|
||||
'camera:direction': p.direction,
|
||||
'surveillance:zone': p.surveillanceZone,
|
||||
ref: p.ref,
|
||||
check_date: p.check_date,
|
||||
},
|
||||
});
|
||||
return record ? { ...record, osmTimestamp: p.osmTimestamp || null } : null;
|
||||
}
|
||||
|
||||
/** Decode detail-level camera points; geometry-only heatmap tiles are not records. */
|
||||
export function decodeAlprTile(bytes, z, x, y) {
|
||||
const layer = new VectorTile(new PbfReader(bytes)).layers.cameras;
|
||||
if (!layer) return [];
|
||||
if (layer.length > 40_000)
|
||||
throw new Error('Camera tile feature limit exceeded');
|
||||
const records = [];
|
||||
for (let i = 0; i < layer.length; i++) {
|
||||
const record = normalizeAlprTileFeature(
|
||||
layer.feature(i).toGeoJSON(x, y, z),
|
||||
);
|
||||
if (record) records.push(record);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
@@ -1,6 +1,25 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { destinationPointDeg } from './model.js';
|
||||
import { DIRECTION_CONE_M, DIRECTION_CONE_HALF_ANGLE_DEG } from './policy.js';
|
||||
import {
|
||||
DIRECTION_CONE_M,
|
||||
DIRECTION_CONE_HALF_ANGLE_DEG,
|
||||
MARKER_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
|
||||
/**
|
||||
* Badge scale at a camera distance, matching Cesium's NearFarScalar for the
|
||||
* native badges (linear between near and far, clamped outside).
|
||||
* @param {number} distanceM Camera-to-marker distance.
|
||||
* @returns {number} Scale factor.
|
||||
*/
|
||||
export function markerScale(distanceM) {
|
||||
const [near, nearScale, far, farScale] = MARKER_SCALE_BY_DISTANCE;
|
||||
if (!Number.isFinite(distanceM) || distanceM <= near) return nearScale;
|
||||
if (distanceM >= far) return farScale;
|
||||
return (
|
||||
nearScale + ((distanceM - near) / (far - near)) * (farScale - nearScale)
|
||||
);
|
||||
}
|
||||
|
||||
// Camera artwork and visual treatment contributed by Manjunath (@manjunath22466).
|
||||
// Module-relative assets also resolve when the layer is consumed by another app.
|
||||
@@ -48,8 +67,16 @@ export function alprLabelDetails(record, source) {
|
||||
return details;
|
||||
}
|
||||
|
||||
/** Illustrative bearing wedge, not measured field of view or operating range. */
|
||||
export function directionWedgePositions(record, heightM = 0) {
|
||||
/**
|
||||
* Illustrative bearing wedge, not measured field of view or operating range.
|
||||
* @param {object} record Camera record.
|
||||
* @param {number} [heightM] Apex height.
|
||||
* @param {function(number, number): (number|null)} [heightAt] Optional height
|
||||
* for the two far corners (degrees lat, lon), so the wedge follows a slope
|
||||
* instead of floating level from the apex; falls back to the apex height.
|
||||
* @returns {Array<Cesium.Cartesian3>|null} Apex, left and right corners.
|
||||
*/
|
||||
export function directionWedgePositions(record, heightM = 0, heightAt = null) {
|
||||
if (!Number.isFinite(record.directionDeg)) return null;
|
||||
const left = destinationPointDeg(
|
||||
record.latitude,
|
||||
@@ -63,10 +90,18 @@ export function directionWedgePositions(record, heightM = 0) {
|
||||
record.directionDeg + DIRECTION_CONE_HALF_ANGLE_DEG,
|
||||
DIRECTION_CONE_M,
|
||||
);
|
||||
const corner = (point) => {
|
||||
const height = heightAt?.(point.latitude, point.longitude);
|
||||
return Number.isFinite(height) ? height : heightM;
|
||||
};
|
||||
return [
|
||||
Cesium.Cartesian3.fromDegrees(record.longitude, record.latitude, heightM),
|
||||
Cesium.Cartesian3.fromDegrees(left.longitude, left.latitude, heightM),
|
||||
Cesium.Cartesian3.fromDegrees(right.longitude, right.latitude, heightM),
|
||||
Cesium.Cartesian3.fromDegrees(left.longitude, left.latitude, corner(left)),
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
right.longitude,
|
||||
right.latitude,
|
||||
corner(right),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user