mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Share the camera events and the stub's drawn positions with other cameras
The geo export now has geodesicAt and horizonFrom. The camera events module is a public export (./render/camera/events) and holds move detection and the command hooks as well as the per-listener changed measure; the stub camera uses them. Each onCommand registration is now its own, so removing one twin leaves the other. The stub's testing.drawnPosition says where it draws an item, so a camera that is not the stub's can follow drawn items.
This commit is contained in:
1 parent
afd8dba67b
commit
ef616b7905
9 files changed
+320
-70
No files matched your search
+111
-8
@@ -1,15 +1,22 @@
|
||||
/**
|
||||
* @module render/camera/events
|
||||
* @description The camera port's events, shared by the Cesium port and the stub: the
|
||||
* listener lists, delivery (a throwing listener is reported, the rest still
|
||||
* run), and the contract's per-listener `changed` measure. A renderer calls
|
||||
* `stepChanged()` once per frame and `emit()` for the events its engine
|
||||
* @description The camera port's events, shared by the renderer, the stub and
|
||||
* camera controllers (the package's `./render/camera/events`
|
||||
* export):
|
||||
* the listener lists, delivery (a throwing listener is reported, the rest
|
||||
* still run), the contract's per-listener `changed` measure, move detection
|
||||
* (`moveStart` on a change, `moveEnd` 500 ms after the last one, never
|
||||
* while following) and the command hooks (`onCommand`). A renderer calls
|
||||
* `stepChanged()` and `stepMoveDetection()` once per frame, `command()`
|
||||
* before each camera command, and `emit()` for the events its engine
|
||||
* raises.
|
||||
*/
|
||||
|
||||
import { acosClamped, distance, dot } from '../../geo/index.js';
|
||||
|
||||
const TWO_PI = Math.PI * 2;
|
||||
/** `moveEnd` waits this long after the last change, ms, as the reference does. */
|
||||
export const MOVE_END_WAIT_MS = 500;
|
||||
|
||||
/** The contract's camera events. */
|
||||
export const CAMERA_EVENTS = Object.freeze([
|
||||
@@ -26,15 +33,43 @@ const angleDelta = (a, b) => {
|
||||
return (d > Math.PI ? TWO_PI - d : d) / Math.PI;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether two world views are the same: the same position, and directions
|
||||
* and ups whose dot products are each one's own.
|
||||
*/
|
||||
function sameView(a, b) {
|
||||
return (
|
||||
a &&
|
||||
b &&
|
||||
distance(a.position, b.position) === 0 &&
|
||||
dot(a.direction, b.direction) === dot(a.direction, a.direction) &&
|
||||
dot(a.up, b.up) === dot(a.up, a.up)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{pose: () => import('../contract/camera').CameraPose,
|
||||
* world?: () => {position: object, direction: object, up: object},
|
||||
* following?: () => boolean,
|
||||
* report: (error: unknown) => void, thresholds?: boolean}} options `pose`
|
||||
* is read only while a `changed` listener is registered; `thresholds`
|
||||
* is read only while a `changed` listener is registered; `world` (the
|
||||
* eye in world coordinates; `pose()` when omitted) and `following` (no
|
||||
* `moveEnd` while true) are read by `stepMoveDetection`; `thresholds`
|
||||
* false (a renderer without `cameraChangeThreshold`) ignores a listener's
|
||||
* own threshold, so every listener fires at 0.5.
|
||||
*/
|
||||
export function createCameraEvents({ pose, report, thresholds = true }) {
|
||||
export function createCameraEvents({
|
||||
pose,
|
||||
world = pose,
|
||||
following = () => false,
|
||||
report,
|
||||
thresholds = true,
|
||||
}) {
|
||||
const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []]));
|
||||
const commandHooks = [];
|
||||
let lastView = null;
|
||||
let moving = false;
|
||||
let lastMovedAt = 0;
|
||||
|
||||
function deliver(entry) {
|
||||
if (!entry.live) return;
|
||||
@@ -109,13 +144,81 @@ export function createCameraEvents({ pose, report, thresholds = true }) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every listener, including those of an event under way. */
|
||||
/**
|
||||
* Once a frame, after `preUpdate`: `moveStart` when the eye changed since
|
||||
* the last frame, `moveEnd` once it has not for 500 ms (`now`, ms) and
|
||||
* nothing is followed.
|
||||
* @param {number} now
|
||||
*/
|
||||
function stepMoveDetection(now) {
|
||||
const v = world();
|
||||
const current = { position: v.position, direction: v.direction, up: v.up };
|
||||
const changed = lastView && !sameView(lastView, current);
|
||||
lastView = current;
|
||||
if (changed) {
|
||||
lastMovedAt = now;
|
||||
if (!moving) {
|
||||
moving = true;
|
||||
emit('moveStart');
|
||||
}
|
||||
} else if (
|
||||
moving &&
|
||||
!following() &&
|
||||
now - lastMovedAt >= MOVE_END_WAIT_MS
|
||||
) {
|
||||
moving = false;
|
||||
emit('moveEnd');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell every command hook about a command before it runs.
|
||||
* @param {import('../contract/camera').CameraCommand['kind']} kind
|
||||
*/
|
||||
function command(kind) {
|
||||
for (const entry of commandHooks.slice()) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb({ kind });
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The contract's `onCommand`. Each registration is its own: its `Off`
|
||||
* removes only it, once.
|
||||
* @param {(command: import('../contract/camera').CameraCommand) => void} cb
|
||||
* @returns {() => void}
|
||||
*/
|
||||
function onCommand(cb) {
|
||||
const entry = { cb, live: true };
|
||||
commandHooks.push(entry);
|
||||
return () => {
|
||||
entry.live = false;
|
||||
const i = commandHooks.indexOf(entry);
|
||||
if (i >= 0) commandHooks.splice(i, 1);
|
||||
};
|
||||
}
|
||||
|
||||
/** Drop every listener and hook, including those of an event under way. */
|
||||
function clear() {
|
||||
for (const list of Object.values(listeners)) {
|
||||
for (const entry of list) entry.live = false;
|
||||
list.length = 0;
|
||||
}
|
||||
for (const entry of commandHooks) entry.live = false;
|
||||
commandHooks.length = 0;
|
||||
}
|
||||
|
||||
return { on, emit, stepChanged, clear };
|
||||
return {
|
||||
on,
|
||||
emit,
|
||||
stepChanged,
|
||||
stepMoveDetection,
|
||||
command,
|
||||
onCommand,
|
||||
clear,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createCameraEvents, MOVE_END_WAIT_MS } from './events.js';
|
||||
import { geodesicAt, horizonFrom } from '../../geo/index.js';
|
||||
|
||||
const view = (x) => ({
|
||||
position: { x, y: 0, z: 0 },
|
||||
direction: { x: -1, y: 0, z: 0 },
|
||||
up: { x: 0, y: 0, z: 1 },
|
||||
});
|
||||
|
||||
test('moveStart on a change, moveEnd once nothing moved for 500 ms and nothing is followed', () => {
|
||||
let eye = view(7e6);
|
||||
let following = false;
|
||||
const seen = [];
|
||||
const events = createCameraEvents({
|
||||
pose: () => eye,
|
||||
world: () => eye,
|
||||
following: () => following,
|
||||
report: (error) => assert.fail(error),
|
||||
});
|
||||
events.on('moveStart', () => seen.push('start'));
|
||||
events.on('moveEnd', () => seen.push('end'));
|
||||
events.stepMoveDetection(0);
|
||||
eye = view(7e6 + 1);
|
||||
events.stepMoveDetection(16);
|
||||
assert.deepEqual(seen, ['start']);
|
||||
events.stepMoveDetection(16 + MOVE_END_WAIT_MS - 1);
|
||||
assert.deepEqual(seen, ['start']);
|
||||
// A later change starts the wait again, and moveStart is not repeated.
|
||||
eye = view(7e6 + 2);
|
||||
events.stepMoveDetection(400);
|
||||
events.stepMoveDetection(16 + MOVE_END_WAIT_MS);
|
||||
assert.deepEqual(seen, ['start']);
|
||||
events.stepMoveDetection(400 + MOVE_END_WAIT_MS - 1);
|
||||
assert.deepEqual(seen, ['start']);
|
||||
following = true;
|
||||
events.stepMoveDetection(400 + MOVE_END_WAIT_MS);
|
||||
assert.deepEqual(seen, ['start'], 'never while following');
|
||||
following = false;
|
||||
events.stepMoveDetection(401 + MOVE_END_WAIT_MS);
|
||||
assert.deepEqual(seen, ['start', 'end']);
|
||||
});
|
||||
|
||||
test('command hooks run before each command, each registration on its own', () => {
|
||||
const events = createCameraEvents({ pose: () => view(1), report() {} });
|
||||
const seen = [];
|
||||
const hook = (c) => seen.push(c.kind);
|
||||
const offFirst = events.onCommand(hook);
|
||||
events.onCommand(hook);
|
||||
events.command('setView');
|
||||
assert.deepEqual(seen, ['setView', 'setView']);
|
||||
offFirst();
|
||||
offFirst();
|
||||
events.command('flyTo');
|
||||
assert.deepEqual(seen, ['setView', 'setView', 'flyTo'], 'one twin is left');
|
||||
// A hook removed by an earlier one in the same delivery does not run.
|
||||
const order = [];
|
||||
const removing = createCameraEvents({ pose: () => view(1), report() {} });
|
||||
let offSecond = null;
|
||||
removing.onCommand(() => {
|
||||
order.push('first');
|
||||
offSecond();
|
||||
});
|
||||
offSecond = removing.onCommand(() => order.push('second'));
|
||||
removing.command('setView');
|
||||
removing.command('setView');
|
||||
assert.deepEqual(order, ['first', 'first']);
|
||||
const reported = [];
|
||||
const throwing = createCameraEvents({
|
||||
pose: () => view(1),
|
||||
report: (error) => reported.push(error.message),
|
||||
});
|
||||
throwing.onCommand(() => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
throwing.onCommand(() => seen.push('after'));
|
||||
throwing.command('flyTo');
|
||||
assert.deepEqual(reported, ['boom']);
|
||||
assert.equal(seen.at(-1), 'after');
|
||||
});
|
||||
|
||||
test('the geo export has the geodesic point and the horizon test', () => {
|
||||
const half = geodesicAt(0, 0, Math.PI / 2, 0, 0.5);
|
||||
assert.ok(Math.abs(half.lon - Math.PI / 4) < 1e-12);
|
||||
assert.ok(Math.abs(half.lat) < 1e-12);
|
||||
const horizon = horizonFrom({ x: 7e6, y: 0, z: 0 });
|
||||
assert.equal(horizon.isPointVisible({ x: 6378137, y: 0, z: 0 }), true);
|
||||
assert.equal(horizon.isPointVisible({ x: -6378137, y: 0, z: 0 }), false);
|
||||
});
|
||||
+14
-53
@@ -47,7 +47,6 @@ import { createCameraEvents } from '../camera/events.js';
|
||||
import { geodesicAt } from '../../geo/geodesic.js';
|
||||
|
||||
const DEFAULT_FOV = Math.PI / 3;
|
||||
const MOVE_END_WAIT_MS = 500;
|
||||
const MINIMUM_ZOOM = 100;
|
||||
const DEFAULT_SPHERE_OFFSET = Object.freeze({
|
||||
heading: 0,
|
||||
@@ -98,17 +97,23 @@ export function createStubCamera({
|
||||
const near = 1;
|
||||
const far = 5e8;
|
||||
|
||||
const events = createCameraEvents({ pose, report, thresholds });
|
||||
const { emit, on, stepChanged } = events;
|
||||
const commandHooks = [];
|
||||
const events = createCameraEvents({
|
||||
pose,
|
||||
world: () => ({
|
||||
position: positionWC(),
|
||||
direction: directionWC(),
|
||||
up: upWC(),
|
||||
}),
|
||||
following: () => Boolean(followed),
|
||||
report,
|
||||
thresholds,
|
||||
});
|
||||
const { emit, on, stepChanged, command, onCommand } = events;
|
||||
const holds = new Map();
|
||||
let holdSeq = 0;
|
||||
let flight = null;
|
||||
let followed = null;
|
||||
let followFramed = false;
|
||||
let lastPose = null;
|
||||
let moving = false;
|
||||
let lastMovedAt = 0;
|
||||
|
||||
let coast = Object.freeze({ drag: 0.4, zoom: 0.2 });
|
||||
const controls = {
|
||||
@@ -202,17 +207,6 @@ export function createStubCamera({
|
||||
};
|
||||
}
|
||||
|
||||
function command(kind) {
|
||||
for (const hook of commandHooks.slice()) {
|
||||
if (!commandHooks.includes(hook)) continue;
|
||||
try {
|
||||
hook({ kind });
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Place the eye at `destination` (world) with `orientation` in its east-north-up frame. */
|
||||
function placeAt(destination, hpr) {
|
||||
const kept = frame;
|
||||
@@ -727,35 +721,8 @@ export function createStubCamera({
|
||||
|
||||
// --- Events ----------------------------------------------------------------
|
||||
|
||||
function sameView(a, b) {
|
||||
return (
|
||||
a &&
|
||||
b &&
|
||||
distance(a.position, b.position) === 0 &&
|
||||
dot(a.direction, b.direction) === dot(a.direction, a.direction) &&
|
||||
dot(a.up, b.up) === dot(a.up, a.up)
|
||||
);
|
||||
}
|
||||
|
||||
function stepMoveDetection() {
|
||||
const current = {
|
||||
position: positionWC(),
|
||||
direction: directionWC(),
|
||||
up: upWC(),
|
||||
};
|
||||
const changed = lastPose && !sameView(lastPose, current);
|
||||
lastPose = current;
|
||||
const t = now();
|
||||
if (changed) {
|
||||
lastMovedAt = t;
|
||||
if (!moving) {
|
||||
moving = true;
|
||||
emit('moveStart');
|
||||
}
|
||||
} else if (moving && !followed && t - lastMovedAt >= MOVE_END_WAIT_MS) {
|
||||
moving = false;
|
||||
emit('moveEnd');
|
||||
}
|
||||
events.stepMoveDetection(now());
|
||||
}
|
||||
|
||||
function matrices() {
|
||||
@@ -844,13 +811,7 @@ export function createStubCamera({
|
||||
followOffset,
|
||||
controls,
|
||||
on,
|
||||
onCommand(cb) {
|
||||
commandHooks.push(cb);
|
||||
return () => {
|
||||
const i = commandHooks.indexOf(cb);
|
||||
if (i >= 0) commandHooks.splice(i, 1);
|
||||
};
|
||||
},
|
||||
onCommand,
|
||||
matrices,
|
||||
};
|
||||
|
||||
|
||||
@@ -1600,6 +1600,13 @@ export function createStubRenderer(options = {}) {
|
||||
canvas.width = viewport.width;
|
||||
canvas.height = viewport.height;
|
||||
},
|
||||
/**
|
||||
* Where a drawn item is drawn now (or `aheadMs` from now), ECEF, or
|
||||
* null: what the stub's own camera follows for a target's `item`, for
|
||||
* a camera of someone else's driving the stub (the `camera.followItem`
|
||||
* conformance check).
|
||||
*/
|
||||
drawnPosition: (ref, aheadMs = 0) => drawnPosition(ref, aheadMs),
|
||||
/** What a set holds. */
|
||||
setRecord: (id) => sets.get(id) ?? null,
|
||||
sets: () => [...sets.keys()],
|
||||
@@ -1624,6 +1631,7 @@ export function createStubRenderer(options = {}) {
|
||||
* @property {(point: object, height: number) => void} cacheHeight
|
||||
* @property {(kind: string, value: boolean) => void} setSettled
|
||||
* @property {(size: {width?: number, height?: number}) => void} setViewport
|
||||
* @property {(ref: {set: string, id: string|number}, aheadMs?: number) => {x: number, y: number, z: number}|null} drawnPosition
|
||||
* @property {(id: string) => object|null} setRecord
|
||||
* @property {() => string[]} sets
|
||||
* @property {Array<{port: string, member: string, args: unknown[]}>} calls
|
||||
|
||||
@@ -130,3 +130,56 @@ test('a draped rectangle across the antimeridian picks on both sides of it, turn
|
||||
assert.ok(!picked(179.5, 0), 'and narrows it');
|
||||
r.destroy();
|
||||
});
|
||||
|
||||
test('the stub says where it draws an item, for a camera that is not its own', () => {
|
||||
const r = createStubRenderer();
|
||||
const t0 = r.frame.time();
|
||||
const from = toEcef({ lon: -97.74, lat: 30.27, height: 1000 });
|
||||
const to = toEcef({ lon: -97.7, lat: 30.27, height: 1000 });
|
||||
const set = r.draw.icons({ id: 'drawn', motionClock: { kind: 'scene' } });
|
||||
set.set([
|
||||
{
|
||||
id: 'm',
|
||||
pos: from,
|
||||
image: 'data:,',
|
||||
size: [16, 16],
|
||||
motion: { kind: 'lerp', from, to, t0, t1: t0 + 60000 },
|
||||
},
|
||||
]);
|
||||
const at = (p) => [p.x, p.y, p.z];
|
||||
assert.deepEqual(
|
||||
at(r.testing.drawnPosition({ set: 'drawn', id: 'm' })),
|
||||
at(from),
|
||||
);
|
||||
r.frame.setTime(t0 + 30000);
|
||||
const mid = r.testing.drawnPosition({ set: 'drawn', id: 'm' });
|
||||
for (const k of ['x', 'y', 'z'])
|
||||
assert.ok(Math.abs(mid[k] - (from[k] + to[k]) / 2) < 1e-6, k);
|
||||
const ahead = r.testing.drawnPosition({ set: 'drawn', id: 'm' }, 30000);
|
||||
for (const k of ['x', 'y', 'z'])
|
||||
assert.ok(Math.abs(ahead[k] - to[k]) < 1e-6, k);
|
||||
assert.equal(r.testing.drawnPosition({ set: 'drawn', id: 'gone' }), null);
|
||||
assert.equal(r.testing.drawnPosition({ set: 'nothing', id: 'm' }), null);
|
||||
r.destroy();
|
||||
});
|
||||
|
||||
test('the stub camera ends no move while it follows', () => {
|
||||
const r = createStubRenderer();
|
||||
const seen = [];
|
||||
r.camera.on('moveStart', () => seen.push('start'));
|
||||
r.camera.on('moveEnd', () => seen.push('end'));
|
||||
r.testing.tick();
|
||||
const target = toEcef({ lon: -97.74, lat: 30.27, height: 0 });
|
||||
r.camera.follow({
|
||||
key: 'still',
|
||||
position: () => target,
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -500, z: 300 },
|
||||
});
|
||||
r.testing.advance(2000);
|
||||
assert.deepEqual(seen, ['start'], 'moveEnd waits for the follow to end');
|
||||
r.camera.follow(null);
|
||||
r.testing.advance(1000);
|
||||
assert.deepEqual(seen, ['start', 'end']);
|
||||
r.destroy();
|
||||
});
|
||||
Reference in new issue
Block a user