fix(cctv): stand cameras and count markers on the drawn terrain

When the terrain height batch loses a chunk to the rate limit, the cameras
in it keep a sea-level fallback height. In the mountains that put them far
under the surface, so the view pass judged them by a point that was not
where they are drawn: a tilted view dropped the count marker, a click on
the marker framed empty ground, and icons drifted on tilt and pan.

- A camera with no real ground height takes the height of the terrain the
  globe draws once it is near the screen (up to 300 reads a pass, through
  the height service), and a later answer from the batch replaces it.
- A count marker is anchored to the drawn terrain under its centre, and a
  click frames that ground.
- Cameras on one mount draw side by side, 30 px apart, each with its own
  callout, instead of as one icon with several callouts.

The photoreal map stack is not covered: terrain is not the surface there.
This commit is contained in:
German Khokhlov committed 2026-11-19 00:03:34 +04:00
1 parent 65942008bf
commit 2e18673df8
9 files changed
+453 -69

No files matched your search

+2 -1
View File
@@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const camera = records[i].camera;
objects.push({
position: records[i].position,
// A camera sharing its mount is drawn beside its mates.
position: records[i].spreadPosition ?? records[i].position,
sourceId: camera.id,
// Short semantic code where the id is opaque (see cameraDisplayCode).
id: `CAM-${camera.code || camera.id}`,
+22 -3
View File
@@ -1,5 +1,6 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
@@ -201,16 +202,32 @@ export function createCountMarkers(
};
}
/** Reuse marker slots in ground-key order, and invalidate only changed frames. */
function update(cells, project) {
/**
* Reuse marker slots in ground-key order, and invalidate only changed frames.
* `groundHeight(lon, lat)` answers the drawn terrain height in metres, or
* null where it is not loaded; with it a count stands on the ground it
* marks whatever heights its cameras hold.
*/
function update(cells, project, groundHeight = null) {
// Lone cameras take part so that one beside a count joins it.
let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key));
const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON);
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
for (const cell of list) {
if (cell.count === 1 || cell.groundM !== undefined) continue;
const { lon, lat } = cellLonLat(cell);
const height = groundHeight(lon, lat);
cell.groundM = Number.isFinite(height) ? Math.round(height) : null;
}
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES && visible.length > 1;
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
@@ -225,6 +242,7 @@ export function createCountMarkers(
for (const cell of cells)
if (cell.count === 1) cell.absorbed = !apart.has(cell);
visible = visible.filter((cell) => cell.count > 1);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
const cell = visible[i];
@@ -236,7 +254,8 @@ export function createCountMarkers(
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM
) {
marker.pos = cellCenter(cell);
changed = true;
+71 -44
View File
@@ -214,56 +214,82 @@ export function createGround({ state: layerState, services, parts, source }) {
let applied = 0;
let moved = 0;
for (let i = 0; i < records.length && i < priors.length; i++) {
const record = records[i];
const prior = priors[i];
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) continue;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
applied += 1;
} else if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
applied += 1;
}
const outcome = applyGroundPrior(records[i], priors[i]);
if (outcome === 'moved') moved += 1;
else if (outcome === 'applied') applied += 1;
}
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
* Gives one live record a ground prior: `'moved'` when only its icon went
* onto the prior in place, `'applied'` when its geometry was recomputed,
* null when nothing changed. Pure recomputes, no scene queries.
*/
function applyGroundPrior(record, prior) {
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
return 'moved';
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
return 'applied';
}
if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
return 'applied';
}
return null;
}
/**
* A camera the height batch never answered for (a failed or rate-limited
* chunk leaves it on the catalog's fabricated ground) takes the terrain
* the globe draws under it as its prior, so that it stands on the surface
* the user sees. `rangeM` is how far the eye was when the terrain was
* read: a closer look reads finer terrain and replaces it, and so does a
* batch answer that arrives later.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, rangeM) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
rangeM,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +425,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+8
View File
@@ -71,6 +71,14 @@ export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Cameras on one mount (the same point to about a metre) draw side by side,
// this many pixels apart, once they show as icons.
export const VIEW_SITE_SPREAD_PX = 30;
// Cameras without a ground height that one view pass may read from the drawn
// terrain. The rest wait for the next pass.
export const VIEW_GROUND_READS = 300;
// Diameter at one camera before applying the size limits, in CSS pixels.
export const COUNT_BASE_PX = 38;
+126 -13
View File
@@ -17,6 +17,8 @@ import {
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
VIEW_SITE_SPREAD_PX,
VIEW_GROUND_READS,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
@@ -27,6 +29,7 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
@@ -383,6 +386,16 @@ export function createRendering({
const picker = [];
const cells = new Map();
const visibleCells = [];
// The terrain the globe draws, where it is the surface (not on the
// photoreal stack) and loaded: null elsewhere.
const heights = heightsOf(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) &&
findGlobe(layerState._viewer)?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -397,20 +410,49 @@ export function createRendering({
(vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared
)
continue;
const screen = project(position);
let screen = project(position);
let range = distance(position, viewer);
// A camera the height batch never answered for (no prior, or the
// geoid fallback a failed chunk leaves) sits near sea level, which can
// be kilometres under the terrain: it would project to the wrong
// place, drift as the view moves and measure too far for its cell.
// Anywhere near the screen, it takes the drawn terrain.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
if (
groundReads > 0 &&
(!prior ||
prior.source === 'geoid-fallback' ||
(drawn && prior.rangeM > 2 * range)) &&
screen &&
screen.x >= -width &&
screen.x <= 2 * width &&
screen.y >= -height &&
screen.y <= 2 * height
) {
groundReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
if (drawn && Math.abs(ground - prior.ellipsoid) < 1) {
prior.rangeM = range;
} else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets: after this pass.
regrounded.push([record, ground, range]);
} else if (
parts.ground.adoptDrawnGround(record, ground, range) === 'moved'
) {
screen = project(position);
range = distance(position, viewer);
}
}
}
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
const cellM =
VIEW_CELL_PX *
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
@@ -435,8 +477,10 @@ export function createRendering({
cell.rank = rank;
}
}
// Marks each lone camera that a count marker beside it has taken in.
layerState._counts?.update(visibleCells, project);
// A count stands on the drawn terrain too: its cell may be too far for
// its cameras to have been read. Marks each lone camera that a count
// marker beside it has taken in.
layerState._counts?.update(visibleCells, project, groundHeight);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
@@ -446,6 +490,7 @@ export function createRendering({
shown.push(record);
}
}
spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
@@ -462,12 +507,21 @@ export function createRendering({
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const fields = { show: record.viewPass === pass };
if (record.spreadPass === pass) {
const drawn = layerState._icons?.item(record.camera.id)?.pos;
if (!drawn || !samePoint(drawn, record.spreadPosition))
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
const item = patchedCameraIcon(record.camera.id, fields);
if (item) writes.push(item);
}
writeCameraIcons(writes);
if (regrounded.length) queueMicrotask(() => reground(regrounded));
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
@@ -483,6 +537,65 @@ export function createRendering({
return changed || pickerChanged;
}
/**
* Cameras that have geometry take the drawn terrain after the pass that
* read it, then the view is passed again from their new positions.
*/
function reground(entries) {
let changed = false;
for (const [record, ground, range] of entries)
changed =
parts.ground.adoptDrawnGround(record, ground, range) !== null ||
changed;
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
}
/**
* Cameras on one mount would draw as one icon with several callouts. Among
* the cameras shown, those that share a point to about a metre get draw
* positions side by side along the screen's horizontal, in id order,
* `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The
* record's own position is untouched: geometry and cards keep the mount.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const mounts = new Map();
for (const record of shown) {
const { lat, lon } = record.camera;
const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`;
const mates = mounts.get(key);
if (mates) mates.push(record);
else mounts.set(key, [record]);
}
for (const mates of mounts.values()) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
const record = mates[i];
const p = record.position;
// A pixel's width on the ground grows with depth along the view.
const depth =
(p.x - eye.x) * direction.x +
(p.y - eye.y) * direction.y +
(p.z - eye.z) * direction.z;
const metres =
(i - (mates.length - 1) / 2) *
VIEW_SITE_SPREAD_PX *
metresPerPixelPerMetre *
depth;
record.spreadPosition = {
x: p.x + right.x * metres,
y: p.y + right.y * metres,
z: p.z + right.z * metres,
};
record.spreadPass = pass;
}
}
}
/**
* Canvas coordinates for world positions, from the eye's pose by the
* renderer's perspective projection (geo/frustum.js): one pose read per