From c7bb08bfb458569463b8dc5443ba5801a38143e3 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 11 Nov 2026 16:00:37 -0800 Subject: [PATCH] GPU frame timing on the Cesium renderer, where timer queries exist With EXT_disjoint_timer_query_webgl2 the Cesium renderer lists gpuTiming: while frame signals have listeners, each drawn frame is timed from preRender to postRender and a signal carries gpuMs of the newest timing back (a disjoint one is dropped); queries are reused and let go on dispose. Without the extension it answers 'none', as before. The new conformance check quality.signals.gpuTiming pins both; the stub's timed frames carry 0 ms. --- docs/RENDERER-CONTRACT.md | 8 +++ src/render/cesium/harness.js | 1 + src/render/cesium/ports.js | 6 +- src/render/cesium/quality.js | 91 ++++++++++++++++++++++++-- src/render/cesium/quality.test.mjs | 69 +++++++++++++++++++ src/render/conformance/checks/ports.js | 37 +++++++++++ src/render/stub/index.js | 1 + 7 files changed, 206 insertions(+), 7 deletions(-) diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 23dcb4c95..1c1e06b32 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -126,6 +126,14 @@ optional, so a renderer written before it still conforms: [The application and its renderer](#the-application-and-its-renderer). - `frame.renderNow()` throws when the frame fails to draw. +The Cesium port lists `gpuTiming` where its context has +`EXT_disjoint_timer_query_webgl2`: while anyone listens to frame signals, +each drawn frame is timed on the GPU from `preRender` to `postRender`, and a +signal carries `gpuMs` of the newest frame whose timing has come back (a +frame or more late; a disjoint timing is dropped). Without the extension it +answers `gpuTiming: 'none'` and lists no capability. The check +`quality.signals.gpuTiming` pins both. + The Cesium port lists `modelAtmosphere`: Cesium scatters drawn models through the atmosphere in the same stage as its distance fog, so models take it while `globe.sky`'s `fog` is on. diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 73f8cc2e9..6122032f5 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -103,6 +103,7 @@ export const CESIUM_CHECKS = new Set([ 'query.withoutCapability', 'quality', 'quality.signals', + 'quality.signals.gpuTiming', 'renderer.listeners', 'renderer.readPixels', 'renderer.releaseUnused', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 69a244e18..51d9e6be0 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -22,7 +22,7 @@ import { createCesiumEffects } from './effects.js'; import { renderNow, willDraw } from './frame.js'; import { createCesiumGlobe } from './globe.js'; import { createCesiumQuery, queryCapabilities } from './query.js'; -import { createCesiumQuality } from './quality.js'; +import { createCesiumQuality, gpuTimerOf } from './quality.js'; import { screenModulationSupported } from './screenModulation.js'; import { atEndOfTick, @@ -30,6 +30,7 @@ import { onEngineWorkCompleted, renderPending, trimGlobeTiles, + webglContext, } from './internals.js'; export { listenerList, toCartesian }; @@ -87,6 +88,8 @@ export function cesiumCapabilities(scene, only) { ...(screenModulationSupported() ? ['screenModulation'] : []), ...GLOBE_CAPABILITIES, ...queryCapabilities(scene), + // Frame timing on the GPU, where the context has timer queries. + ...(gpuTimerOf(webglContext(scene)) ? ['gpuTiming'] : []), ]; const allowed = only && new Set(only); return all.filter( @@ -361,6 +364,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { frame, report, tickStarted: () => tickNow, + gl: capabilities.has('gpuTiming') ? webglContext(scene) : null, }); const creditsPart = createCesiumCredits({ diff --git a/src/render/cesium/quality.js b/src/render/cesium/quality.js index c3674c8b2..09afc6c53 100644 --- a/src/render/cesium/quality.js +++ b/src/render/cesium/quality.js @@ -19,12 +19,81 @@ * * Building the port changes nothing in the scene; each setting is applied * when it is first set, and a detail set back to 1 hands each tileset and - * the globe the error it had (or was given since). There is no GPU timing: - * frame signals carry the CPU time of each drawn tick, from the tick's start - * (before any frame listener) to the end of its draw. + * the globe the error it had (or was given since). Frame signals carry the + * CPU time of each drawn tick, from the tick's start (before any frame + * listener) to the end of its draw. Where the context has + * `EXT_disjoint_timer_query_webgl2` (the `gpuTiming` capability), each drawn + * frame is timed on the GPU too, from `preRender` to `postRender`, while + * anyone listens; a frame's GPU time comes back a frame or more later, so a + * signal carries `gpuMs` of the latest frame whose timing has come back (none + * until the first does, and a timing the GPU marks disjoint is dropped). */ import * as Cesium from 'cesium'; import { listenerList } from './common.js'; +import { webglContext } from './internals.js'; + +/** Timer queries kept waiting at most: past it, the oldest is dropped. */ +const MAX_PENDING_QUERIES = 8; + +/** + * The context's GPU timer extension, or null where it has none (WebGL 1, or + * a GPU or browser without timer queries). + * @param {WebGL2RenderingContext|object|undefined} gl + */ +export function gpuTimerOf(gl) { + if (typeof gl?.createQuery !== 'function') return null; + try { + return gl.getExtension?.('EXT_disjoint_timer_query_webgl2') ?? null; + } catch { + return null; + } +} + +/** + * Times frames on the GPU with timer queries: `begin()` before a frame's + * draw, `end()` after it, and `latest()` the milliseconds of the newest frame + * whose timing has come back. + */ +function createGpuTimer(gl, ext) { + const pending = []; + const free = []; + let active = null; + let latestMs; + function poll() { + while (pending.length > 0) { + const query = pending[0]; + if (!gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE)) break; + pending.shift(); + const ns = gl.getQueryParameter(query, gl.QUERY_RESULT); + if (!gl.getParameter(ext.GPU_DISJOINT_EXT)) latestMs = ns / 1e6; + free.push(query); + } + } + return { + begin() { + if (active) this.end(); + active = free.pop() ?? gl.createQuery(); + gl.beginQuery(ext.TIME_ELAPSED_EXT, active); + }, + end() { + if (!active) return; + gl.endQuery(ext.TIME_ELAPSED_EXT); + pending.push(active); + active = null; + if (pending.length > MAX_PENDING_QUERIES) gl.deleteQuery(pending.shift()); + poll(); + }, + latest: () => latestMs, + dispose() { + if (active) gl.endQuery(ext.TIME_ELAPSED_EXT); + for (const query of [active, ...pending, ...free]) + if (query) gl.deleteQuery(query); + active = null; + pending.length = 0; + free.length = 0; + }, + }; +} const MSAA_OPTIONS = Object.freeze([0, 2, 4, 8]); /** Screen-space error at detail 0, as a multiple of the error at detail 1. */ @@ -68,7 +137,9 @@ function tilesetsIn(collection, isTileset, isCollection, out = []) { * isCollection?: (p: object) => boolean, * limits?: {maximumTextureSize: number, maximumSamples: number}, * tickStarted?: () => number, - * }} options `tickStarted` is when the tick under way started, on the + * gl?: object, + * }} options `gl` is the WebGL context GPU timing reads (the scene's by + * default). `tickStarted` is when the tick under way started, on the * `performance.now()` clock; without it the port times from its own * preUpdate listener. Tests pass the predicates and limits; they default * to Cesium's classes and context limits. @@ -84,9 +155,12 @@ export function createCesiumQuality( isCollection = (p) => p instanceof Cesium.PrimitiveCollection, limits = Cesium.ContextLimits, tickStarted = null, + gl = webglContext(widget.scene), }, ) { const scene = widget.scene; + const timerExt = gpuTimerOf(gl); + const gpuTimer = timerExt ? createGpuTimer(gl, timerExt) : null; let disposed = false; const gone = () => disposed || scene.isDestroyed?.() === true; @@ -282,7 +356,7 @@ export function createCesiumQuality( backend: scene.context?.webgl2 ? 'webgl2' : 'webgl1', maxTextureSize: limits.maximumTextureSize, msaaSamples: scene.msaaSupported ? msaaOptions() : [0], - gpuTimer: false, + gpuTimer: Boolean(gpuTimer), }; } @@ -302,14 +376,18 @@ export function createCesiumQuality( ]), scene.preRender.addEventListener(() => { if (signalListeners.size === 0) return; + gpuTimer?.begin(); const pending = frame.diagnostics?.().pendingReasons ?? []; requested = pending.length > 0; mode = scene.requestRenderMode ? 'demand' : 'continuous'; }), scene.postRender.addEventListener(() => { if (signalListeners.size === 0) return; + gpuTimer?.end(); + const gpuMs = gpuTimer?.latest(); signalListeners.fire({ cpuMs: performance.now() - (tickStarted ? tickStarted() : tickStart), + ...(gpuMs === undefined ? {} : { gpuMs }), pixelRatio: scene.pixelRatio ?? 1, width: scene.drawingBufferWidth ?? scene.canvas?.width ?? 0, height: scene.drawingBufferHeight ?? scene.canvas?.height ?? 0, @@ -354,7 +432,7 @@ export function createCesiumQuality( }; }, signals: { - gpuTiming: 'none', + gpuTiming: gpuTimer ? 'frame' : 'none', on(event, cb) { if (event !== 'frame') return () => {}; return signalListeners.on(cb); @@ -370,6 +448,7 @@ export function createCesiumQuality( disposed = true; signalListeners.clear(); for (const off of removers) off(); + gpuTimer?.dispose(); offWatch?.(); offWatch = null; }, diff --git a/src/render/cesium/quality.test.mjs b/src/render/cesium/quality.test.mjs index 6c511d591..d0e05593b 100644 --- a/src/render/cesium/quality.test.mjs +++ b/src/render/cesium/quality.test.mjs @@ -38,6 +38,7 @@ function fixture({ msaaSupported = true, maximumSamples = 8, tickStarted, + gl = null, } = {}) { const primitives = new Collection(); const scene = { @@ -75,6 +76,7 @@ function fixture({ isCollection: (p) => p instanceof Collection, limits: { maximumTextureSize: 16384, maximumSamples }, tickStarted, + gl, }); const tick = () => { scene.preUpdate.raise(); @@ -245,6 +247,73 @@ test('frame signals come with each drawn frame and follow the listener rules', ( assert.equal(seen.length, 1, 'nothing after dispose'); }); +/** A WebGL 2 context with timer queries whose results come back when told. */ +function timerContext() { + const ext = { TIME_ELAPSED_EXT: 0x88bf, GPU_DISJOINT_EXT: 0x8fbb }; + const log = []; + const results = new Map(); + let disjoint = false; + let made = 0; + const gl = { + QUERY_RESULT: 0x8866, + QUERY_RESULT_AVAILABLE: 0x8867, + log, + getExtension: (name) => + name === 'EXT_disjoint_timer_query_webgl2' ? ext : null, + createQuery: () => ({ n: made++ }), + deleteQuery: (q) => log.push(['delete', q.n]), + beginQuery: (target, q) => log.push(['begin', q.n]), + endQuery: () => log.push(['end']), + getQueryParameter: (q, what) => + what === gl.QUERY_RESULT_AVAILABLE ? results.has(q.n) : results.get(q.n), + getParameter: (what) => (what === ext.GPU_DISJOINT_EXT ? disjoint : null), + /** Query `n` took `ms` on the GPU. */ + finish: (n, ms) => results.set(n, ms * 1e6), + setDisjoint: (value) => (disjoint = value), + }; + return gl; +} + +test('with timer queries, drawn frames are timed on the GPU and signals carry the latest', () => { + const gl = timerContext(); + const { quality, tick, dispose } = fixture({ gl }); + assert.equal(quality.signals.gpuTiming, 'frame'); + assert.equal(quality.device().gpuTimer, true); + tick(); + assert.deepEqual(gl.log, [], 'nothing timed while no one listens'); + const seen = []; + quality.signals.on('frame', (s) => seen.push(s)); + tick(); + assert.deepEqual(gl.log, [['begin', 0], ['end']], 'the frame is timed'); + assert.ok(!('gpuMs' in seen[0]), 'none back yet'); + gl.finish(0, 3.5); + tick(); + assert.equal(seen[1].gpuMs, 3.5, 'the last frame’s, once it is back'); + assert.deepEqual( + gl.log.slice(2), + [['begin', 1], ['end']], + 'a new query while the last is out', + ); + gl.setDisjoint(true); + gl.finish(1, 99); + tick(); + assert.deepEqual(gl.log.slice(4), [['begin', 0], ['end']], 'one reused'); + assert.equal(seen[2].gpuMs, 3.5, 'a disjoint timing is dropped'); + dispose(); + assert.ok( + gl.log.some(([kind]) => kind === 'delete'), + 'queries let go', + ); +}); + +test('without timer queries the port says so', () => { + const { quality } = fixture({ + gl: { createQuery() {}, getExtension: () => null }, + }); + assert.equal(quality.signals.gpuTiming, 'none'); + assert.equal(quality.device().gpuTimer, false); +}); + test('device and probe describe the context and the browser', () => { const { quality } = fixture(); const facts = quality.device(); diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index e7627024b..0e8930125 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -3869,6 +3869,43 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { set.dispose(); }, ), + check( + 'quality.signals.gpuTiming', + 'with gpuTiming, drawn frames come to carry their GPU time; without it they never do', + async (h, r) => { + const timed = r.capabilities.has('gpuTiming'); + equal( + r.quality.signals.gpuTiming !== 'none', + timed, + 'gpuTiming says whether frames are timed', + ); + equal(r.quality.device().gpuTimer, timed, 'device facts agree'); + const signals = []; + const off = r.quality.signals.on('frame', (s) => signals.push(s)); + for (let i = 0; i < 30 && !signals.some((s) => 'gpuMs' in s); i++) + await drawn(h, r, 1); + off(); + const gpu = signals.filter((s) => 'gpuMs' in s); + if (timed) { + ok(gpu.length > 0, 'a GPU time came back within 30 frames'); + ok( + gpu.every((s) => Number.isFinite(s.gpuMs) && s.gpuMs >= 0), + 'GPU times are milliseconds', + ); + } else equal(gpu.length, 0, 'no GPU time without gpuTiming'); + if (!timed) return; + const without = await h.create({ + viewport: SCRIPT_VIEWPORT, + capabilities: CAPABILITIES.filter((c) => c !== 'gpuTiming'), + }); + if (!without) return; + try { + equal(without.quality.signals.gpuTiming, 'none', 'none without it'); + } finally { + without.destroy(); + } + }, + ), check( 'quality.signals', 'frame signals arrive for drawn frames', diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 31cf36e94..323221da8 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -297,6 +297,7 @@ export function createStubRenderer(options = {}) { for (const waiter of onceWaiters.splice(0)) waiter(); const signals = { cpuMs: 0, + ...(capabilities.has('gpuTiming') ? { gpuMs: 0 } : {}), pixelRatio: qualitySettings.pixelRatio || 1, width: viewport.width, height: viewport.height,