mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
The bundled data centres now draw through the draw port, so there are no Cesium entities to walk and nothing sets the viewer's selected entity: the ownership check could not find a target at all. It now finds one from the layer's context records, accepts a draw-port pick by the context id of the item it carries, and counts gev:entity-selected announcements per click for that same item, which both the old and the new build send. Because a selecting click flies the camera away, the camera is put back and the same item is found again, before and after draw mode opens, so the drawing click lands on it rather than on plain ground. The drawing click must add a vertex with no selection announced and no selected entity. The hidden-Line check failed now and then with as much amber appearing as going. Two shots of an unchanged scene differed by 30 to 194 amber pixels on both builds: imagery was still refining after the fly-to, and the green area's pulsing fill moves borderline roofs across the amber threshold. Each shot now waits for the globe's tiles to load, and the other marks are set aside while the Line is shot and checked back afterwards. The thresholds are unchanged.
1201 lines
43 KiB
JavaScript
1201 lines
43 KiB
JavaScript
#!/usr/bin/env node
|
||
/** Rendered acceptance for UTILITIES ▸ Draw: real clicks, real keys, real teardown. */
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import puppeteer from 'puppeteer';
|
||
import { chromeExecutablePath } from './qa-chrome.mjs';
|
||
|
||
const BASE_URL = process.env.QA_BASE_URL || 'http://localhost:4173';
|
||
const SHOT_DIR = process.env.QA_SHOT_DIR || 'qa-shots/draw';
|
||
const SHOT_PREFIX = process.env.QA_SHOT_PREFIX || '';
|
||
const HEADFUL = process.env.QA_HEADFUL === '1';
|
||
// A dense, recognisable grid: neighbourhood blocks to enclose and a straight
|
||
// road to trace along.
|
||
const VIEW = {
|
||
lon: -122.4194,
|
||
lat: 37.7749,
|
||
height: 900,
|
||
heading: 0,
|
||
pitch: -85,
|
||
};
|
||
|
||
const browser = await puppeteer.launch({
|
||
headless: !HEADFUL,
|
||
...(HEADFUL
|
||
? {
|
||
executablePath: chromeExecutablePath(),
|
||
}
|
||
: {}),
|
||
args: [
|
||
'--no-sandbox',
|
||
'--disable-background-timer-throttling',
|
||
'--disable-renderer-backgrounding',
|
||
...(HEADFUL ? ['--window-size=1280,860'] : []),
|
||
...(process.platform === 'darwin'
|
||
? ['--use-angle=metal', '--enable-gpu']
|
||
: ['--use-gl=angle', '--use-angle=swiftshader']),
|
||
],
|
||
});
|
||
const page = await browser.newPage();
|
||
const errors = [];
|
||
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
|
||
let failures = 0;
|
||
function check(name, passed, detail = '') {
|
||
console.log(
|
||
`[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`,
|
||
);
|
||
if (!passed) failures++;
|
||
}
|
||
fs.mkdirSync(SHOT_DIR, { recursive: true });
|
||
const shot = (name) =>
|
||
page.screenshot({
|
||
path: path.join(SHOT_DIR, `${SHOT_PREFIX}${name}.jpg`),
|
||
type: 'jpeg',
|
||
quality: 82,
|
||
});
|
||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||
|
||
/** A clip of the globe canvas, clear of the panels on every side. */
|
||
const CANVAS_CLIP = { x: 340, y: 200, width: 560, height: 380 };
|
||
|
||
// Clear of the open UTILITIES panel (x 100–380), whose own amber swatch
|
||
// dims when its row's shape is hidden.
|
||
const LINE_CLIP = { x: 390, y: 200, width: 510, height: 380 };
|
||
/** The canvas clip as a PNG, for comparing two moments of the same view. */
|
||
const canvasShot = () =>
|
||
page.screenshot({ clip: LINE_CLIP, type: 'png', encoding: 'base64' });
|
||
|
||
/**
|
||
* `canvasShot` once the globe has no imagery or terrain tiles left to load
|
||
* (bounded: a view that never settles is shot as it is, and the comparison
|
||
* then reports what it sees). `globe.tilesLoaded` covers the globe only: a
|
||
* 3D Tiles tileset on a keyed server can still be refining when it is true.
|
||
*/
|
||
async function settledCanvasShot() {
|
||
await page
|
||
.waitForFunction(
|
||
() => {
|
||
const scene = window.__godsEyeView.viewer.scene;
|
||
scene.requestRender();
|
||
return scene.globe.tilesLoaded;
|
||
},
|
||
{ timeout: 15_000, polling: 100 },
|
||
)
|
||
.catch(() => {});
|
||
await wait(200);
|
||
return canvasShot();
|
||
}
|
||
|
||
/**
|
||
* Amber pixels in one shot that are not amber in another of the same view:
|
||
* a mark's own pixels, apart from imagery and panels that both shots share.
|
||
*/
|
||
function amberOnlyIn(shotA, shotB) {
|
||
return page.evaluate(
|
||
async (a, b) => {
|
||
const pixels = async (base64) => {
|
||
const bitmap = await createImageBitmap(
|
||
await (await fetch(`data:image/png;base64,${base64}`)).blob(),
|
||
);
|
||
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
|
||
const context = canvas.getContext('2d');
|
||
context.drawImage(bitmap, 0, 0);
|
||
return context.getImageData(0, 0, bitmap.width, bitmap.height).data;
|
||
};
|
||
const amber = (d, i) =>
|
||
d[i] > 150 &&
|
||
d[i + 1] > 90 &&
|
||
d[i + 1] < 220 &&
|
||
d[i + 2] < 130 &&
|
||
d[i] - d[i + 2] > 70 &&
|
||
d[i] - d[i + 1] > 20;
|
||
const [da, db] = [await pixels(a), await pixels(b)];
|
||
let only = 0;
|
||
for (let i = 0; i < da.length; i += 4)
|
||
if (amber(da, i) && !amber(db, i)) only += 1;
|
||
return only;
|
||
},
|
||
shotA,
|
||
shotB,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* How many amber pixels the clip contains. The drawn area's stroke and fill are
|
||
* the only amber in this scene, so the count going UP after a shape is finished
|
||
* is the shape actually painting — which is what CESIUM_3D_TILE-only
|
||
* classification failed to do on a keyless boot while still reporting a mark on
|
||
* the board. Decoding happens in the page because Node here has no image
|
||
* decoder.
|
||
*/
|
||
async function amberPixels() {
|
||
const shot64 = await page.screenshot({
|
||
clip: CANVAS_CLIP,
|
||
type: 'png',
|
||
encoding: 'base64',
|
||
});
|
||
return page.evaluate(async (base64) => {
|
||
const bitmap = await createImageBitmap(
|
||
await (await fetch(`data:image/png;base64,${base64}`)).blob(),
|
||
);
|
||
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
|
||
const context = canvas.getContext('2d');
|
||
context.drawImage(bitmap, 0, 0);
|
||
const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height);
|
||
let amber = 0;
|
||
for (let i = 0; i < data.length; i += 4) {
|
||
const r = data[i];
|
||
const g = data[i + 1];
|
||
const b = data[i + 2];
|
||
// Warm and saturated: the amber mark (#ffb547) blended over imagery.
|
||
if (r > 150 && g > 90 && g < 220 && b < 130 && r - b > 70 && r - g > 20)
|
||
amber += 1;
|
||
}
|
||
return amber;
|
||
}, shot64);
|
||
}
|
||
|
||
/**
|
||
* Press Enter as the person drawing does — with the map focused, not a button.
|
||
* Enter on a focused control means "press this control", so the tool ignores it
|
||
* there; the harness has to move focus the way a user would before using the
|
||
* finish key.
|
||
*/
|
||
async function pressFinish() {
|
||
await page.evaluate(() => document.activeElement?.blur?.());
|
||
await page.keyboard.press('Enter');
|
||
}
|
||
|
||
/** One click on the globe canvas, the way a person makes one. */
|
||
async function clickWorld(x, y, options = {}) {
|
||
await page.mouse.click(x, y, options);
|
||
await wait(options.settle ?? 140);
|
||
}
|
||
|
||
const drawState = () =>
|
||
page.evaluate(() => {
|
||
const tool = window.__gevDrawTool;
|
||
return {
|
||
...tool.diagnostics(),
|
||
shape: tool.shape,
|
||
vertices: tool.session?.vertices?.length ?? null,
|
||
hint: document.getElementById('draw-hint')?.textContent || '',
|
||
marks: window.__gevAnnotations.count(),
|
||
};
|
||
});
|
||
|
||
const marks = () =>
|
||
page.evaluate(() =>
|
||
window.__gevAnnotations.list().map((mark) => ({
|
||
type: mark.type,
|
||
label: mark.label,
|
||
color: mark.color,
|
||
source: mark.source ?? null,
|
||
})),
|
||
);
|
||
|
||
/** Wait until the board has settled at `expected` marks (annotate is async). */
|
||
async function waitForMarks(expected, timeout = 15_000) {
|
||
try {
|
||
await page.waitForFunction(
|
||
(want) => window.__gevAnnotations.count() === want,
|
||
{ timeout },
|
||
expected,
|
||
);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
try {
|
||
await page.setViewport({ width: 1280, height: 860 });
|
||
await page.goto(`${BASE_URL}/?welcome=0`, { waitUntil: 'domcontentloaded' });
|
||
await page.waitForFunction(
|
||
() =>
|
||
window.__gevDrawTool &&
|
||
window.__gevAnnotations &&
|
||
document.getElementById('loading-screen')?.classList.contains('hidden'),
|
||
{ timeout: 90_000 },
|
||
);
|
||
await page.evaluate((view) => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.scene.tweens?.removeAll?.();
|
||
viewer.camera.setView({
|
||
destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({
|
||
longitude: (view.lon * Math.PI) / 180,
|
||
latitude: (view.lat * Math.PI) / 180,
|
||
height: view.height,
|
||
}),
|
||
orientation: {
|
||
heading: (view.heading * Math.PI) / 180,
|
||
pitch: (view.pitch * Math.PI) / 180,
|
||
roll: 0,
|
||
},
|
||
});
|
||
viewer.scene.requestRender();
|
||
}, VIEW);
|
||
const settled = await page
|
||
.waitForFunction(
|
||
() => {
|
||
const primitives = window.__godsEyeView.viewer.scene.primitives;
|
||
for (let index = 0; index < primitives.length; index++) {
|
||
const primitive = primitives.get(index);
|
||
if (
|
||
typeof primitive.tilesLoaded === 'boolean' &&
|
||
!primitive.tilesLoaded
|
||
)
|
||
return false;
|
||
}
|
||
return true;
|
||
},
|
||
{ timeout: 90_000 },
|
||
)
|
||
.then(
|
||
() => true,
|
||
() => false,
|
||
);
|
||
check('visible tile content settles before drawing', settled);
|
||
|
||
// UTILITIES starts collapsed on a first run: open it the way a user does.
|
||
await page.evaluate(() => {
|
||
const panel = document.getElementById('utilities-panel');
|
||
if (panel?.classList.contains('collapsed'))
|
||
document
|
||
.querySelector(
|
||
'.panel-collapse-btn[data-collapse-target="utilities-panel"]',
|
||
)
|
||
?.click();
|
||
});
|
||
await page.waitForFunction(
|
||
() =>
|
||
document.getElementById('draw-toggle')?.getBoundingClientRect().width > 0,
|
||
{ timeout: 10_000 },
|
||
);
|
||
check(
|
||
'the Draw control is in the UTILITIES panel and starts off',
|
||
await page.evaluate(() => {
|
||
const toggle = document.getElementById('draw-toggle');
|
||
return (
|
||
toggle?.getAttribute('aria-pressed') === 'false' &&
|
||
!document.getElementById('draw-mode-row')?.classList.contains('visible')
|
||
);
|
||
}),
|
||
);
|
||
|
||
// The viewer's own select and follow, which the input port runs: on before
|
||
// the tool runs, off while drawing, and on again after.
|
||
const stockActions = async () => {
|
||
const state = await drawState();
|
||
return {
|
||
clickOn: state.stockSingleClick,
|
||
doubleOn: state.stockDoubleClick,
|
||
};
|
||
};
|
||
const beforeDraw = await stockActions();
|
||
|
||
// ── enable / disable cycles leave nothing behind ────────────────────────
|
||
const before = await drawState();
|
||
for (let cycle = 0; cycle < 3; cycle += 1) {
|
||
await page.click('#draw-toggle');
|
||
await wait(120);
|
||
await page.click('#draw-toggle');
|
||
await wait(120);
|
||
}
|
||
const after = await drawState();
|
||
check(
|
||
'three enable/disable cycles add no listener, handler or preview set',
|
||
after.domListeners === before.domListeners &&
|
||
after.previewSets === 2 &&
|
||
before.previewSets === 2 &&
|
||
after.sceneHandler === false &&
|
||
after.pointerOwner === null &&
|
||
after.stockDoubleClick === before.stockDoubleClick,
|
||
`listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewSets}, ` +
|
||
`handler ${after.sceneHandler}, owner ${after.pointerOwner}, stock dblclick ${after.stockDoubleClick}`,
|
||
);
|
||
|
||
// ── the viewer's own click actions are held off, then given back ───────
|
||
await page.click('#draw-toggle');
|
||
const duringDraw = await stockActions();
|
||
check(
|
||
"Cesium's own selecting click and tracking double-click are both off while drawing",
|
||
duringDraw.clickOn === false && duringDraw.doubleOn === false,
|
||
JSON.stringify({ beforeDraw, duringDraw }),
|
||
);
|
||
await page.click('#draw-toggle');
|
||
const afterDraw = await stockActions();
|
||
check(
|
||
'and both are back after',
|
||
afterDraw.clickOn === beforeDraw.clickOn &&
|
||
afterDraw.doubleOn === beforeDraw.doubleOn,
|
||
JSON.stringify({ beforeDraw, afterDraw }),
|
||
);
|
||
|
||
// ── a pin, finished with Enter ──────────────────────────────────────────
|
||
await page.click('#draw-toggle');
|
||
await page.click('.pp-mode-btn[data-shape="pin"]');
|
||
await clickWorld(520, 330);
|
||
check(
|
||
'the pointer is claimed while a session is open',
|
||
(await drawState()).pointerOwner === 'draw',
|
||
);
|
||
await page.keyboard.press('Enter');
|
||
check(
|
||
'a pin placed by mouse and finished with Enter lands on the board',
|
||
await waitForMarks(1),
|
||
);
|
||
|
||
// ── a line along a road, with Backspace ─────────────────────────────────
|
||
await page.click('.pp-mode-btn[data-shape="line"]');
|
||
// Clear of the open UTILITIES panel, which sits beside the left rail.
|
||
await clickWorld(420, 300);
|
||
await clickWorld(470, 380);
|
||
await clickWorld(600, 470);
|
||
const beforeBackspace = (await drawState()).vertices;
|
||
await page.keyboard.press('Backspace');
|
||
await wait(120);
|
||
const afterBackspace = (await drawState()).vertices;
|
||
check(
|
||
'Backspace removes the last vertex only',
|
||
beforeBackspace === 3 && afterBackspace === 2,
|
||
`${beforeBackspace} → ${afterBackspace}`,
|
||
);
|
||
await clickWorld(640, 500);
|
||
await page.keyboard.press('Enter');
|
||
check('a line finished with Enter lands on the board', await waitForMarks(2));
|
||
const lineMark = (await marks()).find((mark) => mark.type === 'route');
|
||
check(
|
||
'a drawn line reports its length and never a travel time',
|
||
Boolean(lineMark) &&
|
||
/\d/.test(lineMark.label) &&
|
||
!/min|walk|drive/i.test(lineMark.label),
|
||
lineMark?.label,
|
||
);
|
||
await shot('02-line-along-a-road');
|
||
|
||
// ── an area, coloured and labelled, finished with a double-click ────────
|
||
await page.click('.pp-mode-btn[data-shape="area"]');
|
||
await page.click('.draw-color[data-color="amber"]');
|
||
const amberBefore = await amberPixels();
|
||
await clickWorld(400, 280);
|
||
await clickWorld(700, 290);
|
||
await clickWorld(720, 520);
|
||
await clickWorld(410, 500);
|
||
const areaVertices = (await drawState()).vertices;
|
||
check(
|
||
'four clicks on the globe are four vertices',
|
||
areaVertices === 4,
|
||
`${areaVertices} vertices`,
|
||
);
|
||
await page.mouse.click(410, 500, { count: 2 });
|
||
const areaLanded = await waitForMarks(3);
|
||
await wait(900);
|
||
const afterDoubleClick = await page.evaluate(() =>
|
||
window.__gevAnnotations.count(),
|
||
);
|
||
check('an area finished by double-click lands on the board', areaLanded);
|
||
check(
|
||
'a double-click finishes the shape exactly once',
|
||
afterDoubleClick === 3,
|
||
`${afterDoubleClick} marks`,
|
||
);
|
||
// ── each drawn shape gets a row: named, recoloured, hidden from there ──
|
||
const rowIds = () =>
|
||
page.evaluate(() =>
|
||
[...document.querySelectorAll('#draw-mark-list [data-mark-id]')].map(
|
||
(row) => row.dataset.markId,
|
||
),
|
||
);
|
||
const ids = await rowIds();
|
||
check('every drawn shape has a row under Draw', ids.length === 3, ids);
|
||
const areaId = ids[2];
|
||
const rowControl = (id, control) =>
|
||
`#draw-mark-list [data-mark-id="${id}"] [data-control="${control}"]`;
|
||
await page.click(rowControl(areaId, 'name'));
|
||
await page.keyboard.type('Civic Center block');
|
||
await page.keyboard.press('Enter');
|
||
await wait(300);
|
||
const areaMark = (await marks()).find(
|
||
(mark) => mark.label === 'Civic Center block',
|
||
);
|
||
check(
|
||
'the name typed in its row and the colour picked before drawing are what is drawn',
|
||
areaMark?.color === 'amber',
|
||
JSON.stringify(areaMark),
|
||
);
|
||
check(
|
||
'naming a shape keeps Draw on and the shape in progress untouched',
|
||
(await drawState()).active === true,
|
||
);
|
||
await wait(1200);
|
||
const amberAfter = await amberPixels();
|
||
check(
|
||
'the finished area actually PAINTS — amber pixels appear on this surface',
|
||
amberAfter - amberBefore > 500,
|
||
`${amberBefore} → ${amberAfter} amber pixels (+${amberAfter - amberBefore})`,
|
||
);
|
||
await shot('01-area-with-label');
|
||
|
||
// ── the row's own controls: recolour, hide and show, fly to ─────────────
|
||
const markState = (id) =>
|
||
page.evaluate((id) => {
|
||
const mark = window.__gevAnnotations.list().find((m) => m.id === id);
|
||
return (
|
||
mark && { color: mark.color, hidden: mark.hidden, alpha: mark.alpha }
|
||
);
|
||
}, id);
|
||
// Wait for a mark to reach a state rather than for a fixed time.
|
||
const markReaches = (id, want) =>
|
||
page
|
||
.waitForFunction(
|
||
(id, want) => {
|
||
const mark = window.__gevAnnotations.list().find((m) => m.id === id);
|
||
return (
|
||
mark &&
|
||
Object.entries(want).every(([key, value]) => mark[key] === value)
|
||
);
|
||
},
|
||
{ timeout: 10_000 },
|
||
id,
|
||
want,
|
||
)
|
||
.then(
|
||
() => true,
|
||
() => false,
|
||
);
|
||
await page.click(rowControl(areaId, 'swatch'));
|
||
await page.click(rowControl(areaId, 'color-green'));
|
||
await markReaches(areaId, { color: 'green' });
|
||
check(
|
||
'a colour picked in the row recolours that shape',
|
||
(await markState(areaId))?.color === 'green',
|
||
);
|
||
await page.click(rowControl(areaId, 'toggle'));
|
||
await markReaches(areaId, { hidden: true, alpha: 0 });
|
||
const hidden = await markState(areaId);
|
||
check(
|
||
'hiding a shape keeps it on the board but draws it at zero alpha',
|
||
hidden?.hidden === true && hidden.alpha === 0,
|
||
JSON.stringify(hidden),
|
||
);
|
||
await page.click(rowControl(areaId, 'toggle'));
|
||
check(
|
||
'showing it again brings it straight back',
|
||
await markReaches(areaId, { hidden: false, alpha: 1 }),
|
||
);
|
||
// Fly-to frames the line by its whole path: once the flight settles, the
|
||
// middle of the line sits near the middle of the view.
|
||
await page.click(rowControl(ids[1], 'fly'));
|
||
await page
|
||
.waitForFunction(() => !window.__godsEyeView.viewer.camera._currentFlight, {
|
||
timeout: 15_000,
|
||
})
|
||
.catch(() => {});
|
||
await wait(300);
|
||
const framed = await page.evaluate((id) => {
|
||
const { viewer } = window.__godsEyeView;
|
||
// No Cesium global in the page: borrow Cartesian3 from a live object.
|
||
const Cartesian3 = viewer.camera.positionWC.constructor;
|
||
const mark = window.__gevAnnotations.list().find((m) => m.id === id);
|
||
const lons = mark.path.map((p) => p.lon);
|
||
const lats = mark.path.map((p) => p.lat);
|
||
const middle = Cartesian3.fromDegrees(
|
||
(Math.min(...lons) + Math.max(...lons)) / 2,
|
||
(Math.min(...lats) + Math.max(...lats)) / 2,
|
||
);
|
||
const at = viewer.scene.cartesianToCanvasCoordinates(middle);
|
||
const canvas = viewer.scene.canvas;
|
||
return (
|
||
at && {
|
||
dx: Math.abs(at.x - canvas.clientWidth / 2) / canvas.clientWidth,
|
||
dy: Math.abs(at.y - canvas.clientHeight / 2) / canvas.clientHeight,
|
||
}
|
||
);
|
||
}, ids[1]);
|
||
check(
|
||
'fly to frames that shape: its middle is near the middle of the view',
|
||
Boolean(framed) && framed.dx < 0.2 && framed.dy < 0.2,
|
||
JSON.stringify(framed),
|
||
);
|
||
|
||
// ── a hidden Line leaves the globe: its flowing stroke keeps its own
|
||
// colour, so the check is the pixels, not the mark's state ─────────────
|
||
const lineId = ids[1];
|
||
await page.click(rowControl(lineId, 'swatch'));
|
||
await page.click(rowControl(lineId, 'color-amber'));
|
||
await markReaches(lineId, { color: 'amber', alpha: 1 });
|
||
// Only the Line is on the board for its shots. The area's fill pulses, and
|
||
// under it borderline roofs drift into and out of amber between two shots
|
||
// of an unchanged scene, on the old build as on this one.
|
||
const others = await page.evaluate((id) => {
|
||
const marks = window.__gevAnnotations.list();
|
||
const ids = marks.filter((m) => m.id !== id && !m.hidden).map((m) => m.id);
|
||
for (const other of ids) window.__gevAnnotations.setHidden(other, true);
|
||
return ids;
|
||
}, lineId);
|
||
for (const other of others)
|
||
await markReaches(other, { hidden: true, alpha: 0 });
|
||
await wait(800);
|
||
// The fly-to above is still refining imagery near the camera at this
|
||
// point; a tile that sharpens between the two shots repaints roofs into
|
||
// and out of amber, so each shot waits for the globe to finish loading.
|
||
const shown = await settledCanvasShot();
|
||
await page.click(rowControl(lineId, 'toggle'));
|
||
await markReaches(lineId, { hidden: true, alpha: 0 });
|
||
await wait(800);
|
||
const hiddenShot = await settledCanvasShot();
|
||
// Amber the shown line had and the hidden one lost; amber that appears
|
||
// only once it is hidden is noise, and must stay small beside it.
|
||
const gone = await amberOnlyIn(shown, hiddenShot);
|
||
const noise = await amberOnlyIn(hiddenShot, shown);
|
||
check(
|
||
'a hidden Line is no longer painted',
|
||
gone > 40 && noise < gone * 0.2,
|
||
`${gone} amber pixels went with the line, ${noise} appeared`,
|
||
);
|
||
await page.click(rowControl(lineId, 'toggle'));
|
||
await wait(1200);
|
||
const back = await amberOnlyIn(await settledCanvasShot(), hiddenShot);
|
||
check(
|
||
'and paints again when shown',
|
||
back > gone * 0.5,
|
||
`${back} of ${gone} line pixels back`,
|
||
);
|
||
await page.evaluate((ids) => {
|
||
for (const other of ids) window.__gevAnnotations.setHidden(other, false);
|
||
}, others);
|
||
const restored = [];
|
||
for (const other of others)
|
||
if (await markReaches(other, { hidden: false, alpha: 1 }))
|
||
restored.push(other);
|
||
check(
|
||
'the marks set aside for the Line shots are back on the board',
|
||
restored.length === others.length,
|
||
`${restored.length} of ${others.length} back`,
|
||
);
|
||
await shot('03-pins-and-shapes');
|
||
|
||
// ── Escape cancels the shape, a second Escape leaves draw mode ──────────
|
||
await page.evaluate(() => window.__gevDrawTool.cancel());
|
||
await clickWorld(500, 300);
|
||
await clickWorld(560, 340);
|
||
check('a new shape is in progress', (await drawState()).vertices === 2);
|
||
await page.keyboard.press('Escape');
|
||
await wait(150);
|
||
const afterFirstEscape = await drawState();
|
||
check(
|
||
'Escape cancels the shape in progress and stays in draw mode',
|
||
afterFirstEscape.vertices === 0 && afterFirstEscape.active === true,
|
||
`vertices ${afterFirstEscape.vertices}, active ${afterFirstEscape.active}`,
|
||
);
|
||
await page.keyboard.press('Escape');
|
||
await wait(150);
|
||
const afterSecondEscape = await drawState();
|
||
check(
|
||
'a second Escape leaves draw mode and gives the pointer back',
|
||
afterSecondEscape.active === false &&
|
||
afterSecondEscape.pointerOwner === null &&
|
||
afterSecondEscape.sceneHandler === false,
|
||
JSON.stringify(afterSecondEscape),
|
||
);
|
||
check(
|
||
'cancelling never removes a mark already on the board',
|
||
afterSecondEscape.marks === 3,
|
||
`${afterSecondEscape.marks} marks`,
|
||
);
|
||
await page.click(rowControl(ids[0], 'remove'));
|
||
await waitForMarks(2);
|
||
check(
|
||
'remove in a row takes that one shape off the board and out of the list',
|
||
(await rowIds()).join() === ids.slice(1).join(),
|
||
);
|
||
|
||
// ── a click that would select something selects nothing while drawing ───
|
||
const target = await findClickableTarget();
|
||
check(
|
||
'a selectable layer entity is on screen to test click ownership against',
|
||
Boolean(target),
|
||
target
|
||
? `${target.layer} at ${target.x},${target.y}`
|
||
: 'no CCTV camera or bundled site could be reached — the ownership case cannot be proved',
|
||
);
|
||
if (target) {
|
||
// The camera pose the target was found at: a selecting click flies the
|
||
// camera to what it picked, so the drawing click has to come back here
|
||
// and find the target again, or it would land on plain ground.
|
||
await page.evaluate(() => {
|
||
const camera = window.__godsEyeView.viewer.camera;
|
||
window.__qaTargetView = {
|
||
destination: camera.positionWC.clone(),
|
||
orientation: {
|
||
heading: camera.heading,
|
||
pitch: camera.pitch,
|
||
roll: camera.roll,
|
||
},
|
||
};
|
||
});
|
||
await page.evaluate(clearSelection);
|
||
await page.evaluate(startSelectionCount);
|
||
await clickWorld(target.x, target.y, { settle: 900 });
|
||
const normal = await page.evaluate(readSelectionCount, target.key);
|
||
check(
|
||
`clicking a ${target.layer} selects it when nothing owns the pointer`,
|
||
// The CCTV branch looks for `CAM-` Cesium entities and reads the
|
||
// viewer's selection; neither build draws cameras that way any more, so
|
||
// it is not reached and the bundled data centre is the target.
|
||
normal.item > 0 || (target.layerId === 'cctv' && normal.entity),
|
||
`${normal.item} selection(s) of ${target.key}, ${normal.all} in all, entity ${normal.entity}`,
|
||
);
|
||
await page.evaluate(clearSelection);
|
||
await page.evaluate(() => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.camera.setView(window.__qaTargetView);
|
||
viewer.scene.requestRender();
|
||
});
|
||
await wait(1500);
|
||
const again = await onScreen(
|
||
target.belongs,
|
||
target.contextPrefix,
|
||
target.key,
|
||
);
|
||
check(
|
||
`the ${target.layer} is picked again after the camera returns`,
|
||
Boolean(again),
|
||
again ? `at ${again.x},${again.y}` : 'not picked on screen any more',
|
||
);
|
||
if (again) {
|
||
await page.click('#draw-toggle');
|
||
await page.click('.pp-mode-btn[data-shape="area"]');
|
||
// Draw mode's own panel must not have covered it: the drawing click has
|
||
// to land on the same item, not on plain ground.
|
||
const drawingSpot = await onScreen(
|
||
target.belongs,
|
||
target.contextPrefix,
|
||
target.key,
|
||
);
|
||
check(
|
||
`the ${target.layer} is still picked once draw mode is open`,
|
||
Boolean(drawingSpot),
|
||
drawingSpot
|
||
? `at ${drawingSpot.x},${drawingSpot.y}`
|
||
: 'not picked on screen in draw mode',
|
||
);
|
||
if (drawingSpot) {
|
||
await page.evaluate(startSelectionCount);
|
||
await clickWorld(drawingSpot.x, drawingSpot.y, { settle: 900 });
|
||
const whileDrawing = await drawState();
|
||
const drawingSelection = await page.evaluate(
|
||
readSelectionCount,
|
||
target.key,
|
||
);
|
||
check(
|
||
`clicking the same ${target.layer} while drawing adds a vertex and selects nothing`,
|
||
whileDrawing.vertices === 1 &&
|
||
drawingSelection.all === 0 &&
|
||
!drawingSelection.entity,
|
||
`vertices ${whileDrawing.vertices}, ${drawingSelection.all} selection(s), entity ${drawingSelection.entity}`,
|
||
);
|
||
}
|
||
await page.keyboard.press('Escape');
|
||
await page.keyboard.press('Escape');
|
||
await wait(150);
|
||
}
|
||
}
|
||
|
||
// ── what a reload actually does ─────────────────────────────────────────
|
||
const beforeReload = await page.evaluate(() =>
|
||
window.__gevAnnotations.count(),
|
||
);
|
||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||
await page.waitForFunction(
|
||
() =>
|
||
window.__gevAnnotations &&
|
||
document.getElementById('loading-screen')?.classList.contains('hidden'),
|
||
{ timeout: 90_000 },
|
||
);
|
||
const afterReload = await page.evaluate(() =>
|
||
window.__gevAnnotations.count(),
|
||
);
|
||
check(
|
||
'a reload starts an empty board — marks live for the session, not across reloads',
|
||
beforeReload > 0 && afterReload === 0,
|
||
`${beforeReload} before, ${afterReload} after`,
|
||
);
|
||
|
||
// ── Clear wipes the board ───────────────────────────────────────────────
|
||
await page.evaluate(() => {
|
||
const panel = document.getElementById('utilities-panel');
|
||
if (panel?.classList.contains('collapsed'))
|
||
document
|
||
.querySelector(
|
||
'.panel-collapse-btn[data-collapse-target="utilities-panel"]',
|
||
)
|
||
?.click();
|
||
});
|
||
await page.waitForFunction(
|
||
() =>
|
||
document.getElementById('draw-toggle')?.getBoundingClientRect().width > 0,
|
||
{ timeout: 10_000 },
|
||
);
|
||
await page.evaluate((view) => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.camera.setView({
|
||
destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({
|
||
longitude: (view.lon * Math.PI) / 180,
|
||
latitude: (view.lat * Math.PI) / 180,
|
||
height: view.height,
|
||
}),
|
||
orientation: { heading: 0, pitch: (view.pitch * Math.PI) / 180, roll: 0 },
|
||
});
|
||
}, VIEW);
|
||
await wait(2500);
|
||
await page.click('#draw-toggle');
|
||
await page.click('.pp-mode-btn[data-shape="area"]');
|
||
await clickWorld(420, 280);
|
||
await clickWorld(700, 300);
|
||
await clickWorld(660, 520);
|
||
await pressFinish();
|
||
const drewAgain = await waitForMarks(1);
|
||
check('a shape can be drawn again after a reload', drewAgain);
|
||
|
||
// Enter belongs to whatever the keyboard is on. With Clear focused it must
|
||
// PRESS CLEAR — the shape in progress goes, and so does the mark already on
|
||
// the board — and it must NOT quietly finish a second shape.
|
||
await clickWorld(430, 300);
|
||
await clickWorld(690, 320);
|
||
await clickWorld(670, 500);
|
||
const beforeButtonEnter = await drawState();
|
||
await page.focus('#draw-clear');
|
||
await page.keyboard.press('Enter');
|
||
await wait(600);
|
||
const afterButtonEnter = await drawState();
|
||
check(
|
||
'Enter on a keyboard-focused button activates the button, it does not finish the shape',
|
||
beforeButtonEnter.vertices === 3 &&
|
||
beforeButtonEnter.marks === 1 &&
|
||
afterButtonEnter.marks === 0 &&
|
||
afterButtonEnter.vertices === 0,
|
||
`before ${beforeButtonEnter.vertices} vertices / ${beforeButtonEnter.marks} marks, ` +
|
||
`after ${afterButtonEnter.vertices} / ${afterButtonEnter.marks} ` +
|
||
'(a finish would have made it 2 marks)',
|
||
);
|
||
|
||
// Put one back so the Clear BUTTON check below has something to remove.
|
||
await clickWorld(420, 280);
|
||
await clickWorld(700, 300);
|
||
await clickWorld(660, 520);
|
||
await pressFinish();
|
||
check(
|
||
'a shape can be drawn after the board was cleared from the keyboard',
|
||
await waitForMarks(1),
|
||
);
|
||
await page.click('#draw-clear');
|
||
await wait(400);
|
||
const cleared = await drawState();
|
||
check(
|
||
'Clear removes every mark from the board',
|
||
cleared.marks === 0,
|
||
`${cleared.marks} marks left`,
|
||
);
|
||
await shot('04-after-clear');
|
||
|
||
// ── a shape that describes nothing is refused, not placed ───────────────
|
||
const degenerateVertices = await page.evaluate(() => {
|
||
const tool = window.__gevDrawTool;
|
||
tool.cancel();
|
||
// Three points on one line, placed through the same addVertex the clicks use.
|
||
tool.addVertex(-122.42, 37.77);
|
||
tool.addVertex(-122.42, 37.771);
|
||
tool.addVertex(-122.42, 37.772);
|
||
return tool.session?.vertices?.length ?? null;
|
||
});
|
||
check(
|
||
'three collinear vertices are accepted into the session',
|
||
degenerateVertices === 3,
|
||
`${degenerateVertices} vertices`,
|
||
);
|
||
await pressFinish();
|
||
await wait(600);
|
||
const degenerate = await drawState();
|
||
check(
|
||
'three points in a line are refused with a reason, not placed',
|
||
degenerate.marks === 0 && /in a line/.test(degenerate.hint),
|
||
`${degenerate.marks} marks, hint "${degenerate.hint}"`,
|
||
);
|
||
|
||
// ── a shape drawn across the antimeridian lands where it was drawn ──────
|
||
await page.evaluate(() => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.camera.setView({
|
||
destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({
|
||
longitude: (179.9995 * Math.PI) / 180,
|
||
latitude: 0,
|
||
height: 3000,
|
||
}),
|
||
orientation: { heading: 0, pitch: (-88 * Math.PI) / 180, roll: 0 },
|
||
});
|
||
viewer.scene.requestRender();
|
||
});
|
||
await wait(2500);
|
||
await page.evaluate(() => {
|
||
const tool = window.__gevDrawTool;
|
||
tool.cancel();
|
||
tool.setShape('area');
|
||
// A ~200 m square straddling 180.
|
||
tool.addVertex(179.999, -0.001);
|
||
tool.addVertex(-179.999, -0.001);
|
||
tool.addVertex(-179.999, 0.001);
|
||
tool.addVertex(179.999, 0.001);
|
||
});
|
||
await pressFinish();
|
||
const datelineLanded = await waitForMarks(1);
|
||
const datelineAnchor = await page.evaluate(() => {
|
||
const mark = window.__gevAnnotations.list()[0];
|
||
return mark ? { lon: mark.anchor?.lon, lat: mark.anchor?.lat } : null;
|
||
});
|
||
check(
|
||
'a shape drawn across the antimeridian anchors there, not on the Greenwich meridian',
|
||
datelineLanded &&
|
||
datelineAnchor &&
|
||
Math.abs(Math.abs(datelineAnchor.lon) - 180) < 0.1 &&
|
||
Math.abs(datelineAnchor.lat) < 0.1,
|
||
JSON.stringify(datelineAnchor),
|
||
);
|
||
await page.evaluate(() => window.__gevAnnotations.clear());
|
||
|
||
await page.click('#draw-toggle');
|
||
await wait(200);
|
||
const finalState = await drawState();
|
||
check(
|
||
'leaving draw mode gives back the pointer, the handler and the double-click',
|
||
finalState.active === false &&
|
||
finalState.pointerOwner === null &&
|
||
finalState.sceneHandler === false &&
|
||
finalState.previewSets === 2,
|
||
JSON.stringify(finalState),
|
||
);
|
||
// ── destroy(): the shell disposing the tool leaves nothing behind ───────
|
||
await page.click('#draw-toggle'); // destroy from an ACTIVE session: the harder case
|
||
await wait(200);
|
||
const destroyed = await page.evaluate(async () => {
|
||
const tool = window.__gevDrawTool;
|
||
const wasActive = tool.active;
|
||
await tool.destroy();
|
||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||
const diagnostics = tool.diagnostics();
|
||
return {
|
||
wasActive,
|
||
diagnostics,
|
||
previews: diagnostics.previewSets,
|
||
handleGone: window.__gevDrawTool === undefined,
|
||
// The viewer's own select and follow run again.
|
||
clickRestored: diagnostics.stockSingleClick,
|
||
doubleRestored: diagnostics.stockDoubleClick,
|
||
drawingClass: document.body.classList.contains('gev-drawing'),
|
||
};
|
||
});
|
||
check(
|
||
'destroy() from an active session releases the pointer, handler and listeners',
|
||
destroyed.wasActive === true &&
|
||
destroyed.diagnostics.destroyed === true &&
|
||
destroyed.diagnostics.pointerOwner === null &&
|
||
destroyed.diagnostics.sceneHandler === false &&
|
||
destroyed.diagnostics.domListeners === 0 &&
|
||
destroyed.drawingClass === false,
|
||
JSON.stringify(destroyed.diagnostics),
|
||
);
|
||
check(
|
||
'destroy() disposes the preview draw sets and gives the window handle back',
|
||
destroyed.previews === 0 && destroyed.handleGone,
|
||
`preview sets ${destroyed.previews}, handle gone ${destroyed.handleGone}`,
|
||
);
|
||
check(
|
||
"destroy() returns Cesium's own click actions",
|
||
destroyed.clickRestored && destroyed.doubleRestored,
|
||
`click ${destroyed.clickRestored}, double ${destroyed.doubleRestored}`,
|
||
);
|
||
|
||
check(
|
||
'no uncaught page errors across the run',
|
||
errors.length === 0,
|
||
errors.join(' | '),
|
||
);
|
||
} finally {
|
||
await browser.close();
|
||
}
|
||
console.log(`RESULT: ${failures} failures`);
|
||
process.exitCode = failures ? 1 : 0;
|
||
|
||
/**
|
||
* Find something on screen that a layer would select on click, so the ownership
|
||
* guard can be proved against a real selection rather than a stub. Bundled
|
||
* infrastructure first (no network, works keyless); CCTV cameras if they are up.
|
||
*/
|
||
async function findClickableTarget() {
|
||
// CCTV first: it is the layer the brief names, and it goes through the shared
|
||
// tracking click gesture that flights and military use too.
|
||
const camera = await page
|
||
.evaluate(async () => {
|
||
const manager = window.__godsEyeView.dataManager;
|
||
await manager.setEnabled('cctv', true, { origin: 'user' });
|
||
const module = manager.layers.get('cctv')?.module;
|
||
if (!module?.getUIState) return null;
|
||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||
const cameras = module.getUIState()?.cameras || [];
|
||
const found = cameras.find((entry) => {
|
||
const lat = entry.lat ?? entry.latitude;
|
||
const lon = entry.lon ?? entry.longitude;
|
||
return Number.isFinite(lat) && Number.isFinite(lon);
|
||
});
|
||
if (found)
|
||
return {
|
||
id: found.id,
|
||
lat: found.lat ?? found.latitude,
|
||
lon: found.lon ?? found.longitude,
|
||
};
|
||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||
}
|
||
return null;
|
||
})
|
||
.catch(() => null);
|
||
|
||
if (camera) {
|
||
await page.evaluate((spot) => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.camera.setView({
|
||
destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({
|
||
longitude: (spot.lon * Math.PI) / 180,
|
||
latitude: (spot.lat * Math.PI) / 180,
|
||
height: 600,
|
||
}),
|
||
orientation: { heading: 0, pitch: (-80 * Math.PI) / 180, roll: 0 },
|
||
});
|
||
viewer.scene.requestRender();
|
||
}, camera);
|
||
await wait(4000);
|
||
const spot = await onScreen(cameraEntity);
|
||
if (spot)
|
||
return {
|
||
...spot,
|
||
layer: 'CCTV camera',
|
||
layerId: 'cctv',
|
||
belongs: cameraEntity,
|
||
contextPrefix: null,
|
||
};
|
||
}
|
||
|
||
// Bundled infrastructure as the keyless fallback: a different guarded handler,
|
||
// the same shared claim, and always present without a key.
|
||
const site = await page
|
||
.evaluate(async () => {
|
||
// The app registers each local feature's context as `<layer id>:<feature id>`,
|
||
// with its coordinates, whether the layer draws Cesium entities or
|
||
// through the draw port.
|
||
await window.__godsEyeView.dataManager.setEnabled(
|
||
'local-datacenters',
|
||
true,
|
||
{
|
||
origin: 'user',
|
||
},
|
||
);
|
||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||
const records = window.__gevContextStore?.entities?.values() ?? [];
|
||
for (const record of records) {
|
||
if (!String(record?.id).startsWith('local-datacenters:')) continue;
|
||
if (
|
||
!Number.isFinite(record.latitude) ||
|
||
!Number.isFinite(record.longitude)
|
||
)
|
||
continue;
|
||
return { lon: record.longitude, lat: record.latitude };
|
||
}
|
||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||
}
|
||
return null;
|
||
})
|
||
.catch(() => null);
|
||
if (!site) return null;
|
||
await page.evaluate((spot) => {
|
||
const viewer = window.__godsEyeView.viewer;
|
||
viewer.camera.cancelFlight?.();
|
||
viewer.camera.setView({
|
||
destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({
|
||
longitude: (spot.lon * Math.PI) / 180,
|
||
latitude: (spot.lat * Math.PI) / 180,
|
||
height: 2500,
|
||
}),
|
||
orientation: { heading: 0, pitch: (-88 * Math.PI) / 180, roll: 0 },
|
||
});
|
||
viewer.scene.requestRender();
|
||
}, site);
|
||
await wait(4000);
|
||
const spot = await onScreen(dataCentre, 'local-datacenters:');
|
||
return spot
|
||
? {
|
||
...spot,
|
||
layer: 'data centre',
|
||
layerId: 'local-datacenters',
|
||
belongs: dataCentre,
|
||
contextPrefix: 'local-datacenters:',
|
||
}
|
||
: null;
|
||
}
|
||
|
||
/** A CCTV camera entity (runs in the page through `onScreen`). */
|
||
function cameraEntity(entity) {
|
||
return typeof entity.id === 'string' && entity.id.startsWith('CAM-');
|
||
}
|
||
|
||
/**
|
||
* A bundled data centre: a Cesium entity carrying its context, or a draw-port
|
||
* pick id `{ set, id }` from a set named `<layer id>:<n>:<part>` (runs in the
|
||
* page through `onScreen`).
|
||
*/
|
||
function dataCentre(entity) {
|
||
return (
|
||
window.__godsEyeView.entityRecords
|
||
.read(entity)
|
||
?.contextId?.startsWith('local-datacenters:') ||
|
||
(typeof entity?.set === 'string' &&
|
||
entity.set.startsWith('local-datacenters:'))
|
||
);
|
||
}
|
||
|
||
/** Clear both selection slots (runs in the page). */
|
||
function clearSelection() {
|
||
window.__godsEyeView.viewer.selectedEntity = undefined;
|
||
const store = window.__gevContextStore;
|
||
if (store) store.selectedEntityId = null;
|
||
}
|
||
|
||
/**
|
||
* Count click selections from now on (runs in the page). A layer selects
|
||
* through the shared context store, which announces each selection with
|
||
* `gev:entity-selected`; one drawn through the draw port has no Cesium entity
|
||
* to set as the viewer's selection. Counting the announcements rather than
|
||
* reading the slot keeps an earlier selection, or a tracking layer refilling
|
||
* the slot without announcing, from deciding the result.
|
||
*/
|
||
function startSelectionCount() {
|
||
const seen = [];
|
||
window.removeEventListener('gev:entity-selected', window.__qaOnSelected);
|
||
window.__qaSelections = seen;
|
||
window.__qaOnSelected = (event) => seen.push(event.detail ?? null);
|
||
window.addEventListener('gev:entity-selected', window.__qaOnSelected);
|
||
}
|
||
|
||
/**
|
||
* Selections since `startSelectionCount` (runs in the page): `all`, those of
|
||
* the item whose context id is `key`, and whether the viewer holds a selected
|
||
* Cesium entity.
|
||
* @param {string} key
|
||
* @returns {{ all: number, item: number, entity: boolean }}
|
||
*/
|
||
function readSelectionCount(key) {
|
||
const seen = window.__qaSelections || [];
|
||
return {
|
||
all: seen.length,
|
||
item: seen.filter((record) => record?.id === key).length,
|
||
entity: Boolean(window.__godsEyeView.viewer.selectedEntity),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Canvas coordinates of the first entity matching `belongs` that is on screen
|
||
* and clear of the side panels. Annotation marks and the draw tool's own
|
||
* preview vertices are on screen too, so the predicate has to be specific.
|
||
* With `contextPrefix`, the context store's records under that prefix are
|
||
* candidates too (at their ground coordinates), for a layer drawn through the
|
||
* draw port, which has no entities to walk; `belongs` then also receives the
|
||
* draw-port pick id. Returns the spot and `key`, the picked item's context id
|
||
* (from the entity's record or the draw-port item's `meta`; without a prefix,
|
||
* the entity's own id); with `wantKey`, only that item counts.
|
||
*/
|
||
async function onScreen(
|
||
belongs,
|
||
contextPrefix = null,
|
||
wantKey = null,
|
||
timeout = 20_000,
|
||
) {
|
||
return page
|
||
.waitForFunction(
|
||
(belongsSource, prefix, want) => {
|
||
// eslint-disable-next-line no-new-func
|
||
const belongsTo = new Function(`return (${belongsSource})`)();
|
||
const viewer = window.__godsEyeView.viewer;
|
||
const scene = viewer.scene;
|
||
const collections = [viewer.entities];
|
||
for (let i = 0; i < viewer.dataSources.length; i += 1) {
|
||
const source = viewer.dataSources.get(i);
|
||
if (source?.name === 'gev-draw-preview') continue;
|
||
collections.push(source.entities);
|
||
}
|
||
const candidates = [];
|
||
for (const source of collections) {
|
||
for (const entity of source.values) {
|
||
if (!belongsTo(entity)) continue;
|
||
const position = entity.position?.getValue?.(
|
||
viewer.clock.currentTime,
|
||
);
|
||
if (position) candidates.push(position);
|
||
}
|
||
}
|
||
if (prefix) {
|
||
const ellipsoid = scene.globe.ellipsoid;
|
||
for (const record of window.__gevContextStore?.entities?.values() ??
|
||
[]) {
|
||
if (!String(record?.id).startsWith(prefix)) continue;
|
||
if (
|
||
!Number.isFinite(record.latitude) ||
|
||
!Number.isFinite(record.longitude)
|
||
)
|
||
continue;
|
||
candidates.push(
|
||
ellipsoid.cartographicToCartesian({
|
||
longitude: (record.longitude * Math.PI) / 180,
|
||
latitude: (record.latitude * Math.PI) / 180,
|
||
height: 0,
|
||
}),
|
||
);
|
||
}
|
||
}
|
||
for (const position of candidates) {
|
||
const window2d = scene.cartesianToCanvasCoordinates(position);
|
||
if (!window2d) continue;
|
||
const { x, y } = window2d;
|
||
if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue;
|
||
// Projecting into the window is not the same as being clickable:
|
||
// the entity may be beyond the horizon or behind a building. Only a
|
||
// spot where the scene actually picks it proves the control case.
|
||
const hit = scene.pick({ x: Math.round(x), y: Math.round(y) });
|
||
if (!hit?.id || !belongsTo(hit.id)) continue;
|
||
// The picked item's context id: an entity's own record, or that of
|
||
// the object a draw-port item carries as its `meta`.
|
||
const pickId = hit.id;
|
||
const records = window.__godsEyeView.entityRecords;
|
||
const key =
|
||
records.read(pickId)?.contextId ||
|
||
records.read(pickId.meta)?.contextId ||
|
||
(prefix ? null : String(pickId.id));
|
||
if (!key || (want && key !== want)) continue;
|
||
return { x: Math.round(x), y: Math.round(y), key };
|
||
}
|
||
return false;
|
||
},
|
||
{ timeout, polling: 500 },
|
||
belongs.toString(),
|
||
contextPrefix,
|
||
wantKey,
|
||
)
|
||
.then(
|
||
(handle) => handle.jsonValue(),
|
||
() => null,
|
||
);
|
||
}
|