feat(time): the app clock on the engine

src/time/clock.js is the app's own time in ms since the epoch: by default
Date.now exactly (read at each call), with freeze/offset/rate/reset for QA
and tests, and one frame time latched per engine frame (beginFrame). The
contract gains engine.clock { now, frameTime, ticked }, in the fake engine
(a controllable wall clock, fake.advanceTime, fake.appClock), the contract
suite (one frame time for every listener of a frame, latched before
preUpdate, never decreasing), Cesium and Navara.

Cesium latches on the viewer clock's onTick, which CesiumWidget runs right
before scene.render, so scene listeners the app added before the engine
existed read the same frame time; the subscription appears on first use
and destroy removes it. The viewer clock itself is untouched: in the app
it never animates (shouldAnimate false, multiplier 1, its time frozen at
boot), and its time still drives Cesium's lighting as before. Navara
latches in the engine's handler of the view's preUpdate, and the look
reads the engine clock's frame time for the sun, so the app clock is the
one time source on Navara too.

src/time is a portable root in check-import-directions: no engine
packages, no browser globals.
This commit is contained in:
German Khokhlov committed 2026-10-16 15:01:36 +04:00
1 parent 27e28373d0
commit f1a2df5cfe
20 files changed
+771 -13

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
// The engine clock on a Navara view: the app clock (src/time/clock.js), with
// one frame time latched per turn of the view's loop. The engine calls
// beginFrame from its handler of the view's preUpdate, which Navara emits
// first on every turn of its loop (drawn or not), before raising the
// contract's preUpdate; every listener of the frame then reads that time.
// The look (look.js) reads the same clock for the sun.
import { createEngineEvent } from '../contract.js';
import { appClock as pageClock } from '../../time/clock.js';
/**
* @param {{ appClock?: import('../../time/clock.js').AppClock }} [options]
* `appClock` defaults to the page's app clock.
* @returns {{ clock: import('../contract.js').GlobeClock, beginFrame: () => void }}
*/
export function createNavaraClock({ appClock = pageClock } = {}) {
const ticked = createEngineEvent();
return {
clock: {
now: () => appClock.now(),
frameTime: () => appClock.frameTime(),
ticked,
},
beginFrame() {
ticked.raiseValue(appClock.beginFrame());
},
};
}
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { isEngineEvent } from '../contract.js';
import { createAppClock } from '../../time/clock.js';
import { createNavaraClock } from './clock.js';
test('beginFrame latches the app clock and raises ticked with the frame time', () => {
let wall = 10_000;
const appClock = createAppClock({ now: () => wall });
const { clock, beginFrame } = createNavaraClock({ appClock });
assert.ok(isEngineEvent(clock.ticked));
const seen = [];
clock.ticked.addEventListener((time) => seen.push(time));
assert.equal(clock.frameTime(), 10_000);
wall = 10_016;
beginFrame();
wall = 10_020;
assert.deepEqual(seen, [10_016]);
assert.equal(clock.frameTime(), 10_016);
assert.equal(clock.now(), 10_020);
});
+19 -4
View File
@@ -14,6 +14,7 @@ import {
} from '../contract.js';
import { cesiumFovy } from './cameraMath.js';
import { createCameraModel } from './cameraModel.js';
import { createNavaraClock } from './clock.js';
import { createNavaraCredits } from './credits.js';
import { createNavaraInput } from './input.js';
import { createNavaraMaps } from './maps.js';
@@ -68,16 +69,25 @@ function rayRaisedEllipsoid({ origin, direction }, height) {
* container?: HTMLElement,
* fetch?: typeof fetch,
* clock?: object,
* appClock?: import('../../time/clock.js').AppClock,
* sharpen?: { set: (state: { enabled: boolean, amount: number }) => void, destroy: () => void },
* }} options `hooks` are internals.js; `container` defaults to the
* canvas's parent; `sharpen` draws render.setSharpen (sharpen.js; without
* it the engine only keeps the state) and the engine destroys it; `fetch`
* and `clock` are test seams.
* it the engine only keeps the state) and the engine destroys it;
* `appClock` (the engine clock's time) defaults to the page's app clock;
* `fetch` and `clock` (the camera model's timers) are test seams.
* @returns {import('../contract.js').GlobeEngine}
*/
export function createNavaraEngine(
view,
{ hooks, container, fetch, clock, sharpen: sharpenPort = null } = {},
{
hooks,
container,
fetch,
clock,
appClock,
sharpen: sharpenPort = null,
} = {},
) {
if (!view?.camera?.raw)
throw new TypeError('createNavaraEngine needs a view');
@@ -112,10 +122,14 @@ export function createNavaraEngine(
preRender: createEngineEvent(),
postRender: createEngineEvent(),
};
const engineClock = createNavaraClock(appClock ? { appClock } : {});
// Defined below, with the surface and input it needs.
let groundFloor = null;
const handlers = {
preUpdate: (time) => frames.preUpdate.raiseEvent(time),
preUpdate: (time) => {
engineClock.beginFrame();
frames.preUpdate.raiseEvent(time);
},
preRender: (time) => {
model.sync();
groundFloor?.update();
@@ -219,6 +233,7 @@ export function createNavaraEngine(
input: input.input,
credits: credits.credits,
maps: maps.maps,
clock: engineClock.clock,
destroy() {
if (destroyed) return;
destroyed = true;
@@ -130,6 +130,37 @@ test("Navara's frame events drive the contract frames in order with timestamps",
]);
});
test('the engine clock is the app clock, latched on the view preUpdate before frames', async () => {
const { createAppClock } = await import('../../time/clock.js');
let wall = 2_000_000;
const appClock = createAppClock({ now: () => wall });
const view = fakeView();
const engine = createNavaraEngine(view, { hooks, appClock });
assert.equal(engine.clock.now(), 2_000_000);
const seen = [];
engine.clock.ticked.addEventListener((time) => seen.push(['ticked', time]));
for (const name of ['preUpdate', 'preRender', 'postRender'])
engine.frames[name].addEventListener(() =>
seen.push([name, engine.clock.frameTime()]),
);
wall += 16;
view.emit('preUpdate', 1);
wall += 4;
view.emit('preRender', 2);
view.emit('postRender', 3);
assert.deepEqual(seen, [
['ticked', 2_000_016],
['preUpdate', 2_000_016],
['preRender', 2_000_016],
['postRender', 2_000_016],
]);
assert.equal(engine.clock.now(), 2_000_020);
engine.destroy();
wall += 16;
view.emit('preUpdate', 4);
assert.equal(seen.length, 4, 'no tick after destroy');
});
test('render requests are forceUpdate and continuous mode is Navara animation', () => {
const { engine, view } = setup();
engine.render.request();
+10 -1
View File
@@ -79,9 +79,12 @@ function groundInView(engine) {
* effects?: 'minimal' | 'photoreal' | 'cinematic',
* search?: string,
* pixelRatio?: number,
* appClock?: import('../../time/clock.js').AppClock,
* }} options `effects` names the look (cinematic by default); `search`, the
* page's query string, picks it from `?look=` instead (the app's way).
* `pixelRatio` only for measurements; the product uses the device's.
* `appClock` (the page's by default) is the engine clock's time and so the
* sun's: the look reads the engine clock's frame time.
* @returns {Promise<{ view: object, engine: import('../contract.js').GlobeEngine, destroy: () => void }>}
*/
export async function createNavaraGlobe({
@@ -89,6 +92,7 @@ export async function createNavaraGlobe({
effects,
search,
pixelRatio,
appClock,
}) {
if (!container) throw new TypeError('createNavaraGlobe needs a container');
const canvas = preservedCanvas(container);
@@ -103,10 +107,15 @@ export async function createNavaraGlobe({
const plan = navaraScenePlan(effects ?? resolveNavaraLook(search), {
mobile: Boolean(view.isMobileOptimized?.()),
});
const look = buildNavaraLook(view, plugin, plan);
// The sun follows the engine clock (one time source for layers and the
// look); the look only runs in preRender, after the engine exists.
const look = buildNavaraLook(view, plugin, plan, () =>
engine.clock.frameTime(),
);
engine = createNavaraEngine(view, {
hooks: navaraHooks(view),
container,
...(appClock ? { appClock } : {}),
sharpen: createNavaraSharpen(view),
});
const camera = engine.camera;
+4 -2
View File
@@ -1,6 +1,8 @@
// Builds a Navara look (viewOptions.js navaraScenePlan) on an initialised
// view and keeps it current while the view renders: the sun follows the wall
// clock as the HUD's SUN elevation does; the cinematic look lights the globe
// view and keeps it current while the view renders: the sun follows `now`
// (the engine clock's frame time in the app: the app clock, which is the wall
// clock the HUD's SUN elevation reads unless QA moves it); the cinematic look
// lights the globe
// from the atmosphere when seen from space, shows its clouds only for low
// views over low ground, brightens the atmosphere (atmosphereLuminance.js)
// and shows its stars only at night or from space. All of it runs only on frames the view draws