Draw the Draw tool's live preview through the draw port and take the tool off the Cesium list

The preview of a shape being drawn is now two sets on the renderer's draw
port instead of a Cesium data source: one dashed rubber band along the
globe (the chosen colour at 0.9, 3 px, dash 16, primary at 0.35 behind
the surface) and a dot per vertex (8 px, black outline at 0.6, drawn over
depth). The band is written on each pointer move and vertex change
rather than re-read every frame. A pointer move now carries
`pickPosition`, its point in the pick buffer corrected for sensor styles
as a click's position is, which the rubber band follows; the tool reads
its canvas from the renderer and asks frames through the frame port.

The diagnostics count the preview sets live on the viewer
(`previewSets`, `previewItems`) in place of preview data sources.

One difference: where the band runs behind the surface it is drawn in a
solid colour, as the draw contract's depth-fail colour is a colour, not
a dashed material.
This commit is contained in:
Sameh Khamis committed 2026-11-07 16:56:49 -08:00
1 parent c49191a87b
commit 3cce1aaa3e
7 files changed
+198 -167

No files matched your search

+1 -1
View File
@@ -5658,7 +5658,7 @@ request viewbox and continues searching without that geographic preference.
- UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone.
- **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too.
- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the Cesium handler, the preview data source, the borrowed click actions and the `window.__gevDrawTool` handle. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam.
- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam.
- Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins.
- **A vertex is a lon/lat, and the mark is DRAPED.** Clicks are picked through `pickWorldFromScreen` — one of two scene helpers the annotation resolver factory (`src/annotations/resolver.js`) exposes alongside `sampleGroundHeight`, so the app has ONE depth-aware pick cascade rather than a second written beside it — which returns the height the pick landed on as well as the coordinate, so the live preview hangs on the roof or hillside under the pointer instead of sinking to sea level. The world renderer draws areas and routes with `clampToGround`, so the height is dropped at finish in one place (`finishSpec`) rather than being carried downstream and discarded silently: what you get is the outline you drew, lying on the surface beneath it.
- **Draped marks classify onto `ClassificationType.BOTH`** — terrain AND 3D tiles — not onto 3D tiles alone. With only `CESIUM_3D_TILE`, every area fill, area outline, route and arrow rendered to nothing on a keyless boot, where Cesium's own globe carries Esri/OSM imagery and there are no tiles to classify against; the labels appeared and the geometry did not. That hit spoken annotations exactly as hard as hand-drawn ones. `scripts/qa-draw-tool.mjs` counts the mark's own colour in the rendered frame before and after a shape is finished, on a keyed AND a keyless server, so "the board says there is a mark" can no longer pass for "the mark is on screen".
+9 -19
View File
@@ -284,14 +284,14 @@ try {
}
const after = await drawState();
check(
'three enable/disable cycles add no listener, handler or preview data source',
'three enable/disable cycles add no listener, handler or preview set',
after.domListeners === before.domListeners &&
after.previewDataSources === 1 &&
before.previewDataSources === 1 &&
after.previewSets === 2 &&
before.previewSets === 2 &&
after.sceneHandler === false &&
after.pointerOwner === null &&
after.stockDoubleClick === before.stockDoubleClick,
`listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewDataSources}, ` +
`listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewSets}, ` +
`handler ${after.sceneHandler}, owner ${after.pointerOwner}, stock dblclick ${after.stockDoubleClick}`,
);
@@ -774,13 +774,10 @@ try {
finalState.active === false &&
finalState.pointerOwner === null &&
finalState.sceneHandler === false &&
finalState.previewDataSources === 1,
finalState.previewSets === 2,
JSON.stringify(finalState),
);
// ── destroy(): the shell disposing the tool leaves nothing behind ───────
const beforeDestroy = await page.evaluate(
() => window.__godsEyeView.viewer.dataSources.length,
);
await page.click('#draw-toggle'); // destroy from an ACTIVE session: the harder case
await wait(200);
const destroyed = await page.evaluate(async () => {
@@ -788,16 +785,11 @@ try {
const wasActive = tool.active;
await tool.destroy();
await new Promise((resolve) => setTimeout(resolve, 50));
const viewer = window.__godsEyeView.viewer;
let previews = 0;
for (let i = 0; i < viewer.dataSources.length; i += 1)
if (viewer.dataSources.get(i)?.name === 'gev-draw-preview') previews += 1;
const diagnostics = tool.diagnostics();
return {
wasActive,
diagnostics,
previews,
dataSources: viewer.dataSources.length,
previews: diagnostics.previewSets,
handleGone: window.__gevDrawTool === undefined,
// The viewer's own select and follow run again.
clickRestored: diagnostics.stockSingleClick,
@@ -816,11 +808,9 @@ try {
JSON.stringify(destroyed.diagnostics),
);
check(
'destroy() detaches the preview data source and gives the window handle back',
destroyed.previews === 0 &&
destroyed.dataSources === beforeDestroy - 1 &&
destroyed.handleGone,
`previews ${destroyed.previews}, dataSources ${beforeDestroy} → ${destroyed.dataSources}, handle gone ${destroyed.handleGone}`,
'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",
+100 -101
View File
@@ -1,5 +1,5 @@
/**
* Manual whiteboard drawing: the Cesium + DOM half.
* Manual whiteboard drawing: the scene + DOM half.
*
* UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
* shape (area, line or pin) and a colour, click the vertices on the real world,
@@ -20,7 +20,7 @@
* pointer) and double click (track it) on the viewer's handler, outside every
* layer and therefore outside the shared claim. Both are suppressed for the
* session and given back on the way out, and `destroy()` gives back every
* listener, the pointer subscriptions, the preview data source and the window
* listener, the pointer subscriptions, the preview draw sets and the window
* handle, so the tool can be turned off or the shell disposed without leaving
* anything behind.
*
@@ -30,7 +30,6 @@
* drapes finished areas and routes onto the surface, so the height is dropped
* at finish, deliberately and in one place — see `finishSpec` in drawMode.js.
*/
import * as Cesium from 'cesium';
import { pickWorldFromScreen } from './annotationResolver.js';
import {
claimPointer,
@@ -38,7 +37,6 @@ import {
releasePointer,
} from '../data/inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
import { sensorPickPosition } from '../input/sensorPick.js';
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
import {
DRAW_SHAPES,
@@ -55,9 +53,20 @@ import {
import { DRAW_COLORS, DRAW_COLOR_CSS, presentDrawMarks } from './drawMarks.js';
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
import { fromDegrees } from '../geo/index.js';
import { cssColor } from '../render/color.js';
import { drawOf, findFrame, rendererOf } from '../render/rendererOf.js';
/** The id this tool claims the pointer under. */
const DRAW_POINTER_OWNER = 'draw';
const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview';
/** Each tool's preview sets get their own ids. */
let previewSerial = 0;
/**
* Preview sets drawn on each viewer by its live tools, so a tool left
* undestroyed beside its replacement shows up in `diagnostics()`.
*/
const livePreviewSets = new WeakMap();
const countPreviewSets = (viewer, delta) =>
livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta);
const PREVIEW = DRAW_COLOR_CSS;
@@ -69,7 +78,7 @@ const PREVIEW = DRAW_COLOR_CSS;
* through the actions it gives `connect`, which returns their disconnect.
* A row's fly-to is an immediate navigation through `navigation`, like
* Import's, so Cockpit can refuse it and a running orbit or follow lets go.
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
@@ -97,7 +106,6 @@ export function initDrawTool({
// the board, leaving draw mode, teardown. An `annotate()` that resolves after
// one of those must not write its outcome over the newer state.
let generation = 0;
const previewEntities = [];
// Every DOM listener this tool adds (the session's keydown), so teardown is
// one loop rather than a list that can fall out of step with the bindings.
const domListeners = [];
@@ -106,14 +114,26 @@ export function initDrawTool({
domListeners.push([target, type, listener, options]);
};
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
// remove a source that had not been attached yet and leave the attachment to
// land afterwards — a preview data source nobody owns. Chain the removal onto
// the attachment instead of racing it.
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
() => null,
);
// The preview: one dashed rubber band and a dot per vertex, drawn through
// the renderer's draw port. Both sets live as long as the tool.
const draw = drawOf(viewer);
const previewId = `draw-preview:${++previewSerial}`;
const previewLines = draw.lines({ id: `${previewId}:line` });
const previewPoints = draw.points({ id: `${previewId}:vertices` });
countPreviewSets(viewer, 2);
let previewReleased = false;
const releasePreview = () => {
if (previewReleased) return;
previewReleased = true;
countPreviewSets(viewer, -2);
previewLines.dispose();
previewPoints.dispose();
};
/** The canvas the renderer draws in (the viewer's own when none is bound). */
const canvasOf = () => rendererOf(viewer)?.canvas ?? viewer.canvas;
const requestRender = () => findFrame(viewer)?.requestRender('draw-preview');
// Teardown finishes synchronously; `whenSettled()` keeps its promise.
const attaching = Promise.resolve();
const present = () =>
publish({
@@ -137,70 +157,66 @@ export function initDrawTool({
// ---- preview ---------------------------------------------------------
const vertexPositions = () =>
session.vertices.map((v) =>
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
);
const previewLine = dataSource.entities.add({
show: false,
polyline: {
positions: new Cesium.CallbackProperty(() => {
if (!session) return [];
const pts = vertexPositions();
if (cursor && session.shape !== 'pin') pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
return pts;
}, false),
width: 3,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
dashLength: 16,
}),
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
dashLength: 16,
}),
clampToGround: false,
},
});
const syncPreview = () => {
session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0));
/** The rubber band, from the vertices to the pointer (and closed for an area). */
const syncPreviewLine = () => {
if (destroyed) return;
previewEntities.forEach((e) => dataSource.entities.remove(e));
previewEntities.length = 0;
if (!session) {
previewLine.show = false;
setHint(() => drawHint(null));
viewer.scene.requestRender();
if (!session || session.shape === 'pin') {
previewLines.clear();
return;
}
const stroke = Cesium.Color.fromCssColorString(
PREVIEW[color] || PREVIEW.primary,
);
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
color: stroke.withAlpha(0.9),
dashLength: 16,
});
previewLine.show = session.shape !== 'pin';
for (const v of session.vertices) {
previewEntities.push(
dataSource.entities.add({
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
point: {
pixelSize: 8,
color: stroke,
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}),
);
const pts = vertexPositions();
if (cursor) pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
if (pts.length < 2) {
previewLines.clear();
return;
}
previewLines.upsert([
{
id: 'band',
positions: pts,
widthPx: 3,
// Along the ellipsoid between vertices, as the entity polyline was.
mode: 'geodesic',
style: {
kind: 'dash',
color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9),
length: 16,
},
depthFailColor: withAlpha(cssColor(PREVIEW.primary), 0.35),
},
]);
};
const syncPreview = () => {
if (destroyed) return;
if (!session) {
previewPoints.clear();
previewLines.clear();
setHint(() => drawHint(null));
requestRender();
return;
}
const stroke = cssColor(PREVIEW[color] || PREVIEW.primary);
previewPoints.set(
session.vertices.map((v, index) => ({
id: String(index),
pos: { lon: v.lon, lat: v.lat, height: v.height || 0 },
pixelSize: 8,
color: stroke,
outlineColor: [0, 0, 0, 0.6],
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
})),
);
syncPreviewLine();
setHint(() => drawHint(session));
viewer.scene.requestRender();
requestRender();
};
// ---- vertices from clicks --------------------------------------------
const worldAt = (position) => {
const canvas = viewer.scene.canvas;
const canvas = canvasOf();
const w = canvas.clientWidth || canvas.width || 1;
const h = canvas.clientHeight || canvas.height || 1;
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
@@ -230,11 +246,10 @@ export function initDrawTool({
if (!session || session.shape === 'pin' || destroyed) return;
// The click's own position is sensor-corrected; the rubber band must
// follow the same point the click would place.
const p = worldAt(sensorPickPosition(viewer.scene, event.endPosition));
cursor = p
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0)
: null;
viewer.scene.requestRender();
const p = worldAt(event.pickPosition ?? event.endPosition);
cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null;
syncPreviewLine();
requestRender();
};
// ---- finish / cancel -------------------------------------------------
@@ -314,9 +329,7 @@ export function initDrawTool({
t.closest('button, a, select, [role="button"], [role="radio"]')
)
return false;
return (
t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS'
);
return t === document.body || t === canvasOf() || t.tagName === 'CANVAS';
};
const onKey = (event) => {
if (!active || destroyed || typingElsewhere(event)) return;
@@ -506,8 +519,11 @@ export function initDrawTool({
destroyed,
sceneHandler: Boolean(unbindScene),
domListeners: domListeners.length,
previewDataSources: countPreviewDataSources(viewer),
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
// Every live tool's on this viewer: 2 while one tool lives.
previewSets: livePreviewSets.get(viewer) ?? 0,
previewItems: previewReleased
? 0
: previewLines.size() + previewPoints.size(),
pointerOwner: pointerOwner(),
// The viewer's own select and follow, which the input port runs: off
// while a session is open, back on after it closes.
@@ -534,18 +550,7 @@ export function initDrawTool({
for (const [target, type, listener, options] of domListeners.splice(0)) {
target.removeEventListener(type, listener, options);
}
previewEntities.length = 0;
dataSource.entities.removeAll();
// Wait for the pending add() before removing: a destroy() in the same
// tick as init would otherwise remove nothing and let the attachment land
// behind it.
attaching = attaching.then(() => {
try {
viewer.dataSources.remove(dataSource, true);
} catch {
/* viewer already disposed — nothing to detach from */
}
});
releasePreview();
document.body.classList.remove('gev-drawing');
hint = '';
present();
@@ -557,13 +562,7 @@ export function initDrawTool({
return api;
}
/** How many draw previews are attached — more than one means a leaked tool. */
function countPreviewDataSources(viewer) {
const sources = viewer?.dataSources;
if (!sources) return 0;
let found = 0;
for (let index = 0; index < sources.length; index += 1) {
if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1;
}
return found;
/** `color` at `alpha`. */
function withAlpha(color, alpha) {
return [color[0], color[1], color[2], alpha];
}
+55 -43
View File
@@ -14,6 +14,7 @@ import {
resetPointerOwnership,
} from '../data/inputOwnership.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
/* ── DOM doubles ───────────────────────────────────────────────────────── */
@@ -144,33 +145,9 @@ function fakeViewer() {
setInputAction: (action, type) => actions.set(type, action),
removeInputAction: (type) => actions.delete(type),
};
const attached = [];
const pendingAdds = [];
const dataSources = {
get length() {
return attached.length;
},
get: (index) => attached[index],
add(source) {
// Cesium resolves this on a later tick — the whole point of finding 7.
const promise = Promise.resolve().then(() => {
attached.push(source);
return source;
});
pendingAdds.push(promise);
return promise;
},
remove(source) {
const at = attached.indexOf(source);
if (at >= 0) attached.splice(at, 1);
return at >= 0;
},
};
return {
scene: { canvas, requestRender() {} },
screenSpaceEventHandler: stockHandler,
dataSources,
_attached: attached,
_actions: actions,
};
}
@@ -231,6 +208,10 @@ function harness({ navigation = null, beforeInput = () => {} } = {}) {
// The viewer's own actions are bound before its input port takes them.
beforeInput(viewer);
const input = fakeInput(viewer);
// The renderer the tool draws its preview with, drawing in the viewer's canvas.
const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, {
canvas: viewer.scene.canvas,
});
const annotations = fakeAnnotations();
const previousDocument = globalThis.document;
const previousWindow = globalThis.window;
@@ -253,6 +234,7 @@ function harness({ navigation = null, beforeInput = () => {} } = {}) {
tool,
shown,
viewer,
draw,
annotations,
byId,
documentDouble,
@@ -263,6 +245,7 @@ function harness({ navigation = null, beforeInput = () => {} } = {}) {
input,
restore() {
input.destroy();
unbindDraw();
resetPointerOwnership();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
@@ -416,15 +399,16 @@ test('the live preview hangs at the height the click landed on', async () => {
h.tool.addVertex(-97.75, 30.26, 187.5);
h.tool.addVertex(-97.74, 30.26, 212.25);
await h.tool.whenSettled();
const source = h.viewer._attached[0] ?? null;
assert.ok(source, 'the preview data source is attached');
const points = source.entities.values.filter((entity) => entity.point);
assert.equal(points.length, 2, 'one preview dot per vertex');
const heights = points.map((entity) => {
const position = entity.position.getValue(Cesium.JulianDate.now());
return Cesium.Cartographic.fromCartesian(position).height;
});
const dots = [...h.draw.sets.values()].find(
(set) => !set.disposed && set.kind === 'points',
);
assert.equal(dots.items.size, 2, 'one preview dot per vertex');
const heights = [...dots.items.values()].map((item) => item.pos.height);
const band = [...h.draw.sets.values()]
.find((set) => !set.disposed && set.kind === 'lines')
.items.get('band');
assert.equal(band.positions.length, 2, 'the rubber band joins the vertices');
assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped');
assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`);
assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`);
@@ -443,18 +427,46 @@ test('the live preview hangs at the height the click landed on', async () => {
}
});
test('destroy in the same tick as init still removes the preview data source', async () => {
test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => {
const h = harness();
try {
// Nothing has been attached yet — dataSources.add() resolves later.
assert.equal(h.viewer._attached.length, 0, 'the add is still pending');
await h.tool.destroy();
await Promise.resolve();
assert.equal(
h.viewer._attached.length,
0,
'the preview must not be left attached behind the teardown',
const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
const band = () => sets().find((set) => set.kind === 'lines').items.get('band');
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
assert.equal(band(), undefined, 'one vertex and no pointer draw no band');
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
assert.equal(band().positions.length, 4, 'an area of three closes back to its first vertex');
assert.deepEqual(band().positions[3], band().positions[0]);
h.tool.setColor('red');
assert.deepEqual(band().style.color, [1, 107 / 255, 107 / 255, 0.9], 'the band takes the colour');
assert.deepEqual(
band().depthFailColor,
[139 / 255, 233 / 255, 1, 0.35],
'behind the surface it stays the primary colour, as before',
);
assert.equal(band().style.kind, 'dash');
assert.equal(band().style.length, 16);
assert.equal(band().widthPx, 3);
h.tool.setShape('pin');
assert.equal(band(), undefined, 'a pin has no rubber band');
} finally {
h.restore();
}
});
test('destroy in the same tick as init disposes the preview sets', async () => {
const h = harness();
try {
const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
assert.equal(live().length, 2, 'the rubber band and the vertex dots');
await h.tool.destroy();
assert.equal(live().length, 0, 'nothing is left drawn behind the teardown');
assert.equal(h.tool.diagnostics().previewSets, 0, 'no live tool draws a preview');
} finally {
h.restore();
}
@@ -486,7 +498,7 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
stockClick,
'the viewer got its selecting click back',
);
assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached');
assert.equal(after.previewSets, 0, 'the preview sets are disposed');
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
// Idempotent: a second destroy is harmless.
+11 -2
View File
@@ -123,7 +123,8 @@ const dispatchers = new WeakMap();
* Ambient click subscription. Returns its unsubscribe.
* @property {(type: 'down'|'move'|'up'|'click'|'dblclick', fn: Function, options?: {lease?: object|(() => object|null)}) => () => void} onPointer
* Raw pointer subscription: `click` gets the {@link ClickEvent}, the others
* Cesium's event. With a lease, runs only while that lease is current;
* Cesium's event; `move`'s also carries `pickPosition`, its `endPosition`
* corrected for sensor styles as a click's `position` is. With a lease, runs only while that lease is current;
* without one, only while the pointer is free (`move` and `up` always run).
* @property {(reason: string) => () => void} suspendCamera Hold camera input
* off; returns this hold's release.
@@ -227,9 +228,17 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
}),
port.on('move', (ev) => {
if (!unmodified(ev)) return;
const endPosition = cartesian(ev.endPosition ?? ev.position);
let pickPosition;
run(pointerSubscribers.move, true, {
startPosition: cartesian(ev.position),
endPosition: cartesian(ev.endPosition ?? ev.position),
endPosition,
// Where the pointer lands in the pick buffer, as a click's
// `position` is (corrected for sensor styles); made on first read.
get pickPosition() {
pickPosition ??= sensorPickPosition(viewer.scene, endPosition);
return pickPosition;
},
});
}),
port.on('up', (ev) => {
+22
View File
@@ -426,6 +426,28 @@ test('sensor styles move the pick to where the picture came from', () => {
assert.deepEqual([plain.x, plain.y], [300, 50]);
});
test('a move carries its pick-buffer position, sensor-corrected as a click is', (t) => {
const h = harness();
t.after(() => h.input.destroy());
Object.assign(h.viewer.scene.canvas, {
clientWidth: 400,
clientHeight: 200,
width: 400,
height: 200,
});
const stage = { enabled: true, uniforms: { intensity: 1, pixelation: 4 } };
registerStyleStages(h.viewer.scene, { surveillance: stage });
const seen = [];
h.input.onPointer('move', (event) => seen.push(event));
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 300, y: 50 } });
const expected = sensorPickPosition(h.viewer.scene, { x: 300, y: 50 });
assert.deepEqual(
[seen[0].pickPosition.x, seen[0].pickPosition.y],
[expected.x, expected.y],
);
assert.deepEqual([seen[0].endPosition.x, seen[0].endPosition.y], [300, 50]);
});
test('the dispatcher is the package input export', async () => {
const exported = await import('gods-eye-view/input');
assert.equal(exported.inputFor, inputFor);
-1
View File
@@ -1,6 +1,5 @@
[
"dev/conformance/main.js",
"src/annotations/drawTool.js",
"src/annotations/worldAnnotationRenderer.js",
"src/app/embed.js",
"src/app/scene.js",