fix(cctv): settle the review of the count markers

Bugs:
- Cameras on one mount stay side by side after their geometry is built,
  so a click or a settled view no longer folds them back into one icon.
- A count click yields to a card drawn over the marker and to another
  layer's object under it, waits while the cockpit or tracking holds the
  view, and flies at most halfway, so a long chain of cameras still splits.
- The active camera's icon is never covered by a count, transparent
  corners of the marker no longer catch clicks, and a count hidden under
  the HUD keeps its lone cameras.
- A lone camera joins only its nearest count and never bridges two; cameras
  close enough to draw as icons take part too, at their drawn icon size.
- Groups across the antimeridian keep their longitude; the flight frames
  the highest mount; markers on ground below the ellipsoid stay visible;
  counts fade outside the Scope circle.
- Mounts less than a metre apart count as one mount.
- A drawn-terrain height survives a late fallback answer, is read for an
  unresolved camera and for one projected off the window, is re-read when
  the terrain under it finishes loading or the terrain source changes, and
  the read budget no longer goes to the same misses each pass.

Cleanup: the glyph draws from one green SVG sprite instead of recolouring
pixels, marker-only constants move next to their use, layout tests check
behaviour rather than formulas, and docs and comments match the code.
docs/I18N.md names the one fixed notation of count badges as an exception.
This commit is contained in:
German Khokhlov committed 2026-11-19 03:07:04 +04:00
1 parent 2e18673df8
commit 81fe7f88cc
26 files changed
+1608 -638

No files matched your search

+124 -160
View File
@@ -7,113 +7,65 @@ import {
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import {
CAMERA_GREEN,
IDLE_CAMERA_ICON,
COUNT_BASE_PX,
COUNT_PX_PER_DECADE,
COUNT_MIN_HEIGHT_PX,
COUNT_MAX_HEIGHT_PX,
COUNT_TEXT_PADDING_PX,
COUNT_GLYPH_MIN_PX,
COUNT_GLYPH_MAX_PX,
COUNT_GLYPH_TOP_MIN_PX,
COUNT_GLYPH_TOP_MAX_PX,
COUNT_GLYPH_PADDING_PX,
COUNT_LABEL_DROP,
COUNT_CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
COUNT_SINGLE_ICON_PX,
COUNT_MERGE_PASSES,
} from './policy.js';
import { liftedForHorizon } from '../../geo/horizon.js';
// Diameter at one camera before applying the size limits, in CSS pixels.
const COUNT_BASE_PX = 38;
// Extra diameter for each tenfold increase in camera count.
const COUNT_PX_PER_DECADE = 5;
// Minimum height of a count marker in CSS pixels.
const COUNT_MIN_HEIGHT_PX = 40;
// Maximum height of a count marker in CSS pixels.
const COUNT_MAX_HEIGHT_PX = 58;
// Clear fill between the count and the inside of the ring, in CSS pixels.
const COUNT_TEXT_PADDING_PX = 6;
// Height of the camera glyph in the smallest and the largest marker.
const COUNT_GLYPH_MIN_PX = 7.5;
const COUNT_GLYPH_MAX_PX = 10;
// Clear fill above the glyph in the smallest and the largest marker.
const COUNT_GLYPH_TOP_MIN_PX = 3;
const COUNT_GLYPH_TOP_MAX_PX = 4;
// Clear fill between the glyph's top corners and the inside of the ring.
const COUNT_GLYPH_PADDING_PX = 2;
// The middle of the digits sits this share of the inner radius below the
// marker's centre, which leaves the glyph clear of the count.
const COUNT_LABEL_DROP = 0.2;
// Merge passes per view. A merged centre and wider label can reach a further
// marker. The cap bounds work on motion ticks.
const COUNT_MERGE_PASSES = 3;
const FONT = WORLD_OVERLAY_STYLE.fontTitle;
// Reserve the camera's landscape slot even while the map sprite is loading.
const GLYPH_ASPECT = 1.5;
const RING_PX = 2;
const RIM_PX = 1;
const STROKE_INSET = RIM_PX + RING_PX / 2;
const SINGLE_ICON = Object.freeze({
width: COUNT_SINGLE_ICON_PX,
height: COUNT_SINGLE_ICON_PX,
});
/** Apply the billboard's RGB tint to the sprite and find its painted bounds. */
function rasterizeGlyph(canvas, image, size, dpr, color) {
if (!canvas) return null;
// The artwork occupies just over half the height of the square SVG viewport.
const side = 2 * Math.ceil(size * dpr);
canvas.width = canvas.height = side;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
ctx.drawImage(image, 0, 0, side, side);
const pixels = ctx.getImageData(0, 0, side, side);
const { data } = pixels;
const rgb = Number.parseInt(color.slice(1), 16);
const red = (rgb >> 16) / 255;
const green = ((rgb >> 8) & 255) / 255;
const blue = (rgb & 255) / 255;
let left = side,
top = side,
right = -1,
bottom = -1;
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
const i = (y * side + x) * 4;
if (!data[i + 3]) continue;
data[i] *= red;
data[i + 1] *= green;
data[i + 2] *= blue;
left = Math.min(left, x);
right = Math.max(right, x);
top = Math.min(top, y);
bottom = y;
}
}
if (right < 0) return null;
ctx.putImageData(pixels, 0, 0);
const width = right - left + 1;
const height = bottom - top + 1;
const scale = Math.min(size / height, (size * GLYPH_ASPECT) / width);
return {
canvas,
left,
top,
width,
height,
drawWidth: width * scale,
drawHeight: height * scale,
};
}
/** Load the map artwork once, then share each tinted device-density raster. */
export function createCameraGlyphCache(createCanvas, source, onLoad) {
const glyphs = new Map();
let image;
let ready = false;
return (size, dpr, color) => {
if (!image && typeof Image !== 'undefined') {
image = new Image();
image.onload = () => {
ready = true;
onLoad?.();
};
image.src = source;
}
if (!ready) return null;
const key = `${size}:${dpr}:${color}`;
if (!glyphs.has(key)) {
glyphs.set(key, rasterizeGlyph(createCanvas(), image, size, dpr, color));
}
return glyphs.get(key);
};
}
// Painted bounds of the camera art, scaled from its viewBox to source pixels.
const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36);
const GLYPH_SOURCE_ASPECT = 28.1 / 19.5;
/** Merged camera groups and their last painted hit rectangles in CSS pixels. */
export function createCountMarkers(
registerPaintLane,
id,
refreshView,
createCanvas = () => globalThis.document?.createElement('canvas'),
keyholeAlpha,
) {
let dpr = Math.max(1, Number(globalThis.window?.devicePixelRatio) || 1);
let hardUi = null;
let sprite = null;
let spriteReady = false;
const markers = [];
const hits = [];
const textMetrics = new Map();
@@ -125,15 +77,15 @@ export function createCountMarkers(
active: false,
target: 'shared',
});
const glyphFor = createCameraGlyphCache(
createCanvas,
IDLE_CAMERA_ICON,
() => {
if (!markers.length) return;
refreshGlyphs();
lane?.requestPaint();
},
);
function loadSprite() {
if (sprite || typeof Image === 'undefined') return;
sprite = new Image();
sprite.onload = () => {
spriteReady = true;
if (markers.length) lane?.requestPaint();
};
sprite.src = COUNT_CAMERA_ICON;
}
fonts?.addEventListener?.('loadingdone', fontsLoaded);
/** Font changes can widen a pill enough to merge it with its neighbor. */
@@ -149,14 +101,12 @@ export function createCountMarkers(
const text = formatCameraCount(count);
let metrics = textMetrics.get(text);
if (!metrics) {
measureCtx ??= createCanvas()?.getContext('2d');
if (measureCtx) {
measureCtx.font = FONT;
measureCtx.textBaseline = 'middle';
metrics = measureCtx.measureText(text);
} else {
metrics = { width: text.length * 8 };
}
measureCtx ??= globalThis.document
.createElement('canvas')
.getContext('2d');
measureCtx.font = FONT;
measureCtx.textBaseline = 'middle';
metrics = measureCtx.measureText(text);
textMetrics.set(text, metrics);
}
const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count);
@@ -175,9 +125,8 @@ export function createCountMarkers(
COUNT_GLYPH_TOP_MIN_PX +
(COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown -
radius;
// Width-only metrics use half the 12 px type size on each side of the baseline.
const ascent = metrics.actualBoundingBoxAscent ?? 6;
const descent = metrics.actualBoundingBoxDescent ?? 6;
const ascent = metrics.actualBoundingBoxAscent;
const descent = metrics.actualBoundingBoxDescent;
const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2;
// Each row must clear the ring at the edge where the circle is narrowest.
const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2));
@@ -204,14 +153,18 @@ export function createCountMarkers(
/**
* 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.
* `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite
* value where it has not loaded. A count stands on that ground when available
* and otherwise uses its cameras' mean mount height.
*/
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);
const footprint = (count, cell) => {
if (count > 1) return sizeFor(count);
const px = cell.iconPx ?? CAMERA_ICON_PX;
return { width: px, height: px };
};
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
@@ -224,7 +177,9 @@ export function createCountMarkers(
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES && visible.length > 1;
pass < COUNT_MERGE_PASSES &&
visible.length > 1 &&
visible.some((cell) => cell.count > 1);
pass++
) {
ground(visible);
@@ -246,7 +201,7 @@ export function createCountMarkers(
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
const cell = visible[i];
const marker = markers[i] ?? (markers[i] = { focus: 1 });
const marker = (markers[i] ??= { focus: 1 });
const last = marker.cell;
const size = sizeFor(cell.count);
if (
@@ -258,16 +213,23 @@ export function createCountMarkers(
last.groundM !== cell.groundM
) {
marker.pos = cellCenter(cell);
marker.cullPos = liftedForHorizon(marker.pos);
marker.hudHidden = undefined;
changed = true;
} else if (
last.west !== cell.west ||
last.east !== cell.east ||
last.south !== cell.south ||
last.north !== cell.north ||
last.low !== cell.low ||
last.high !== cell.high
) {
changed = true;
}
// A count hidden by the HUD leaves its lone cameras visible as icons.
if (hardUi && cell.lone?.length) {
const at = project(marker.pos);
if (
at &&
hardUi({
x: at.x - size.width / 2,
y: at.y - size.height / 2,
w: size.width,
h: size.height,
})
)
for (const lone of cell.lone) lone.absorbed = false;
}
changed ||=
size.text !== marker.text ||
@@ -276,24 +238,19 @@ export function createCountMarkers(
size.labelY !== marker.labelY;
marker.cell = cell;
Object.assign(marker, size);
marker.glyph = glyphFor(size.glyphHeight, dpr, CAMERA_GREEN);
// Paint never grows the hit buffer, even when a pan reveals every group.
hits[i] ??= {};
}
markers.length = visible.length;
if (markers.length) loadSprite();
// Keep the last frame pickable until the host clears its pixels.
lane?.setActive(markers.length > 0 || hitCount > 0);
if (changed) lane?.requestPaint();
}
/** Attach the raster for the current overlay density to each visible group. */
function refreshGlyphs() {
for (const marker of markers)
marker.glyph = glyphFor(marker.glyphHeight, dpr, CAMERA_GREEN);
}
/** Draw at device density using the host's CSS-pixel transform and projection. */
function paint(frame) {
hardUi = frame.overlapsHardUi ?? hardUi;
if (!markers.length) {
// Deactivating invalidates the host, so finish the shared frame first.
if (hitCount) queueMicrotask(deactivateIfEmpty);
@@ -302,10 +259,7 @@ export function createCountMarkers(
}
hitCount = 0;
const { ctx, occluder, viewProjectionMatrix: m } = frame;
if (dpr !== frame.dpr) {
dpr = frame.dpr;
refreshGlyphs();
}
let refresh = false;
ctx.save();
try {
ctx.font = FONT;
@@ -316,7 +270,7 @@ export function createCountMarkers(
const { height } = marker;
const { x: px, y: py, z: pz } = marker.pos;
const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos)))
if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos)))
continue;
const x =
(0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) *
@@ -333,11 +287,22 @@ export function createCountMarkers(
rect.x >= frame.width ||
rect.y >= frame.height ||
rect.x + rect.w <= 0 ||
rect.y + rect.h <= 0 ||
frame.overlapsHardUi(rect)
rect.y + rect.h <= 0
)
continue;
ctx.globalAlpha = marker.focus;
const hidden = Boolean(hardUi?.(rect));
if (marker.hudHidden !== hidden) {
marker.hudHidden = hidden;
// A first frame or moving HUD can change which lone icons must show.
refresh ||= marker.cell.lone?.some(
(cell) => cell.absorbed === hidden,
);
}
if (hidden) continue;
const fade =
frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1;
if (!(fade > 0)) continue;
ctx.globalAlpha = marker.focus * fade;
ctx.beginPath();
ctx.roundRect(
rect.x + STROKE_INSET,
@@ -355,18 +320,15 @@ export function createCountMarkers(
ctx.lineWidth = RING_PX;
ctx.stroke();
ctx.fillStyle = CAMERA_GREEN;
const glyph = marker.glyph;
if (glyph) {
if (spriteReady) {
const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT;
ctx.drawImage(
glyph.canvas,
glyph.left,
glyph.top,
glyph.width,
glyph.height,
x - glyph.drawWidth / 2,
y + marker.glyphBottom - glyph.drawHeight,
glyph.drawWidth,
glyph.drawHeight,
sprite,
...GLYPH_SOURCE,
x - width / 2,
y + marker.glyphBottom - marker.glyphHeight,
width,
marker.glyphHeight,
);
}
ctx.fillText(marker.text, x, y + marker.labelY);
@@ -376,6 +338,7 @@ export function createCountMarkers(
} finally {
ctx.restore();
}
if (refresh) queueMicrotask(refreshView);
}
/** Resolve the topmost group actually painted at this screen position. */
@@ -383,13 +346,14 @@ export function createCountMarkers(
if (!point) return null;
for (let i = hitCount - 1; i >= 0; i--) {
const rect = hits[i];
if (
point.x >= rect.x &&
point.x <= rect.x + rect.w &&
point.y >= rect.y &&
point.y <= rect.y + rect.h
)
return rect.cell;
const radius = rect.h / 2;
// Distance from the pill's horizontal centre segment.
const dx = Math.max(
0,
Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2,
);
const dy = point.y - (rect.y + radius);
if (dx * dx + dy * dy <= radius * radius) return rect.cell;
}
return null;
}
@@ -407,7 +371,7 @@ export function createCountMarkers(
/** Unhook this viewer's painter and its font listener. */
function dispose() {
markers.length = hits.length = hitCount = 0;
hide();
fonts?.removeEventListener?.('loadingdone', fontsLoaded);
lane?.unregister();
}
+136
View File
@@ -0,0 +1,136 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height });
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => {
const m = counts();
m.update([cellAt('a', 400, 2, -20)], project, () => -30);
const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid
const horizon = horizonFrom(eye);
assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true);
assert.equal(paint({ occluder: horizon }).length, 1);
});
test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => {
const hud = { overlapsHardUi: (rect) => rect.x < 200 };
for (const paintedFirst of [true, false]) {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const m = counts(() => m.update(cells, project));
if (paintedFirst) paint(hud);
m.update(cells, project);
const labels = paint(hud);
await Promise.resolve();
assert.ok(!cells[1].absorbed || labels.length > 0);
// Moving the HUD at rest also changes whether the lone icon is needed.
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
paint(hud);
await Promise.resolve();
assert.equal(cells[1].absorbed, false);
m.dispose();
}
});
test('counts fade with the Scope keyhole like the callouts', () => {
const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha);
m.update([cellAt('a', 400, 2)], project);
assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25);
assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []);
assert.equal(m.pickedCell({ x: 400, y: 300 }), null);
assert.equal(paint()[0].alpha, 1);
});
+15 -13
View File
@@ -1,4 +1,4 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
@@ -233,6 +233,12 @@ export function createGround({ state: layerState, services, parts, source }) {
// 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;
// The drawn terrain beats a fallback. Only a real batch answer replaces it.
if (
prior.source === 'geoid-fallback' &&
record.groundPrior?.source === 'drawn-terrain'
)
return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
@@ -247,14 +253,12 @@ export function createGround({ state: layerState, services, parts, source }) {
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
fromDegreesInto(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
record.position,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
return 'moved';
}
@@ -274,19 +278,17 @@ export function createGround({ state: layerState, services, parts, source }) {
}
/**
* 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.
* Applies drawn terrain as a drawn-terrain prior. The read records the eye
* distance (rangeM), globe surface version (surface) and whether terrain
* loading had finished (settled). Reading from under half that range or
* receiving a later Re:Earth answer replaces the height.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, rangeM) {
function adoptDrawnGround(record, heightM, read) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
rangeM,
...read,
});
}
+64
View File
@@ -0,0 +1,64 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createGround } from './ground.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
function setup(record) {
const calls = { culling: 0, geometry: [], notify: 0 };
const state = {
_viewer: null,
_recordById: new Map([[record.camera.id, record]]),
};
const parts = {
rendering: {
refreshHorizonCulling: () => (calls.culling++, true),
moveCameraIcon() {},
},
geometryQueue: { enqueueViewGeometry() {} },
presentation: { notifyListeners: () => calls.notify++ },
geometry: {
// Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell.
updateRecordGeometry(r) {
calls.geometry.push(
ground.groundPriorAltFor(r) + r.camera.mountHeightM,
);
},
},
};
const ground = createGround({
state,
services: {
ground: { resolveGroundFloorCells: async () => {} },
terrain: { resolveEllipsoidalGround: async () => [] },
},
parts,
});
return { ground, calls };
}
test('a late geoid fallback leaves a drawn-terrain height in place', () => {
const camera = {
id: 'a',
lat: 42,
lon: -118,
mountHeightM: 8,
absoluteHeightM: 1880,
};
const record = {
camera,
position: fromDegrees(camera.lon, camera.lat, 1880),
frustumGeometry: {},
frustumPositions: {},
groundSamples: {},
groundResolved: {},
groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 },
};
const { ground, calls } = setup(record);
ground.applyLateGroundPriors(
[record],
[{ ellipsoid: 0, source: 'geoid-fallback' }],
);
assert.equal(record.groundPrior.source, 'drawn-terrain');
assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback');
});
+30 -4
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
@@ -103,6 +103,30 @@ export function createLifecycle({
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const globe = findGlobe(layerState._viewer);
if (layerState._surfaceListenerGlobe !== globe) {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = globe;
}
if (!layerState._surfaceListener && globe?.on) {
// Refresh drawn heights when terrain finishes loading or the surface changes.
let version = globe.surfaceVersion?.();
let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0;
layerState._surfaceListener = globe.on('progress', (progress) => {
const next = globe.surfaceVersion?.();
const loaded = progress?.terrainPending === 0 && terrainPending !== 0;
const swapped = next !== version;
version = next;
terrainPending = progress?.terrainPending ?? terrainPending;
if (
(loaded || swapped) &&
layerState._enabled &&
!layerState._cameraMoving
)
settleView();
});
}
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
@@ -140,6 +164,9 @@ export function createLifecycle({
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
@@ -287,9 +314,8 @@ export function createLifecycle({
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
// groundPrior — { ellipsoid, source } from the Re:Earth batch
// (null until a late batch lands). The prior applies in EVERY
// regime and is the terrain-globe resolution outright.
// groundPrior — { ellipsoid, source } from the Re:Earth batch, or
// drawn-terrain with its read conditions for an unanswered camera.
// groundResolved — PER-REGIME one-shot latch (regime key →
// boolean): true once this record's resolution completed for that
// regime; such records are excluded from the completion pass so
+34
View File
@@ -72,3 +72,37 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
test('terrain loading and surface changes rerun the view pass', () => {
const viewer = {};
let version = 1,
progress,
removed = false;
bindRenderer(viewer, {
camera: fakeCameraPort().port,
globe: {
surfaceVersion: () => version,
on(event, cb) {
assert.equal(event, 'progress');
progress = cb;
return () => {
removed = true;
};
},
},
});
const { lifecycle, passes } = lifecycleFor({
_viewer: viewer,
_enabled: true,
});
lifecycle.attachViewListeners();
progress({ terrainPending: 2 });
assert.equal(passes.length, 0);
progress({ terrainPending: 0 });
assert.equal(passes.length, 1);
version++;
progress({ terrainPending: 0 });
assert.equal(passes.length, 2);
lifecycle.detachViewListeners();
assert.ok(removed);
});
+25 -8
View File
@@ -1,3 +1,5 @@
import { distance } from '../../geo/vector.js';
import { rangeForBoundingSphere } from '../../data/cameraFraming.js';
import { isFollowing } from '../../data/followed.js';
import { cellBounds } from '../../data/cctvCellCounts.js';
import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js';
@@ -64,6 +66,16 @@ export function createNavigation({
return true;
}
/** What holds the view instead of a CCTV flight, or null when it is free. */
function viewHeldBy(viewer) {
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
)
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null;
}
/**
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
@@ -75,14 +87,12 @@ export function createNavigation({
function focusCctvRecord(viewer, record, duration = 2.2) {
if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA;
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
) {
const held = viewHeldBy(viewer);
if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) {
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (isFollowing(viewer)) {
if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -108,17 +118,24 @@ export function createNavigation({
/** Frame a group's padded bounds from above, including coincident mounts. */
function zoomToCell(cell) {
const viewer = layerState._viewer;
if (!viewer || viewHeldBy(viewer)) return;
const camera = cameraOf(viewer);
const pose = camera.pose();
const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2);
const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height || 1;
const halfFov = Math.atan(tanHalfY * Math.min(1, pose.aspectRatio || 1));
const bounds = cellBounds(cell);
// A tight group lands comfortably inside the individual-icon level.
// Half the range where cells stop grouping, so even coincident mounts split.
const closeRange =
(VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY);
const range = Math.max(closeRange, bounds.radius / Math.sin(halfFov));
// Approach long groups in halves so every click gets closer.
const halfway = pose.position
? distance(pose.position, bounds.center) / 2
: Infinity;
const range = Math.min(
halfway,
Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)),
);
camera.flyToBounds(bounds, {
offset: { heading: 0, pitch: -Math.PI / 2, range },
durationS: 1.2,
+49 -57
View File
@@ -60,65 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300;
export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10;
// View thinning: camera icons show only on or near the screen, and each
// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX
// at its distance from the viewer (in power-of-two metre steps, so a pan
// keeps the same winners until a camera's distance crosses a step). Cells
// smaller than VIEW_MIN_CELL_M do not thin:
// close up every camera shows, co-located ones included.
// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX
// at their distance. Power-of-two metre steps keep cells stable during a pan.
// A cell with several cameras draws one count. Its best-ranked camera represents
// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so
// every camera shows close up.
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,
// Cameras within this horizontal distance in metres share a mount.
export const VIEW_SITE_M = 1.5;
// Cameras on one mount (VIEW_SITE_M) 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.
// Drawn-terrain reads per view pass for unanswered cameras and for re-reads
// of drawn heights. Off-screen cameras can use at most half of the budget.
// Remaining reads 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;
// Extra diameter for each tenfold increase in camera count.
export const COUNT_PX_PER_DECADE = 5;
// Minimum height of a count marker in CSS pixels.
export const COUNT_MIN_HEIGHT_PX = 40;
// Maximum height of a count marker in CSS pixels.
export const COUNT_MAX_HEIGHT_PX = 58;
// Clear fill between the count and the inside of the ring, in CSS pixels.
export const COUNT_TEXT_PADDING_PX = 6;
// Height of the camera glyph in the smallest and the largest marker.
export const COUNT_GLYPH_MIN_PX = 7.5;
export const COUNT_GLYPH_MAX_PX = 10;
// Clear fill above the glyph in the smallest and the largest marker.
export const COUNT_GLYPH_TOP_MIN_PX = 3;
export const COUNT_GLYPH_TOP_MAX_PX = 4;
// Clear fill between the glyph's top corners and the inside of the ring.
export const COUNT_GLYPH_PADDING_PX = 2;
// The middle of the digits sits this share of the inner radius below the
// marker's centre, which leaves the glyph clear of the count.
export const COUNT_LABEL_DROP = 0.2;
/**
* The camera icon's drawn size (px). Its SVG is 48 px: 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
export const CAMERA_ICON_PX = 24;
// Minimum gap between the outer rims of two separate markers.
export const COUNT_MERGE_GAP_PX = 4;
// On-screen size of a lone camera's icon when testing it against a count
// marker: an icon closer than the merge gap joins that count.
export const COUNT_SINGLE_ICON_PX = 24;
// Recheck moved centres and wider labels while bounding work on motion ticks.
export const COUNT_MERGE_PASSES = 3;
// Icons this far past the screen edge (fraction of its size) still show, so
// a pan does not reveal empty ground before the next view pass.
@@ -230,33 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
/**
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
* 2× display draws it at 60 device px, and it stays sharp there.
* 2× display draws it at 60 device px, and it stays sharp there. Active and
* live cameras use cyan art with a billboard tint. Idle cameras use white
* and gray art so the billboard green shows true. The overlay draws the
* green variant directly.
*/
function cameraIcon(neutral) {
const tone = (original, gray) => (neutral ? gray : original);
const stroke = tone('#75e7ff', '#fff');
function cameraIcon(tint = null) {
function tone(original, gray) {
if (!tint) return original;
const shade = parseInt(gray.slice(1, 3), 16) / 255;
return (
'#' +
tint
.slice(1)
.match(/../g)
.map((channel) =>
Math.round(parseInt(channel, 16) * shade)
.toString(16)
.padStart(2, '0'),
)
.join('')
);
}
const stroke = tone('#75e7ff', '#ffffff');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="${tone('#c9f6ff', '#fff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#ddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666')}"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#fff')}" stroke-width="0.8"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#ccc')}" stroke-width="0.8"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
}
export const CAMERA_ICON = cameraIcon(false);
export const IDLE_CAMERA_ICON = cameraIcon(true);
export const CAMERA_ICON = cameraIcon();
export const IDLE_CAMERA_ICON = cameraIcon('#ffffff');
/**
* Seed camera definitions used when no live sources are available.
@@ -496,6 +487,7 @@ export const CAMERA_SEEDS = [
/** Shared accent for idle still cameras and grouped cameras. */
export const CAMERA_GREEN = '#5dff8f';
export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN);
export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN);
+11 -8
View File
@@ -229,9 +229,12 @@ export function createPresentation({
// separately from the currently applied frustum ground. Google-3D may
// legitimately refine the latter to the rendered mesh, so callers must
// not infer the prior by subtracting mount height from live geometry.
groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid)
? record.groundPrior.ellipsoid
: null,
// A height read from drawn terrain is unavailable as a Re:Earth prior.
groundPriorM:
Number.isFinite(record.groundPrior?.ellipsoid) &&
record.groundPrior.source !== 'drawn-terrain'
? record.groundPrior.ellipsoid
: null,
intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null,
extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null,
anchor: camera.anchor ? { ...camera.anchor } : null,
@@ -310,11 +313,11 @@ export function createPresentation({
}
/**
* `{ id, city, name }` for the active camera, then every camera the view
* pass shows: what the camera picker lists. A whole catalog would put tens
* of thousands of options in the DOM and slow every layout. The same array
* is returned until the view or the active camera changes, so a consumer
* can compare it by identity.
* `{ id, city, name }` for the active camera, then each camera shown as an
* icon and the best-ranked camera of each visible group. A whole catalog
* would put tens of thousands of options in the DOM and slow every layout.
* Consumers can compare the array by identity until the picker records or
* active camera change.
* @returns {{id: string, city: string, name: string}[]}
*/
+198 -63
View File
@@ -4,6 +4,9 @@ import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
VIEW_SITE_M,
IDLE_CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
@@ -30,11 +33,16 @@ import {
findQuery,
} from '../../render/rendererOf.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import {
fromDegrees,
fromDegreesInto,
toLonLatH,
WGS84,
} from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import { add, distance, dot, scale, sub } from '../../geo/vector.js';
const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR };
const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR };
@@ -56,12 +64,6 @@ const samePoint = (a, b) =>
/** Degrees to radians. */
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
const CAMERA_ICON_PX = 24;
const CAMERA_SCALE_BY_DISTANCE = Object.freeze({
near: 350,
nearValue: 1.25,
@@ -153,6 +155,7 @@ export function createRendering({
services.overlays?.registerWorldOverlayPaintLane,
`cctv:${iconSets}:counts`,
refreshHorizonCulling,
services.overlays?.keyholeAlpha,
);
return set.id;
}
@@ -170,7 +173,7 @@ export function createRendering({
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
pos: copyPoint(record.spreadPosition ?? record.position),
...cameraIconStyleFor(record),
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
scale: 1,
@@ -211,14 +214,18 @@ export function createRendering({
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
// A camera drawn beside its mount mates keeps its offset from the mount.
if (record.spreadOffset)
record.spreadPosition = add(record.position, record.spreadOffset);
const pos = record.spreadPosition ?? record.position;
const item = icons.item(record.camera.id);
// A camera whose icon waited for a position is drawn now.
if (!item) {
icons.put(cameraIconItem(record));
return;
}
if (samePoint(item.pos, record.position)) return;
icons.put({ ...item, pos: copyPoint(record.position) });
if (samePoint(item.pos, pos)) return;
icons.put({ ...item, pos: copyPoint(pos) });
}
/** Select the sprite and tint together when a camera changes state. */
@@ -235,7 +242,10 @@ export function createRendering({
focusPassIsNeeded,
advanceSpriteFocus,
focusAlphaNeedsWrite,
nearFarScalarValueAtDistance,
} = services.focus;
const iconScaleAt = (range) =>
nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1;
/**
* Focus modulation rides the layer's existing animation loop; no additional
@@ -292,9 +302,14 @@ export function createRendering({
let writes = 0;
let transitioning = false;
let activeCount = 0;
/** A changed focus factor for a camera icon or a painted count. */
/**
* A changed focus factor for an icon or count. CCTV publishes no tracked
* focus target, so every icon is ambient.
*/
function changedFocus(owner, position, shown, width, height, current) {
const focus = advanceSpriteFocus(owner, {
// Keep hidden owners in the active count until their dim alpha clears,
// so the focus pass keeps running while they recover.
screenPosition: shown && position ? screenPositionFor(position) : null,
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
@@ -342,13 +357,16 @@ export function createRendering({
}
/**
* Group horizon-visible mounts by ground cell. Every cell with a member
* near the screen contributes a representative to the picker. Singletons
* and the active camera also enter the icon, geometry and card working set.
* Cull far-side cameras on the CPU because the hidden globe writes no depth.
* Group the rest by ground cell. _viewRecords holds the active camera and
* every nearby icon outside a count for geometry and cards. Cells smaller
* than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the
* best-ranked camera of each visible cell. Both arrays keep their identity
* while their contents are unchanged.
*
* Runs on camera settle, throttled during motion, on resize, enable and
* activation changes — never per frame.
* @returns {boolean} Whether the shown set changed.
* @returns {boolean} Whether the shown set or the picker list changed.
*/
function refreshHorizonCulling() {
@@ -386,15 +404,26 @@ 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.
// Drawn terrain where the globe is the surface. The photoreal stack has
// no reader, and unloaded tiles return a non-finite height.
const heights = heightsOf(layerState._viewer);
const globe = findGlobe(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) &&
findGlobe(layerState._viewer)?.isGlobeVisible?.() === true
findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
const surface = globe?.surfaceVersion?.() ?? 0;
const terrainSettled = globe?.isSettled?.('terrain') ?? true;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
let offscreenReads = groundReads / 2;
let eyeGround;
const column = { x: 0, y: 0, z: 0 };
const inReadWindow = (s) =>
s &&
s.x >= -width &&
s.x <= 2 * width &&
s.y >= -height &&
s.y <= 2 * height;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
@@ -412,39 +441,66 @@ export function createRendering({
continue;
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.
// Missing, unresolved and fallback priors can put a mount kilometres
// below the terrain, shifting its projection and inflating its cell.
// Read nearby mounts again from under half the range, on finer terrain
// after loading, or on a different surface.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
const unanswered =
!Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback';
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
!record.regroundPending &&
(unanswered ||
(drawn &&
(prior.rangeM > 2 * range ||
prior.surface !== surface ||
(!prior.settled && terrainSettled))))
) {
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);
let probe = inReadWindow(screen) ? screen : null;
if (!probe && unanswered) {
// Its height is a guess. Try the ground under the eye instead.
if (eyeGround === undefined) {
const eye = toLonLatH(viewer);
eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null;
groundReads--;
}
if (Number.isFinite(eyeGround)) {
fromDegreesInto(
record.camera.lon,
record.camera.lat,
eyeGround + (record.camera.mountHeightM || 0),
column,
);
const at = project(column);
if (inReadWindow(at)) probe = at;
}
}
const onScreen =
probe &&
probe.x >= 0 &&
probe.x <= width &&
probe.y >= 0 &&
probe.y <= height;
if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) {
groundReads--;
if (!onScreen) offscreenReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
const read = { rangeM: range, surface, settled: terrainSettled };
if (drawn && Math.abs(ground - prior.ellipsoid) < 1)
Object.assign(prior, read);
else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets after this pass.
record.regroundPending = true;
regrounded.push([record, ground, read]);
} else parts.ground.adoptDrawnGround(record, ground, read);
}
}
// The probe reuses the projector's result, and the mount may have moved.
screen = project(position);
range = distance(position, viewer);
}
const nearScreen =
screen &&
@@ -453,13 +509,25 @@ export function createRendering({
screen.y >= minY &&
screen.y <= maxY;
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
if (record.camera.id === activeId) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
shown.push(record);
picker.push(record);
continue;
}
if (!(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
// Too close to group, but a count beside it can still take it in.
const cell = createCameraCell(`near:${record.camera.id}`);
addCellCamera(cell, record.camera);
cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
cell.winner = record;
cell.rank = 0;
record.viewCell = cell;
visibleCells.push(cell);
continue;
}
const key = worldCellKey(record, cellM);
let cell = cells.get(key);
if (!cell) {
@@ -467,6 +535,7 @@ export function createRendering({
cells.set(key, cell);
}
addCellCamera(cell, record.camera);
if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
record.viewCell = cell;
if (!nearScreen) continue;
// The picker ranks only candidates that were in its padded viewport.
@@ -491,6 +560,7 @@ export function createRendering({
}
}
spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass);
clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
@@ -514,6 +584,7 @@ export function createRendering({
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadOffset = null;
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
@@ -543,10 +614,11 @@ export function createRendering({
*/
function reground(entries) {
let changed = false;
for (const [record, ground, range] of entries)
for (const [record, ground, read] of entries) {
record.regroundPending = false;
changed =
parts.ground.adoptDrawnGround(record, ground, range) !== null ||
changed;
parts.ground.adoptDrawnGround(record, ground, read) !== null || changed;
}
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
@@ -554,7 +626,7 @@ export function createRendering({
/**
* 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
* the cameras shown, those within VIEW_SITE_M horizontally 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.
@@ -562,15 +634,31 @@ export function createRendering({
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const mounts = new Map();
const grid = new Map();
const mounts = [];
const axes = eastNorthUp(eye);
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]);
// Sea-level coordinates compare horizontal distance across longitude
// and latitude boundaries, including the antimeridian.
const p = fromDegrees(record.camera.lon, record.camera.lat, 0);
const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M);
const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M);
let mount;
for (let i = col - 1; !mount && i <= col + 1; i++)
for (let j = row - 1; !mount && j <= row + 1; j++)
mount = grid
.get(`${i}:${j}`)
?.find((site) => distance(p, site.p) <= VIEW_SITE_M);
if (!mount) {
mount = { p, mates: [] };
mounts.push(mount);
const key = `${col}:${row}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(mount);
}
mount.mates.push(record);
}
for (const mates of mounts.values()) {
for (const { mates } of mounts) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
@@ -586,16 +674,63 @@ export function createRendering({
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.spreadOffset = scale(right, metres);
record.spreadPosition = add(p, record.spreadOffset);
record.spreadPass = pass;
}
}
}
/** Move the active camera's icon beside any count marker that would cover it. */
function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) {
if (!layerState._activeCameraId) return;
const record = layerState._recordById.get(layerState._activeCameraId);
const markers = layerState._counts?.markers;
if (
record?.viewPass !== pass ||
!markers?.length ||
!pose.right ||
!pose.direction
)
return;
const spread = record.spreadPass === pass;
const p = spread ? record.spreadPosition : record.position;
const screen = project(p);
if (!screen) return;
const { x, y } = screen;
const half =
(CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2;
const spans = [];
for (const marker of markers) {
const at = project(marker.pos);
if (
!at ||
Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX
)
continue;
const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX;
spans.push([at.x - reach, at.x + reach]);
}
// Leave the entire overlapping interval, including an adjacent count.
spans.sort((a, b) => a[0] - b[0]);
let left = Infinity,
right = -Infinity;
for (const [start, end] of spans) {
if (start >= right) {
if (left < x && x < right) break;
left = start;
right = end;
} else right = Math.max(right, end);
}
if (!(left < x && x < right)) return;
const shift = x - left < right - x ? left - x : right - x;
const depth = dot(sub(p, pose.position), pose.direction);
const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth);
record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset;
record.spreadPosition = add(record.position, record.spreadOffset);
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
+1
View File
@@ -153,6 +153,7 @@ test('the icons go with the viewer that drew them, whichever tears down', () =>
name,
paint,
options,
setActive() {},
unregister() {
this.disposed = true;
},
+23 -5
View File
@@ -1,3 +1,4 @@
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
@@ -7,7 +8,7 @@ export function createSelection({
source,
}) {
const { CCTV_ACTIVATION_RESULT } = services.activation;
const { resolvePickId } = services.picking;
const { resolvePickId, findPickOwner } = services.picking;
/**
* Returns the camera record for the currently active camera. A stale ID falls
@@ -29,6 +30,23 @@ export function createSelection({
return fallback;
}
/** A card painted above the count, or another layer's object, owns the click. */
function countYields(event) {
const { x, y } = event.screenPosition;
if (
layerState._cctvOverlayHost?.hitTest(x, y, {
sourceId: CCTV_OVERLAY_SOURCE_ID,
})?.entryId
)
return true;
const top = event.topHit;
if (!top) return false;
const drawHit = event.drawHit;
if (drawHit) return !parts.rendering.extractPickedCameraId(drawHit);
const id = resolvePickId(top);
return id !== null && findPickOwner?.(id) !== 'cctv';
}
/**
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
@@ -44,7 +62,7 @@ export function createSelection({
const cell =
layerState._enabled &&
layerState._counts?.pickedCell(event.screenPosition);
if (cell) {
if (cell && !countYields(event)) {
parts.navigation.zoomToCell(cell);
return;
}
@@ -146,9 +164,9 @@ export function createSelection({
// is looking at ever asks.
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
// The active icon always shows and the previous one rejoins its cell.
// Restyle coverage after the view pass sets grouping. Its coverage
// neighbours join the working set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
+47
View File
@@ -1,3 +1,4 @@
import * as picking from '../../data/pickRegistry.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
@@ -103,3 +104,49 @@ test('a count click preserves the provisional opening pick until the view settle
unbind();
}
});
test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: {
hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null),
},
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
picking.registerPickOwner('cctv', (id) => id.startsWith('cam-'));
try {
for (const [x, topHit, expected] of [
[14, null, [0, 1]],
[20, { set: 'flights', id: 'abc' }, [0, 2]],
[20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]],
[20, null, [2, 2]],
[20, { set: 'flights', id: 'cam-2' }, [2, 3]],
]) {
click({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterPickOwner('cctv');
}
});
+8 -4
View File
@@ -96,13 +96,14 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// Includes a health-ranked representative for each visible group.
// The view records plus the best-ranked camera of each visible cell.
layerState._pickerRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
// The active camera's coverage neighbours, including grouped ones. A
// grouping change in this cohort requires a coverage refresh.
layerState._coverageCohort = null;
// The cohort minus grouped cameras, last drawn by refreshCoverageStyles.
// These belong to the geometry working set even off screen.
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
@@ -117,6 +118,9 @@ export function createState({ services }) {
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
// Reruns the view pass when terrain loads or the surface changes.
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
// A motion pass changed the shown set and the settle pass has not yet told
// subscribers; the camera pose the last view pass ran at.