Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(spine): the report is the whole frame, and the two dead doors are gone

esengine80edd0dc9733
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index cf6106d11..2e60e500f 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -107,6 +107,7 @@ entityCount: number
metrics: () => SpineFrameMetrics | null
residencies: () => SpineResidencyFacts[]
version: SpineVersion
+windows: () => { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow; }
worldPoseDebt: () => number
```
@@ -159,14 +160,12 @@ entities: number
## SpineManager — class @experimental
```
-@internal runtimeForDiagnostics: (version: SpineVersion) => SpineRuntime | undefined
boundEntities: () => Iterable<Entity>
clipBudget: (entity: Entity) => SpineClipBudget | null
collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]
diagnostics: () => SpineSceneDiagnostics
dispose: () => void
enableEvents: (entity: Entity) => void
-frameMetrics: () => Array<{ version: SpineVersion; metrics: SpineFrameMetrics; }>
getAnimations: (entity: Entity) => string[]
getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | null
getEntityVersion: (entity: Entity) => SpineVersion | undefined
@@ -333,13 +332,17 @@ skins: number
## SpineSceneDiagnostics — interface @experimental
```
+abi: SpineAbiCounts
assets: SpineAssetDiagnostic[]
+bytes: SpineByteCounts
deferrable: number
entities: number
findings: SpineFinding[]
frame: number
+geometry: { meshBatches: number; vertices: number; indices: number; }
observing: boolean
pose: SpinePoseTotals
+runtimes: SpineRuntimeTiming[]
time: { pose: number; readback: number; total: number; }
worldPoseDebt: number
```
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
index 79e6e5dbf..35cb848ed 100644
--- a/sdk/src/spine/SpineManager.ts
+++ b/sdk/src/spine/SpineManager.ts
@@ -8,7 +8,7 @@ import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } fro
import type { SpineModuleFactory } from './SpineModuleLoader';
import { SpineRuntime } from './SpineRuntime';
import type { SpineEraBinding } from './prepareSpine';
-import type { SpineClipBudget, SpineFrameMetrics } from './spineMetrics';
+import type { SpineClipBudget } from './spineMetrics';
import { spineSceneDiagnostics } from './spineSceneDiagnostics';
import type { SpineSceneDiagnostics } from './spineSceneDiagnostics';
import type { SpineCullingEnvelope } from './spineBounds';
@@ -155,13 +155,6 @@ export class SpineManager {
return this.runtimes_.has(version);
}
- /** @internal One version's runtime, for a diagnostic that has to look at
- * what it holds. Not a door into it: an entity's binding is this manager's,
- * and reaching a runtime directly is how one gets posed by two of them. */
- runtimeForDiagnostics(version: SpineVersion): SpineRuntime | undefined {
- return this.runtimes_.get(version);
- }
-
/**
* Start or stop reporting what frames cost, on every runtime this app has
* and every one it loads later. Off by default.
@@ -185,19 +178,6 @@ export class SpineManager {
return spineSceneDiagnostics(this.runtimes_.values(), this.observing_);
}
- /**
- * What the last frame cost, per runtime — the unit anything is done about.
- * Empty while not observing.
- */
- frameMetrics(): Array<{ version: SpineVersion; metrics: SpineFrameMetrics }> {
- const out: Array<{ version: SpineVersion; metrics: SpineFrameMetrics }> = [];
- for (const runtime of this.runtimes_.values()) {
- const metrics = runtime.metrics();
- if (metrics) out.push({ version: runtime.version, metrics });
- }
- return out;
- }
-
setAnimation(entity: Entity, animation: string, loop: boolean): void {
this.runtimeOf_(entity)?.setAnimation(entity, animation, loop);
}
diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.ts
index 043951574..d29c5568d 100644
--- a/sdk/src/spine/SpineRuntime.ts
+++ b/sdk/src/spine/SpineRuntime.ts
@@ -468,6 +468,7 @@ export class SpineRuntime {
// extract runs once per camera and no camera knows it was the last,
// so the window is fed the previous frame, once, from the next one.
if (m.frame > 0) {
+ this.poseWindow_.push(m.time.pose);
this.readbackWindow_.push(m.time.readback);
this.totalWindow_.push(m.time.total);
}
@@ -497,7 +498,6 @@ export class SpineRuntime {
m.time.pose = performance.now() - started;
m.entities = this.entities_.size;
m.residencies = this.skeletons_.size;
- this.poseWindow_.push(m.time.pose);
}
/** @param core whichever engine core is present (see ecs/engineApi.ts) — the
@@ -556,8 +556,9 @@ export class SpineRuntime {
return this.metrics_;
}
- /** The last 120 frames of each timed phase. A mean hides the frame that
- * missed; these say whether one did. */
+ /** The last 120 COMPLETED frames of each timed phase — all three fed at the
+ * same boundary, so they always describe the same frames. A mean hides the
+ * frame that missed; these say whether one did. */
windows(): { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow } {
return { pose: this.poseWindow_, readback: this.readbackWindow_, total: this.totalWindow_ };
}
diff --git a/sdk/src/spine/spineSceneDiagnostics.ts b/sdk/src/spine/spineSceneDiagnostics.ts
index c238b68f0..302de36c6 100644
--- a/sdk/src/spine/spineSceneDiagnostics.ts
+++ b/sdk/src/spine/spineSceneDiagnostics.ts
@@ -27,7 +27,8 @@
*/
import type { SpineVersion } from '../sideModules/registry';
import type { SpineCullingEnvelope } from './spineBounds';
-import type { SpineFrameMetrics } from './spineMetrics';
+import type { SpineAbiCounts, SpineByteCounts, SpineFrameMetrics,
+ SpineTimeWindow } from './spineMetrics';
/**
* One residency as a diagnostic reads it: the two proofs AND what they came to.
@@ -56,6 +57,7 @@ export interface SpineDiagnosticRuntime {
worldPoseDebt(): number;
residencies(): SpineResidencyFacts[];
metrics(): SpineFrameMetrics | null;
+ windows(): { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow };
}
/** A proof a residency is missing. Both absent is possible; neither is `mayDefer`. */
@@ -86,6 +88,28 @@ export interface SpinePoseTotals {
renderCulled: number;
}
+/** One phase over the frames behind it. */
+export interface SpineWindowStats {
+ last: number;
+ p50: number;
+ p95: number;
+ max: number;
+}
+
+/**
+ * One runtime's recent frames. PER RUNTIME rather than summed, because a
+ * percentile does not add: the p95 of two runtimes' totals is not the sum of
+ * their p95s, and printing it as one would be a number nobody's frame had.
+ */
+export interface SpineRuntimeTiming {
+ version: SpineVersion;
+ /** Completed frames behind these numbers. */
+ frames: number;
+ pose: SpineWindowStats;
+ readback: SpineWindowStats;
+ total: SpineWindowStats;
+}
+
export type SpineFindingCode =
/** Nothing is counting, so every per-frame number below is zero. */
| 'not-observing'
@@ -122,12 +146,24 @@ export interface SpineSceneDiagnostics {
/** Entities whose residency permits owing one at all. */
deferrable: number;
assets: SpineAssetDiagnostic[];
+ /** What the frames behind this one cost, per runtime. */
+ runtimes: SpineRuntimeTiming[];
pose: SpinePoseTotals;
+ /** What the frame drew, summed across runtimes. */
+ geometry: { meshBatches: number; vertices: number; indices: number };
+ /** Crossings into the modules, and the bytes they moved. */
+ abi: SpineAbiCounts;
+ bytes: SpineByteCounts;
/** Milliseconds, summed across runtimes; `readback` covers every camera. */
time: { pose: number; readback: number; total: number };
findings: SpineFinding[];
}
+function windowStats(window: SpineTimeWindow): SpineWindowStats {
+ const { last, p50, p95, max } = window.stats();
+ return { last, p50, p95, max };
+}
+
function blockersOf(facts: SpineResidencyFacts): SpineDeferralBlocker[] {
const blockers: SpineDeferralBlocker[] = [];
if (facts.requiresContinuousWorldPose) blockers.push('stateful-constraints');
@@ -146,10 +182,17 @@ export function spineSceneDiagnostics(
runtimes: Iterable<SpineDiagnosticRuntime>, observing: boolean,
): SpineSceneDiagnostics {
const assets: SpineAssetDiagnostic[] = [];
+ const timings: SpineRuntimeTiming[] = [];
const pose: SpinePoseTotals = {
logicalUpdates: 0, worldMaterializations: 0, worldAlreadyCurrent: 0,
meshExtractions: 0, renderCulled: 0,
};
+ const geometry = { meshBatches: 0, vertices: 0, indices: 0 };
+ const abi: SpineAbiCounts = {
+ pose: 0, world: 0, batchCount: 0, vertexCount: 0, indexCount: 0,
+ batchData: 0, malloc: 0, free: 0, submit: 0,
+ };
+ const bytes: SpineByteCounts = { wasmRead: 0, coreWrite: 0, scratchAllocated: 0 };
const time = { pose: 0, readback: 0, total: 0 };
let frame = 0;
let entities = 0;
@@ -169,12 +212,25 @@ export function spineSceneDiagnostics(
}
const m = runtime.metrics();
if (!m) continue;
+ const w = runtime.windows();
+ timings.push({
+ version: runtime.version, frames: w.total.size,
+ pose: windowStats(w.pose), readback: windowStats(w.readback),
+ total: windowStats(w.total),
+ });
frame = Math.max(frame, m.frame);
pose.logicalUpdates += m.pose.logicalUpdates;
pose.worldMaterializations += m.pose.worldMaterializations;
pose.worldAlreadyCurrent += m.pose.worldAlreadyCurrent;
pose.meshExtractions += m.pose.meshExtractions;
pose.renderCulled += m.pose.renderCulled;
+ geometry.meshBatches += m.meshBatches;
+ geometry.vertices += m.vertices;
+ geometry.indices += m.indices;
+ for (const key of Object.keys(abi) as Array<keyof SpineAbiCounts>) abi[key] += m.abi[key];
+ for (const key of Object.keys(bytes) as Array<keyof SpineByteCounts>) {
+ bytes[key] += m.bytes[key];
+ }
time.pose += m.time.pose;
time.readback += m.time.readback;
time.total += m.time.total;
@@ -182,7 +238,8 @@ export function spineSceneDiagnostics(
assets.sort((a, b) => b.entities - a.entities || (a.era < b.era ? -1 : a.era > b.era ? 1 : 0));
return {
- observing, frame, entities, worldPoseDebt, deferrable, assets, pose, time,
+ observing, frame, entities, worldPoseDebt, deferrable, assets,
+ runtimes: timings, pose, geometry, abi, bytes, time,
findings: findingsOf(observing, entities, worldPoseDebt, deferrable, assets),
};
}
@@ -234,6 +291,12 @@ function ms(value: number): string {
return `${value.toFixed(2)}ms`;
}
+function bytesOf(value: number): string {
+ if (value < 1024) return `${value}B`;
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)}KB`;
+ return `${(value / (1024 * 1024)).toFixed(1)}MB`;
+}
+
function count(n: number, one: string, many = `${one}s`): string {
return `${n} ${n === 1 ? one : many}`;
}
@@ -291,14 +354,26 @@ function wrapped(prefix: string, text: string, width = 78): string[] {
export function formatSpineDiagnostics(d: SpineSceneDiagnostics): string {
const lines: string[] = [
`spine — frame ${d.frame}, ${entities(d.entities)} across ${count(d.assets.length, 'asset')}`,
- ` time pose ${ms(d.time.pose)} readback ${ms(d.time.readback)}`
+ ` time pose ${ms(d.time.pose)} readback ${ms(d.time.readback)}`
+ ` total ${ms(d.time.total)}`,
- ` world ${d.pose.worldMaterializations} resolved, ${d.worldPoseDebt} unresolved,`
+ ` world ${d.pose.worldMaterializations} resolved, ${d.worldPoseDebt} unresolved,`
+ ` ${d.pose.worldAlreadyCurrent} already current`,
- ` logical ${d.pose.logicalUpdates} advances`,
- ` draw ${d.pose.meshExtractions} extracted, ${d.pose.renderCulled} camera declines`,
- '',
+ ` logical ${d.pose.logicalUpdates} advances`,
+ ` draw ${d.pose.meshExtractions} extracted, ${d.pose.renderCulled} camera declines`,
+ ` geometry ${d.geometry.meshBatches} batches, ${d.geometry.vertices} vertices,`
+ + ` ${d.geometry.indices} indices`,
+ ` bytes ${bytesOf(d.bytes.wasmRead)} out of the modules,`
+ + ` ${bytesOf(d.bytes.coreWrite)} into the core`,
+ ` crossings ${d.abi.pose} pose, ${d.abi.world} world, ${d.abi.batchData} batch data,`
+ + ` ${d.abi.submit} submit`,
];
+ // A single frame is a sample; the window is what says whether it was a
+ // typical one, which is the difference between a report and an anecdote.
+ for (const t of d.runtimes) {
+ lines.push(` ${t.version.padEnd(9)} ${t.frames} frames — total`
+ + ` p50 ${ms(t.total.p50)} p95 ${ms(t.total.p95)} max ${ms(t.total.max)}`);
+ }
+ lines.push('');
for (const asset of d.assets) {
const why = asset.mayDefer ? 'may defer' : `always resolves — ${asset.blockedBy.join(', ')}`;
lines.push(` ${asset.era.padEnd(28)} ${String(asset.entities).padStart(6)}`
diff --git a/sdk/tests/spine-frame-boundary.test.ts b/sdk/tests/spine-frame-boundary.test.ts
index 2f96efed4..0cb806c2d 100644
--- a/sdk/tests/spine-frame-boundary.test.ts
+++ b/sdk/tests/spine-frame-boundary.test.ts
@@ -92,6 +92,20 @@ describe('a frame drawn by more than one camera', () => {
runtime.dispose();
});
+ it('feeds all three windows at one boundary, so they describe one set of frames', () => {
+ const runtime = watched();
+ for (let i = 0; i < 5; i++) {
+ runtime.updateAll(DT);
+ runtime.extractAndSubmitMeshes(camera(), {} as never);
+ }
+
+ const { pose, readback, total } = runtime.windows();
+ expect([pose.size, readback.size, total.size],
+ 'a window holds a different set of frames from the one beside it')
+ .toEqual([4, 4, 4]);
+ runtime.dispose();
+ });
+
it('starts the next frame\'s counts over, however the last one ended', () => {
const runtime = watched();
runtime.updateAll(DT);
diff --git a/sdk/tests/spine-scene-diagnostics.test.ts b/sdk/tests/spine-scene-diagnostics.test.ts
index fbc05b3cf..90c9fa716 100644
--- a/sdk/tests/spine-scene-diagnostics.test.ts
+++ b/sdk/tests/spine-scene-diagnostics.test.ts
@@ -18,7 +18,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { SpineRuntime } from '../src/spine/SpineRuntime';
import { spineSceneDiagnostics, formatSpineDiagnostics } from '../src/spine/spineSceneDiagnostics';
-import type { SpineFindingCode } from '../src/spine/spineSceneDiagnostics';
+import type { SpineFindingCode, SpineDiagnosticRuntime } from '../src/spine/spineSceneDiagnostics';
+import { newSpineFrameMetrics, SpineTimeWindow } from '../src/spine/spineMetrics';
+import type { SpineVersion } from '../src/spine/SpineManager';
import { certifyBounds } from '../src/spine/spineBounds';
import type { SpineCullingEnvelope } from '../src/spine/spineBounds';
import { fakeSpineModule, fakeSpineEra } from './helpers/fakeSpineModule';
@@ -269,4 +271,74 @@ describe('a scene is every runtime it loaded', () => {
expect(d.assets.map(a => a.version)).toEqual(['4.2', '3.8']);
dispose(runtimes);
});
+
+ it('keeps each runtime\'s window to itself, because a percentile does not add', () => {
+ const runtimes = scene([
+ { era: 'hero#1', entities: 1, culling: CERTIFIED },
+ { era: 'rope#1', entities: 1, culling: CERTIFIED, stateful: true },
+ ]);
+ for (let i = 0; i < 4; i++) {
+ for (const runtime of runtimes) {
+ runtime.updateAll(DT);
+ runtime.extractAndSubmitMeshes(ALWAYS, {} as never);
+ }
+ }
+
+ const d = spineSceneDiagnostics(runtimes, true);
+ expect(d.runtimes.map(t => t.version)).toEqual(['3.8', '4.2']);
+ // Four frames begun, three of them completed: the one in hand is not a
+ // frame yet, and a window over frames may not contain it.
+ for (const t of d.runtimes) expect(t.frames).toBe(3);
+ dispose(runtimes);
+ });
+});
+
+/** A runtime as the report reads one — the whole seam, so what a frame moved
+ * can be driven to KNOWN and different numbers. Zeros on both sides would sum
+ * to zero however the summing was written. */
+function stub(version: SpineVersion, at: number): SpineDiagnosticRuntime {
+ const m = newSpineFrameMetrics();
+ m.frame = at;
+ m.meshBatches = at; m.vertices = at * 10; m.indices = at * 100;
+ m.abi.pose = at * 2; m.abi.world = at * 3; m.abi.batchData = at * 4; m.abi.submit = at * 5;
+ m.abi.batchCount = at * 6; m.abi.vertexCount = at * 7; m.abi.indexCount = at * 8;
+ m.abi.malloc = at * 9; m.abi.free = at * 11;
+ m.bytes.wasmRead = at * 1000; m.bytes.coreWrite = at * 2000; m.bytes.scratchAllocated = at * 3000;
+ m.pose.logicalUpdates = at;
+ const window = () => { const w = new SpineTimeWindow(); w.push(at); return w; };
+ return {
+ version, entityCount: 0,
+ worldPoseDebt: () => 0,
+ residencies: () => [],
+ metrics: () => m,
+ windows: () => ({ pose: window(), readback: window(), total: window() }),
+ };
+}
+
+describe('what a frame moved, not only what it decided', () => {
+ it('sums the crossings and the bytes, so the report needs no second door', () => {
+ // Retiring SpineManager.frameMetrics() is only honest if these survive:
+ // the batch-storage work was argued entirely in bytes moved.
+ const d = spineSceneDiagnostics([stub('3.8', 1), stub('4.2', 2)], true);
+
+ expect(d.geometry).toEqual({ meshBatches: 3, vertices: 30, indices: 300 });
+ expect(d.bytes).toEqual({ wasmRead: 3000, coreWrite: 6000, scratchAllocated: 9000 });
+ expect(d.abi).toEqual({
+ pose: 6, world: 9, batchCount: 18, vertexCount: 21, indexCount: 24,
+ batchData: 12, malloc: 27, free: 33, submit: 15,
+ });
+ expect(d.frame, 'the newest frame any runtime reached').toBe(2);
+ expect(d.runtimes.map(t => t.total.last)).toEqual([1, 2]);
+ });
+
+ it('reports the crossings a real runtime actually made', () => {
+ const runtimes = scene([{ era: 'hero#1', entities: 3, culling: CERTIFIED }]);
+ runtimes[0].updateAll(DT);
+ runtimes[0].extractAndSubmitMeshes(ALWAYS, {} as never);
+
+ const d = spineSceneDiagnostics(runtimes, true);
+ expect(d.abi.pose, 'the advance crossings went missing').toBe(3);
+ expect(d.abi.world, 'the world crossings went missing').toBe(3);
+ dispose(runtimes);
+ });
});