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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(spine): why this scene's spine costs what it does, from what the frame knew
esengine9ccae5cf0a25
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex e85450626..a1bb0057a 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 91,- "experimental": 1653,+ "experimental": 1663,"deprecated": 3},- "total": 1857,+ "total": 1867,"subsystems": [{"id": "ecs",diff --git a/examples/spine-demo/src/main.ts b/examples/spine-demo/src/main.tsindex 7688d596c..91ca38af9 100644--- a/examples/spine-demo/src/main.ts+++ b/examples/spine-demo/src/main.ts@@ -4,5 +4,6 @@ import './components';import { switchSystem } from './systems/switch';console.log('[spine-demo] press 1-5 to switch: idle / walk / run / jump / shoot');+console.log('[spine-demo] press D for the spine scene diagnostics');addSystemToSchedule(Schedule.Update, switchSystem);diff --git a/examples/spine-demo/src/systems/switch.ts b/examples/spine-demo/src/systems/switch.tsindex 02017ed86..4fc8e1407 100644--- a/examples/spine-demo/src/systems/switch.ts+++ b/examples/spine-demo/src/systems/switch.ts@@ -2,7 +2,7 @@ import {defineSystem, Query, Mut, Res, Time, Input,SpineAnimation,} from 'esengine';-import { Spine } from 'esengine/spine';+import { Spine, formatSpineDiagnostics } from 'esengine/spine';import { AnimState } from '../components';const CYCLE = ['idle', 'walk', 'run', 'jump', 'shoot'];@@ -13,6 +13,17 @@ const HOLD_SECONDS = 2.5;export const switchSystem = defineSystem([Query(Mut(AnimState), SpineAnimation), Res(Spine), Res(Input), Res(Time)],(query, spine, input, time) => {+ // Counting is opt-in, so the first press turns it on and the next one+ // reads a frame that was actually counted.+ if (input.isKeyPressed('KeyD')) {+ if (spine.observing) {+ console.log(formatSpineDiagnostics(spine.diagnostics()));+ } else {+ spine.observe(true);+ console.log('[spine-demo] counting — press D again for the report');+ }+ }+for (const [entity, state] of query) {let target = -1;for (let i = 0; i < CYCLE.length; i++) {diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 6138838c3..cf6106d11 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -1,7 +1,7 @@# API surface — esengine/spine<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 1 beta · 35 experimental · 0 deprecated+Symbols: 0 public · 1 beta · 45 experimental · 0 deprecated## ConstraintList — interface @experimental```@@ -47,6 +47,16 @@ minX: numberminY: number```+## SpineAssetDiagnostic — interface @experimental+```+blockedBy: readonly SpineDeferralBlocker[]+entities: number+envelope: "unknown" | "certified" | "observed"+era: string+mayDefer: boolean+version: SpineVersion+```+## SpineBoundsSource — interface @experimental```animationDuration: (skeletonHandle: number, animation: string) => number@@ -86,6 +96,20 @@ static prototype: SpineCertificates| { kind: 'unknown' }```+## SpineDeferralBlocker — type @experimental+```+'no-certificate' | 'stateful-constraints'+```++## SpineDiagnosticRuntime — interface @experimental+```+entityCount: number+metrics: () => SpineFrameMetrics | null+residencies: () => SpineResidencyFacts[]+version: SpineVersion+worldPoseDebt: () => number+```+## SpineEvent — interface @experimental```animationName: string@@ -113,12 +137,33 @@ ResourceDef<SpineEventsData>events: readonly SpineEvent[]```+## SpineFinding — interface @experimental+```+assets: readonly string[]+code: SpineFindingCode+entities: number+```++## SpineFindingCode — type @experimental+```+| 'not-observing'+ /** Assets a culling contract would unlock. The one actionable finding. */+ | 'no-certificate'+ /** Assets no contract can unlock: their world pose carries state. */+ | 'stateful-constraints'+ /** Deferral is permitted and bought nothing this frame — everything was wanted. */+ | 'nothing-deferred'+ /** Deferral is permitted and is paying. */+ | 'deferral-working'+```+## SpineManager — class @experimental```@internal runtimeForDiagnostics: (version: SpineVersion) => SpineRuntime | undefinedboundEntities: () => Iterable<Entity>clipBudget: (entity: Entity) => SpineClipBudget | nullcollectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]+diagnostics: () => SpineSceneDiagnosticsdispose: () => voidenableEvents: (entity: Entity) => voidframeMetrics: () => Array<{ version: SpineVersion; metrics: SpineFrameMetrics; }>@@ -134,6 +179,7 @@ listConstraints: (entity: Entity) => ConstraintList | nullloadEntity: (entity: Entity, era: SpineEraBinding, _registry: CppRegistry) => Promise<SpineVersion | null>observe: (on: boolean) => voidobservedBounds: (entity: Entity, sampleStep?: number) => SpineCullingEnvelope | null+observing: booleanremoveEntity: (entity: Entity) => voidsetAnimation: (entity: Entity, animation: string, loop: boolean) => voidsetAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean@@ -217,6 +263,24 @@ static new (manager?: SpineManager): SpinePluginstatic prototype: SpinePlugin```+## SpinePoseTotals — interface @experimental+```+logicalUpdates: number+meshExtractions: number+renderCulled: number+worldAlreadyCurrent: number+worldMaterializations: number+```++## SpineResidencyFacts — interface @experimental+```+culling: SpineCullingEnvelope+entities: number+era: string+mayDefer: boolean+requiresContinuousWorldPose: boolean+```+## SpineRuntime — class @experimental```clipBudget: (entity: Entity) => SpineClipBudget | null@@ -239,6 +303,7 @@ observe: (on: boolean) => voidobservedBounds: (entity: Entity, sampleStep?: number) => SpineCullingEnvelope | nullposeEligibility: (entity: Entity) => { culling: SpineCullingEnvelope; requiresContinuousWorldPose: boolean; } | nullremoveEntity: (entity: Entity) => void+residencies: () => SpineResidencyFacts[]setAnimation: (entity: Entity, animation: string, loop: boolean) => voidsetAttachment: (entity: Entity, slotName: string, attachmentName: string) => booleansetDefaultMix: (entity: Entity, duration: number) => void@@ -254,6 +319,7 @@ setTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData)updateAll: (dt: number) => voidversion: SpineVersionwindows: () => { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow; }+worldPoseDebt: () => numberstatic new (version: SpineVersion, module: SpineWasmModule): SpineRuntimestatic prototype: SpineRuntime```@@ -265,6 +331,19 @@ samples: numberskins: number```+## SpineSceneDiagnostics — interface @experimental+```+assets: SpineAssetDiagnostic[]+deferrable: number+entities: number+findings: SpineFinding[]+frame: number+observing: boolean+pose: SpinePoseTotals+time: { pose: number; readback: number; total: number; }+worldPoseDebt: number+```+## SpineVersion — type @experimental```'2.1' | '3.8' | '4.1' | '4.2' | '4.3'@@ -300,6 +379,11 @@ mixY: number(envelope: SpineCullingEnvelope, era: string): SpineCullingEnvelope```+## formatSpineDiagnostics — function @experimental+```+(d: SpineSceneDiagnostics): string+```+## loadSpineAssets — function @experimental```(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider, owner?: SpineAssetOwner, certificates?: SpineCertificateSource): Promise<Map<string, SpineAssetInfo>>@@ -340,6 +424,11 @@ mixY: number(manager?: SpineManager): SpinePlugin```+## spineSceneDiagnostics — function @experimental+```+(runtimes: Iterable<SpineDiagnosticRuntime>, observing: boolean): SpineSceneDiagnostics+```+## worldBounds — function @experimental```(local: SpineAABB, transform: SpineAffine): SpineAABBdiff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex 48249cf76..79e6e5dbf 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -9,6 +9,8 @@ import type { SpineModuleFactory } from './SpineModuleLoader';import { SpineRuntime } from './SpineRuntime';import type { SpineEraBinding } from './prepareSpine';import type { SpineClipBudget, SpineFrameMetrics } from './spineMetrics';+import { spineSceneDiagnostics } from './spineSceneDiagnostics';+import type { SpineSceneDiagnostics } from './spineSceneDiagnostics';import type { SpineCullingEnvelope } from './spineBounds';import { log } from '../util/logger';@@ -169,6 +171,20 @@ export class SpineManager {for (const runtime of this.runtimes_.values()) runtime.observe(on);}+ /** Whether anything is counting. */+ get observing(): boolean {+ return this.observing_;+ }++ /**+ * Why this scene's spine costs what it does — the frame's numbers joined to+ * the per-asset reason each of them was paid. Derived on the spot from what+ * the runtimes already know; see spineSceneDiagnostics.+ */+ diagnostics(): SpineSceneDiagnostics {+ return spineSceneDiagnostics(this.runtimes_.values(), this.observing_);+ }+/*** What the last frame cost, per runtime — the unit anything is done about.* Empty while not observing.diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.tsindex 09025866f..043951574 100644--- a/sdk/src/spine/SpineRuntime.ts+++ b/sdk/src/spine/SpineRuntime.ts@@ -31,6 +31,7 @@ import { mayDeferWorldPose, scanObservedBounds } from './spineBounds';import type { SpineBoundsSource } from './spineBounds';import type { SpineCullingEnvelope } from './spineBounds';import { withScratch } from '../wasm/wasmScratch';+import type { SpineResidencyFacts } from './spineSceneDiagnostics';/*** What a camera said about an entity. `unknown` is not a no — it is the absence@@ -402,6 +403,35 @@ export class SpineRuntime {};}+ /** Every residency this runtime holds, for a scene-level diagnostic. */+ residencies(): SpineResidencyFacts[] {+ const out: SpineResidencyFacts[] = [];+ for (const [era, residency] of this.skeletons_) {+ out.push({+ era, entities: residency.refcount, culling: residency.culling,+ requiresContinuousWorldPose: residency.requiresContinuousWorldPose,+ mayDefer: residencyMayDefer(residency),+ });+ }+ return out;+ }++ /**+ * Entities owing a world pose, disabled ones aside — those are out of the+ * frame, so posing every frame would not have resolved them either.+ *+ * A STATE and not a tally, which is what makes it exact: read after a+ * frame's submit it is the world-transform resolves that frame did not do.+ */+ worldPoseDebt(): number {+ let owed = 0;+ for (const [entity, info] of this.entities_) {+ if (this.disabledEntities_.has(entity)) continue;+ if (info.worldRevision !== info.logicalRevision) owed++;+ }+ return owed;+ }+/*** Resolve this entity's world transforms if they do not already reflect its* local pose; returns whether it had to. The REVISION is the authority, notdiff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.tsindex 1b22db4fe..75be76dcb 100644--- a/sdk/src/spine/index.ts+++ b/sdk/src/spine/index.ts@@ -18,6 +18,11 @@ export {} from './spineBounds';export { SpineCertificates, projectSpineCertificates, NO_CERTIFICATES } from './spineCertificates';export type { SpineCertificateSource } from './spineCertificates';+export { spineSceneDiagnostics, formatSpineDiagnostics } from './spineSceneDiagnostics';+export type {+ SpineSceneDiagnostics, SpineAssetDiagnostic, SpineFinding, SpineFindingCode,+ SpineDeferralBlocker, SpinePoseTotals, SpineResidencyFacts, SpineDiagnosticRuntime,+} from './spineSceneDiagnostics';// Shared spine scene loader — the editor loads spine entities through the same// single implementation the builder runtime uses (see ./loadSpineScene).export { loadSpineSceneEntities, loadSpineAssets, applySpineEntities, spineEntityProps } from './loadSpineScene';diff --git a/sdk/src/spine/spineSceneDiagnostics.ts b/sdk/src/spine/spineSceneDiagnostics.tsnew file mode 100644index 000000000..c238b68f0--- /dev/null+++ b/sdk/src/spine/spineSceneDiagnostics.ts@@ -0,0 +1,310 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spineSceneDiagnostics.ts+ * @brief Why this scene's spine costs what it does, answered from what the+ * frame already knew.+ *+ * @details Everything here is DERIVED. No counter is added, no clock is read,+ * and nothing is remembered between calls: a report is the frame+ * metrics and the residency facts, read at the moment somebody asks.+ * A diagnostic that kept its own tally would be a second authority+ * about the same frame, and the first thing to go wrong with one is+ * that it disagrees with the thing it is explaining.+ *+ * What makes it worth having is the join. The runtime knows what a+ * frame paid; the residencies know who was ALLOWED to skip and which+ * of the two proofs they were missing. Neither answers "why is this+ * scene expensive" alone — 800 unresolved world poses is a number, and+ * "150 entities across two assets resolve every frame because nothing+ * certified their extent" is somewhere to go.+ *+ * The split between the two blockers is the editorial part, and it is+ * deliberate: an asset that also carries state across its world pose is+ * NOT reported as wanting a certificate, because certifying it would+ * change nothing. Only the assets a promise would actually unlock are+ * offered as work.+ */+import type { SpineVersion } from '../sideModules/registry';+import type { SpineCullingEnvelope } from './spineBounds';+import type { SpineFrameMetrics } from './spineMetrics';++/**+ * One residency as a diagnostic reads it: the two proofs AND what they came to.+ * Kept as three fields rather than the verdict alone, because "this asset is not+ * deferring" is not something anyone can act on and "nothing certified its+ * extent" is.+ */+export interface SpineResidencyFacts {+ era: string;+ /** Its refcount — entities posed by it, disabled ones included. */+ entities: number;+ culling: SpineCullingEnvelope;+ requiresContinuousWorldPose: boolean;+ mayDefer: boolean;+}++/**+ * The slice of a runtime a report reads, declared HERE rather than taken as a+ * runtime — everything the diagnostic needs is a read, and a view that cannot+ * reach `loadEntity` cannot become a second answer to which runtime poses an+ * entity. That answer is the manager's alone (tools/check-spine-lifetimes).+ */+export interface SpineDiagnosticRuntime {+ readonly version: SpineVersion;+ readonly entityCount: number;+ worldPoseDebt(): number;+ residencies(): SpineResidencyFacts[];+ metrics(): SpineFrameMetrics | null;+}++/** A proof a residency is missing. Both absent is possible; neither is `mayDefer`. */+export type SpineDeferralBlocker = 'no-certificate' | 'stateful-constraints';++/** One loaded skeleton, and whether the entities on it may owe a world pose. */+export interface SpineAssetDiagnostic {+ version: SpineVersion;+ /** The era — one generation of one skeleton+atlas pair. */+ era: string;+ /** Entities posed by it, disabled ones included: it is the residency's refcount. */+ entities: number;+ mayDefer: boolean;+ /** What the culling promise amounts to, not the rectangle itself. */+ envelope: SpineCullingEnvelope['kind'];+ /** Empty exactly when `mayDefer`. */+ blockedBy: readonly SpineDeferralBlocker[];+}++/** A frame's posing, summed over every loaded runtime. */+export interface SpinePoseTotals {+ logicalUpdates: number;+ worldMaterializations: number;+ worldAlreadyCurrent: number;+ /** Per (entity, CAMERA): a scene drawn by two cameras extracts twice. */+ meshExtractions: number;+ /** Per (entity, CAMERA) too — camera declines, not entities culled. */+ renderCulled: number;+}++export type SpineFindingCode =+ /** Nothing is counting, so every per-frame number below is zero. */+ | 'not-observing'+ /** Assets a culling contract would unlock. The one actionable finding. */+ | 'no-certificate'+ /** Assets no contract can unlock: their world pose carries state. */+ | 'stateful-constraints'+ /** Deferral is permitted and bought nothing this frame — everything was wanted. */+ | 'nothing-deferred'+ /** Deferral is permitted and is paying. */+ | 'deferral-working';++/** A statement about the scene, with the numbers that justify it. Wording lives+ * in {@link formatSpineDiagnostics}, so a panel can say it its own way. */+export interface SpineFinding {+ code: SpineFindingCode;+ /** Entities the finding is about. */+ entities: number;+ /** The eras it is about, where it is about assets at all. */+ assets: readonly string[];+}++export interface SpineSceneDiagnostics {+ /** False when no runtime is counting; the per-frame numbers are then zero. */+ observing: boolean;+ /** The newest frame any runtime has begun. */+ frame: number;+ entities: number;+ /**+ * Enabled entities owing a world pose. Read after the frame's submit — where+ * a diagnostic is read — this is exactly what the frame did not resolve.+ */+ worldPoseDebt: number;+ /** Entities whose residency permits owing one at all. */+ deferrable: number;+ assets: SpineAssetDiagnostic[];+ pose: SpinePoseTotals;+ /** Milliseconds, summed across runtimes; `readback` covers every camera. */+ time: { pose: number; readback: number; total: number };+ findings: SpineFinding[];+}++function blockersOf(facts: SpineResidencyFacts): SpineDeferralBlocker[] {+ const blockers: SpineDeferralBlocker[] = [];+ if (facts.requiresContinuousWorldPose) blockers.push('stateful-constraints');+ if (facts.culling.kind !== 'certified') blockers.push('no-certificate');+ return blockers;+}++/**+ * Read every loaded runtime and say what the scene's spine is doing.+ *+ * `observing` is the manager's, not inferred from whether metrics objects+ * exist: a realm watching a scene that has loaded no runtime yet is observing,+ * and reporting otherwise would send someone to turn on what is already on.+ */+export function spineSceneDiagnostics(+ runtimes: Iterable<SpineDiagnosticRuntime>, observing: boolean,+): SpineSceneDiagnostics {+ const assets: SpineAssetDiagnostic[] = [];+ const pose: SpinePoseTotals = {+ logicalUpdates: 0, worldMaterializations: 0, worldAlreadyCurrent: 0,+ meshExtractions: 0, renderCulled: 0,+ };+ const time = { pose: 0, readback: 0, total: 0 };+ let frame = 0;+ let entities = 0;+ let worldPoseDebt = 0;+ let deferrable = 0;++ for (const runtime of runtimes) {+ entities += runtime.entityCount;+ worldPoseDebt += runtime.worldPoseDebt();+ for (const facts of runtime.residencies()) {+ if (facts.mayDefer) deferrable += facts.entities;+ assets.push({+ version: runtime.version, era: facts.era, entities: facts.entities,+ mayDefer: facts.mayDefer, envelope: facts.culling.kind,+ blockedBy: blockersOf(facts),+ });+ }+ const m = runtime.metrics();+ if (!m) continue;+ 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;+ time.pose += m.time.pose;+ time.readback += m.time.readback;+ time.total += m.time.total;+ }++ 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,+ findings: findingsOf(observing, entities, worldPoseDebt, deferrable, assets),+ };+}++/** Ordered actionable-first: what to go do, before what merely explains. */+const FINDING_ORDER: readonly SpineFindingCode[] = [+ 'not-observing', 'no-certificate', 'stateful-constraints',+ 'nothing-deferred', 'deferral-working',+];++function findingsOf(+ observing: boolean, entities: number, worldPoseDebt: number, deferrable: number,+ assets: readonly SpineAssetDiagnostic[],+): SpineFinding[] {+ const found: SpineFinding[] = [];+ if (!observing) found.push({ code: 'not-observing', entities, assets: [] });++ // Only the assets a promise would actually unlock. One that also carries+ // state across its world pose stays out of this: certifying it changes+ // nothing, and offering it as work is offering a dead end.+ const uncertified = assets.filter(a =>+ a.blockedBy.includes('no-certificate') && !a.blockedBy.includes('stateful-constraints'));+ if (uncertified.length > 0) {+ found.push({+ code: 'no-certificate',+ entities: uncertified.reduce((n, a) => n + a.entities, 0),+ assets: uncertified.map(a => a.era),+ });+ }++ const stateful = assets.filter(a => a.blockedBy.includes('stateful-constraints'));+ if (stateful.length > 0) {+ found.push({+ code: 'stateful-constraints',+ entities: stateful.reduce((n, a) => n + a.entities, 0),+ assets: stateful.map(a => a.era),+ });+ }++ if (observing && deferrable > 0) {+ found.push(worldPoseDebt > 0+ ? { code: 'deferral-working', entities: worldPoseDebt, assets: [] }+ : { code: 'nothing-deferred', entities: deferrable, assets: [] });+ }+ return found.sort((a, b) => FINDING_ORDER.indexOf(a.code) - FINDING_ORDER.indexOf(b.code));+}++function ms(value: number): string {+ return `${value.toFixed(2)}ms`;+}++function count(n: number, one: string, many = `${one}s`): string {+ return `${n} ${n === 1 ? one : many}`;+}++function entities(n: number): string {+ return count(n, 'entity', 'entities');+}++function sentence(finding: SpineFinding): string {+ const across = finding.assets.length > 0+ ? ` across ${count(finding.assets.length, 'asset')} (${finding.assets.join(', ')})`+ : '';+ switch (finding.code) {+ case 'not-observing':+ return 'nothing is counting — call observe(true) and read this again after a frame.';+ case 'no-certificate':+ return `${entities(finding.entities)}`+ + `${across} resolve a world pose every frame because nothing certified their`+ + ' extent. Scan the asset and record a culling contract to let them skip it'+ + ' while no camera wants them.';+ case 'stateful-constraints':+ return `${entities(finding.entities)}`+ + `${across} can never defer: their world pose carries state across frames,`+ + ' which no culling contract changes.';+ case 'nothing-deferred':+ return `${entities(finding.entities)} may defer`+ + ' and none did — every one of them was wanted this frame, so this cost is work'+ + ' being consumed rather than opportunity being missed.';+ case 'deferral-working':+ return `${count(finding.entities, 'world pose')} went unresolved — work this frame`+ + ' did not do.';+ }+}++/** Wrapped to a terminal, since a finding is a sentence and not a field. */+function wrapped(prefix: string, text: string, width = 78): string[] {+ const indent = ' '.repeat(prefix.length);+ const lines: string[] = [];+ let line = '';+ for (const word of text.split(' ')) {+ if (line === '') {+ line = (lines.length === 0 ? prefix : indent) + word;+ } else if (line.length + 1 + word.length > width) {+ lines.push(line);+ line = indent + word;+ } else {+ line += ` ${word}`;+ }+ }+ if (line !== '') lines.push(line);+ return lines;+}++/** The report as text, for a console or an overlay. */+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)}`+ + ` total ${ms(d.time.total)}`,+ ` 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`,+ '',+ ];+ 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)}`+ + ` ${asset.version.padEnd(4)} ${why}`);+ }+ if (d.findings.length > 0) lines.push('');+ for (const finding of d.findings) lines.push(...wrapped(' * ', sentence(finding)));+ return lines.join('\n');+}diff --git a/sdk/tests/spine-scene-diagnostics.test.ts b/sdk/tests/spine-scene-diagnostics.test.tsnew file mode 100644index 000000000..fbc05b3cf--- /dev/null+++ b/sdk/tests/spine-scene-diagnostics.test.ts@@ -0,0 +1,272 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-scene-diagnostics.test.ts+ * @brief "Why is this scene's spine expensive" — answered without a profiler.+ *+ * @details Two halves that are only useful joined. What a frame paid is a+ * number, and a number is not somewhere to go; what each asset was+ * MISSING is the other half, and it turns 800 unresolved poses into+ * two assets nobody promised an extent for.+ *+ * So the criteria here are about the join, and about the one editorial+ * decision in it: an asset whose world pose carries state is never+ * offered as wanting a certificate, because certifying it would change+ * nothing. A diagnostic that sends someone to do work that cannot help+ * is worse than one that says nothing.+ */+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 { certifyBounds } from '../src/spine/spineBounds';+import type { SpineCullingEnvelope } from '../src/spine/spineBounds';+import { fakeSpineModule, fakeSpineEra } from './helpers/fakeSpineModule';+import type { Entity } from '../src/types';++const CERTIFIED: SpineCullingEnvelope = certifyBounds({ minX: -100, minY: -100, maxX: 100, maxY: 100 });+const DT = 1 / 60;++afterEach(() => { vi.restoreAllMocks(); });++/** A core answering visibility as `sees` says, per entity. */+function camera(sees: (entity: number) => boolean) {+ const heap = new Uint32Array(64);+ return {+ renderer_submitSkeletalBatchByEntity: () => {},+ renderer_entityVisibleToCamera: (+ _r: unknown, entity: number, _l: number,+ _a: number, _b: number, _c: number, _d: number, out: number,+ ) => { heap[out >> 2] = sees(entity) ? 1 : 0; },+ _malloc: () => 4,+ _free: () => {},+ HEAPU8: new Uint8Array(heap.buffer),+ HEAPU32: heap,+ } as never;+}++const ALWAYS = camera(() => true);+const NEVER = camera(() => false);++interface Asset {+ era: string;+ entities: number;+ culling?: SpineCullingEnvelope;+ stateful?: boolean;+}++/** One runtime per statefulness, since that is a property of the MODULE. */+function scene(assets: Asset[]): SpineRuntime[] {+ const runtimes: SpineRuntime[] = [];+ let nextEntity = 1;+ for (const kind of [false, true]) {+ const mine = assets.filter(a => (a.stateful ?? false) === kind);+ if (mine.length === 0) continue;+ const fake = fakeSpineModule();+ fake.continuousWorldPose = kind;+ const runtime = new SpineRuntime(kind ? '4.2' : '3.8', fake.module);+ for (const asset of mine) {+ const era = fakeSpineEra(asset.era, new Uint8Array([1]), asset.culling ?? { kind: 'unknown' });+ for (let i = 0; i < asset.entities; i++) runtime.loadEntity(nextEntity++ as Entity, era);+ }+ runtime.observe(true);+ runtimes.push(runtime);+ }+ return runtimes;+}++function codes(runtimes: SpineRuntime[]): SpineFindingCode[] {+ return spineSceneDiagnostics(runtimes, true).findings.map(f => f.code);+}++function dispose(runtimes: SpineRuntime[]): void {+ for (const runtime of runtimes) runtime.dispose();+}++describe('what the frame did not do', () => {+ it('an unseen certified entity leaves the frame owing the pose nobody wanted', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ runtimes[0].updateAll(DT);+ runtimes[0].extractAndSubmitMeshes(NEVER, {} as never);++ const d = spineSceneDiagnostics(runtimes, true);+ expect(d.pose.logicalUpdates, 'the animation stopped').toBe(1);+ expect(d.pose.worldMaterializations, 'a pose nobody asked for was resolved').toBe(0);+ expect(d.worldPoseDebt, 'the skipped world pose was not reported as skipped').toBe(1);+ expect(d.deferrable).toBe(1);+ dispose(runtimes);+ });++ it('a seen one owes nothing, and a second camera finds the debt settled', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ runtimes[0].updateAll(DT);+ runtimes[0].extractAndSubmitMeshes(ALWAYS, {} as never);+ runtimes[0].extractAndSubmitMeshes(ALWAYS, {} as never);++ const d = spineSceneDiagnostics(runtimes, true);+ expect(d.pose.worldMaterializations, 'the second camera paid for the pose again').toBe(1);+ expect(d.pose.worldAlreadyCurrent).toBe(1);+ expect(d.pose.meshExtractions, 'extraction is per camera, and two of them drew it').toBe(2);+ expect(d.worldPoseDebt, 'a pose that was resolved is still reported as owed').toBe(0);+ dispose(runtimes);+ });++ it('counts a decline per camera, because that is what it is', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ runtimes[0].updateAll(DT);+ runtimes[0].extractAndSubmitMeshes(NEVER, {} as never);+ runtimes[0].extractAndSubmitMeshes(NEVER, {} as never);++ const d = spineSceneDiagnostics(runtimes, true);+ expect(d.pose.renderCulled).toBe(2);+ expect(d.worldPoseDebt, 'one entity owes one pose however many cameras declined it').toBe(1);+ dispose(runtimes);+ });++ it('a disabled entity is out of the frame, not in debt', () => {+ // Posing every frame would not have resolved it either, so counting it+ // would credit the scheduler with work no scheduler was going to do.+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ runtimes[0].updateAll(DT);+ expect(runtimes[0].worldPoseDebt(), 'it owes one after advancing').toBe(1);++ runtimes[0].setEnabled(1 as Entity, false);+ runtimes[0].updateAll(DT);+ expect(spineSceneDiagnostics(runtimes, true).worldPoseDebt,+ 'an entity nobody was going to pose was counted as a saving').toBe(0);+ dispose(runtimes);+ });+});++describe('why an asset is not lazy', () => {+ it('names the missing proof, and both of them when both are missing', () => {+ const runtimes = scene([+ { era: 'lazy#1', entities: 1, culling: CERTIFIED },+ { era: 'unpromised#1', entities: 1 },+ { era: 'stateful#1', entities: 1, culling: CERTIFIED, stateful: true },+ { era: 'neither#1', entities: 1, stateful: true },+ ]);+ const byEra = new Map(spineSceneDiagnostics(runtimes, true).assets.map(a => [a.era, a]));++ expect(byEra.get('lazy#1')!.mayDefer).toBe(true);+ expect(byEra.get('lazy#1')!.blockedBy).toEqual([]);+ expect(byEra.get('unpromised#1')!.blockedBy).toEqual(['no-certificate']);+ expect(byEra.get('stateful#1')!.blockedBy).toEqual(['stateful-constraints']);+ expect(byEra.get('neither#1')!.blockedBy)+ .toEqual(['stateful-constraints', 'no-certificate']);+ expect(byEra.get('neither#1')!.envelope).toBe('unknown');+ dispose(runtimes);+ });++ it('offers only the assets a certificate would actually unlock', () => {+ // The one with stateful constraints stays out: certifying it changes+ // nothing, and offering it as work is offering a dead end.+ const runtimes = scene([+ { era: 'unpromised#1', entities: 3 },+ { era: 'neither#1', entities: 40, stateful: true },+ ]);+ const d = spineSceneDiagnostics(runtimes, true);+ const certificate = d.findings.find(f => f.code === 'no-certificate')!;++ expect(certificate.assets).toEqual(['unpromised#1']);+ expect(certificate.entities, 'an asset no promise can unlock was offered as work').toBe(3);+ expect(d.findings.find(f => f.code === 'stateful-constraints')!.assets)+ .toEqual(['neither#1']);+ dispose(runtimes);+ });++ it('puts the biggest asset first, so the first line is the one that matters', () => {+ const runtimes = scene([+ { era: 'few#1', entities: 2 },+ { era: 'many#1', entities: 30 },+ { era: 'some#1', entities: 9 },+ ]);+ const d = spineSceneDiagnostics(runtimes, true);+ expect(d.assets.map(a => a.era)).toEqual(['many#1', 'some#1', 'few#1']);+ expect(d.assets.map(a => a.entities)).toEqual([30, 9, 2]);+ expect(d.entities).toBe(41);+ dispose(runtimes);+ });+});++describe('what the report says about itself', () => {+ it('says nothing is counting rather than handing over zeros as facts', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ for (const runtime of runtimes) runtime.observe(false);++ const d = spineSceneDiagnostics(runtimes, false);+ expect(d.observing).toBe(false);+ expect(d.findings[0].code).toBe('not-observing');+ expect(d.pose.logicalUpdates).toBe(0);+ expect(formatSpineDiagnostics(d)).toContain('nothing is counting');+ dispose(runtimes);+ });++ it('separates deferral that paid from deferral that had no chance to', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 1, culling: CERTIFIED }]);+ runtimes[0].updateAll(DT);+ runtimes[0].extractAndSubmitMeshes(ALWAYS, {} as never);+ expect(codes(runtimes), 'a frame that deferred nothing claimed a saving')+ .toContain('nothing-deferred');++ runtimes[0].updateAll(DT);+ runtimes[0].extractAndSubmitMeshes(NEVER, {} as never);+ expect(codes(runtimes)).toContain('deferral-working');+ dispose(runtimes);+ });++ it('wraps a finding without losing or gluing a word', () => {+ const runtimes = scene([{ era: 'a-very-long-era-name-for-wrapping#1', entities: 7 }]);+ const text = formatSpineDiagnostics(spineSceneDiagnostics(runtimes, true));+ const bullet = text.split('\n').filter(l => l.startsWith(' * ') || l.startsWith(' '));++ expect(bullet.length, 'the sentence never wrapped at all').toBeGreaterThan(1);+ for (const line of bullet) expect(line.length).toBeLessThanOrEqual(78);+ expect(bullet[0]).toMatch(/^ {2}\* \S/);+ // Exactly the bullet's width, so the sentence hangs under itself. A+ // continuation that drifts by one space still READS fine, which is why+ // the column is asserted rather than eyeballed.+ for (const line of bullet.slice(1)) expect(line).toMatch(/^ {4}\S/);+ expect(bullet.map(l => l.replace(/^ +\*? ?/, '')).join(' '))+ .toBe('7 entities across 1 asset (a-very-long-era-name-for-wrapping#1) resolve a world'+ + ' pose every frame because nothing certified their extent. Scan the asset and'+ + ' record a culling contract to let them skip it while no camera wants them.');+ dispose(runtimes);+ });++ it('never asks for a certificate when every asset already has one', () => {+ const runtimes = scene([{ era: 'hero#1', entities: 4, culling: CERTIFIED }]);+ expect(codes(runtimes)).not.toContain('no-certificate');+ expect(codes(runtimes)).not.toContain('stateful-constraints');+ dispose(runtimes);+ });+});++describe('a scene is every runtime it loaded', () => {+ it('adds up what two spine versions each cost, rather than reporting one', () => {+ // A scene mixing versions loads a runtime per version, and the frame is+ // the sum: reporting either alone understates it by the other.+ const now = vi.spyOn(performance, 'now');+ now.mockReturnValueOnce(0).mockReturnValueOnce(2) // 3.8 pose: 2ms+ .mockReturnValueOnce(10).mockReturnValueOnce(13) // 3.8 read: 3ms+ .mockReturnValueOnce(20).mockReturnValueOnce(27) // 4.2 pose: 7ms+ .mockReturnValueOnce(30).mockReturnValueOnce(31); // 4.2 read: 1ms++ const runtimes = scene([+ { era: 'hero#1', entities: 2, culling: CERTIFIED },+ { era: 'rope#1', entities: 5, culling: CERTIFIED, stateful: true },+ ]);+ for (const runtime of runtimes) {+ runtime.updateAll(DT);+ runtime.extractAndSubmitMeshes(ALWAYS, {} as never);+ }++ const d = spineSceneDiagnostics(runtimes, true);+ expect(d.time.pose, 'one runtime was reported as the scene').toBe(9);+ expect(d.time.readback).toBe(4);+ expect(d.time.total).toBe(13);+ expect(d.pose.logicalUpdates).toBe(7);+ expect(d.assets.map(a => a.version)).toEqual(['4.2', '3.8']);+ dispose(runtimes);+ });+});