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): a frame that can say what it cost, and where the cost actually is
esenginee17288b435ad
diff --git a/sdk/benchmarks/spine-readback-phases.bench.ts b/sdk/benchmarks/spine-readback-phases.bench.tsnew file mode 100644index 000000000..a2d7aea52--- /dev/null+++ b/sdk/benchmarks/spine-readback-phases.bench.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-readback-phases.bench.ts+ * @brief Which part of reading a pose back is the cost.+ *+ * @details The runtime reports `pose` and `readback` because splitting the+ * second in-frame needs a clock at every batch boundary — six thousand+ * reads at a thousand entities, the observer costing what it observes.+ * So the split is measured HERE, by running the same crossings in the+ * same order and stopping at five depths:+ *+ * extract `getMeshBatchCount` — which POSES AND BUILDS every+ * vertex buffer on the module side before it can answer+ * (SpineModuleEntry.cpp: extractBatches)+ * query how many vertices, how many indices (2 calls/batch)+ * read copy them out of the module (1 call/batch)+ * transfer copy them into the core's heap (no call, MBs)+ *+ * Each depth includes the ones above it, so a phase is the difference+ * between two — which is why they are benched together and read as a+ * set, never one at a time.+ */+import { describe, bench, beforeAll } from 'vitest';+import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { WASM_DIR } from '../tests/helpers/loadWasm';+import { wrapSpineModule } from '../src/spine/SpineModuleLoader';+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';+import { withMalloc, withScratch } from '../src/wasm/wasmScratch';++const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');+const FIXTURES = resolve(__dirname, 'fixtures/spine/spineboy-38');+const HAS_ASSETS = existsSync(SPINE38_WASM) && existsSync(resolve(FIXTURES, 'spineboy-pro.skel'));++const ENTITIES = 1000;+const FRAMES = 20;+const VERTEX_FLOATS = 8;++let raw: SpineWasmModule;+let api: SpineWrappedAPI;+let instances: number[] = [];+/** The engine core's heap, as far as a copy is concerned. */+let coreHeap: Uint8Array;++beforeAll(async () => {+ if (!HAS_ASSETS) return;+ const factory = (await import(SPINE38_JS)).default as (opts: unknown) => Promise<SpineWasmModule>;+ const bytes = readFileSync(SPINE38_WASM);+ raw = await factory({+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));+ return {};+ },+ });+ api = wrapSpineModule(raw);++ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'spineboy-pro.skel')));+ const atlasText = readFileSync(resolve(FIXTURES, 'spineboy.atlas'), 'utf-8');+ const skelHandle = withScratch(raw, (alloc) => {+ const ptr = alloc(skelData.length);+ raw.HEAPU8.set(skelData, ptr);+ return api.loadSkeleton(ptr, skelData.length, atlasText, atlasText.length, true);+ });+ const pages = api.getAtlasPageCount(skelHandle);+ for (let i = 0; i < pages; i++) api.setAtlasPageTexture(skelHandle, i, 1, 1024, 1024);+ for (let i = 0; i < ENTITIES; i++) {+ const id = api.createInstance(skelHandle);+ api.playAnimation(id, 'walk', 1, 0);+ instances.push(id);+ }+ coreHeap = new Uint8Array(1 << 26);+});++/** Depth 0 is the pose; each depth after it adds the next stage. */+function pass(depth: 0 | 1 | 2 | 3 | 4): void {+ for (let f = 0; f < FRAMES; f++) {+ for (const id of instances) api.update(id, 1 / 60);+ if (depth === 0) continue;+ for (const id of instances) {+ // Not a query: this is where the module poses and builds the whole+ // frame's geometry for the instance.+ const batches = api.getMeshBatchCount(id);+ if (batches === 0 || depth === 1) continue;+ withMalloc(raw, 8, (metaPtr) => {+ for (let b = 0; b < batches; b++) {+ const vertexCount = api.getMeshBatchVertexCount(id, b);+ const indexCount = api.getMeshBatchIndexCount(id, b);+ if (depth === 2 || vertexCount <= 0 || indexCount <= 0) continue;+ const vertBytes = vertexCount * VERTEX_FLOATS * 4;+ const idxBytes = indexCount * 2;+ withScratch(raw, (alloc) => {+ const vertPtr = alloc(vertBytes);+ const idxPtr = alloc(idxBytes);+ api.getMeshBatchData(id, b, vertPtr, idxPtr, metaPtr, metaPtr + 4);+ if (depth === 3) return;+ coreHeap.set(new Uint8Array(raw.HEAPU8.buffer, vertPtr, vertBytes), 0);+ coreHeap.set(new Uint8Array(raw.HEAPU8.buffer, idxPtr, idxBytes), vertBytes);+ // Submitting is the renderer's cost, not this walk's; it+ // is measured against a real core, not faked in here.+ });+ }+ });+ }+ }+}++describe.skipIf(!HAS_ASSETS)(`Spine readback phases: ${ENTITIES} entities x${FRAMES} frames`, () => {+ bench('pose', () => { pass(0); });+ bench('+ extract (getMeshBatchCount)', () => { pass(1); });+ bench('+ query counts', () => { pass(2); });+ bench('+ read bytes out', () => { pass(3); });+ bench('+ copy into the core heap', () => { pass(4); });+});diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 0502a335b..4cd4aad65 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -68,6 +68,7 @@ boundEntities: () => Iterable<Entity>collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]dispose: () => voidenableEvents: (entity: Entity) => void+frameMetrics: () => Array<{ version: SpineVersion; metrics: SpineFrameMetrics; }>getAnimations: (entity: Entity) => string[]getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | nullgetEntityVersion: (entity: Entity) => SpineVersion | undefined@@ -78,6 +79,7 @@ hasInstance: (entity: Entity) => booleanhasRuntime: (version: SpineVersion) => booleanlistConstraints: (entity: Entity) => ConstraintList | nullloadEntity: (entity: Entity, era: SpineEraBinding, _registry: CppRegistry) => Promise<SpineVersion | null>+observe: (on: boolean) => voidremoveEntity: (entity: Entity) => voidsetAnimation: (entity: Entity, animation: string, loop: boolean) => voidsetAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean@@ -106,7 +108,7 @@ collectEvents: (instanceId: number) => RawSpineEvent[]createInstance: (skeletonHandle: number) => numberdestroyInstance: (instanceId: number) => voidenableEvents: (instanceId: number) => void-forEachMeshBatch: (instanceId: number, cb: MeshBatchVisitor) => void+forEachMeshBatch: (instanceId: number, cb: MeshBatchVisitor, probe?: SkeletalProbe) => voidgetAnimations: (instanceId: number) => string[]getAtlasPageCount: (handle: number) => numbergetAtlasPageTextureName: (handle: number, pageIndex: number) => string@@ -169,6 +171,8 @@ getSkins: (entity: Entity) => string[]getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | nulllistConstraints: (entity: Entity) => ConstraintList | nullloadEntity: (entity: Entity, era: SpineEraBinding) => boolean+metrics: () => SpineFrameMetrics | null+observe: (on: boolean) => voidremoveEntity: (entity: Entity) => voidsetAnimation: (entity: Entity, animation: string, loop: boolean) => voidsetAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean@@ -184,6 +188,7 @@ setTrackAlpha: (entity: Entity, track: number, alpha: number) => voidsetTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => booleanupdateAll: (dt: number) => voidversion: SpineVersion+windows: () => { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow; }static new (version: SpineVersion, module: SpineWasmModule): SpineRuntimestatic prototype: SpineRuntime```diff --git a/sdk/src/skeletal/meshBatches.ts b/sdk/src/skeletal/meshBatches.tsindex ee8e3ed45..1e004646e 100644--- a/sdk/src/skeletal/meshBatches.ts+++ b/sdk/src/skeletal/meshBatches.ts@@ -16,6 +16,7 @@* array per batch per frame.*/import { withMalloc, withScratch } from '../wasm/wasmScratch';+import type { SkeletalProbe } from '../spine/spineMetrics';/** The heap a module marshals through. */export interface SkeletalHeap {@@ -45,23 +46,32 @@ export type MeshBatchVisitor = (/** Interleaved x,y,u,v,r,g,b,a — the layout every skeletal module writes. */const VERTEX_FLOATS = 8;-/** Visit each posed batch. Views are valid only for the duration of each call. */+/**+ * Visit each posed batch. Views are valid only for the duration of each call.+ *+ * `probe` is counted into, never timed into: this loop is per batch per entity,+ * so a clock read here is one per crossing.+ */export function forEachMeshBatch(heap: SkeletalHeap,api: MeshBatchSource,instanceId: number,cb: MeshBatchVisitor,+ probe?: SkeletalProbe,): void {const batchCount = api.getMeshBatchCount(instanceId);+ if (probe) probe.abi.batchCount++;if (batchCount === 0) return;withMalloc(heap, 8, metaPtr => {+ if (probe) { probe.abi.malloc++; probe.abi.free++; probe.bytes.scratchAllocated += 8; }const texIdPtr = metaPtr;const blendPtr = metaPtr + 4;for (let i = 0; i < batchCount; i++) {const vertexCount = api.getMeshBatchVertexCount(instanceId, i);const indexCount = api.getMeshBatchIndexCount(instanceId, i);+ if (probe) { probe.abi.vertexCount++; probe.abi.indexCount++; }if (vertexCount <= 0 || indexCount <= 0) continue;const vertByteLen = vertexCount * VERTEX_FLOATS * 4;@@ -70,6 +80,16 @@ export function forEachMeshBatch(const vertPtr = alloc(vertByteLen);const idxPtr = alloc(idxByteLen);api.getMeshBatchData(instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);+ if (probe) {+ probe.meshBatches++;+ probe.vertices += vertexCount;+ probe.indices += indexCount;+ probe.abi.batchData++;+ probe.abi.malloc += 2;+ probe.abi.free += 2;+ probe.bytes.scratchAllocated += vertByteLen + idxByteLen;+ probe.bytes.wasmRead += vertByteLen + idxByteLen;+ }cb(new Uint8Array(heap.HEAPU8.buffer, vertPtr, vertByteLen),new Uint8Array(heap.HEAPU8.buffer, idxPtr, idxByteLen),diff --git a/sdk/src/skeletal/submitMeshes.ts b/sdk/src/skeletal/submitMeshes.tsindex ffe8f7d11..15a787353 100644--- a/sdk/src/skeletal/submitMeshes.ts+++ b/sdk/src/skeletal/submitMeshes.ts@@ -17,6 +17,7 @@import { withScratch } from '../wasm/wasmScratch';import type { Entity } from '../types';import type { MeshBatchVisitor } from './meshBatches';+import type { SkeletalProbe } from '../spine/spineMetrics';/** How an entity's skeleton sits in the world, independent of what posed it. */export interface SkeletalSubmitProps {@@ -65,6 +66,7 @@ export function submitEntityMeshes(props: SkeletalSubmitProps,walk: MeshBatchWalker,materialOf?: SkeletalMaterialOf,+ probe?: SkeletalProbe,): boolean {const submit = core.renderer_submitSkeletalBatchByEntity;const heap = core.HEAPU8;@@ -78,6 +80,10 @@ export function submitEntityMeshes(const dstIdx = alloc(idxBytes.byteLength);heap.set(vertBytes, dstVert);heap.set(idxBytes, dstIdx);+ if (probe) {+ probe.abi.submit++;+ probe.bytes.coreWrite += vertBytes.byteLength + idxBytes.byteLength;+ }submit.call(core, registry,dstVert, vertexCount, dstIdx, indexCount,textureId, blendMode, entity as number,diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex ddf2b3086..e19af8753 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -11,6 +11,7 @@ import { SpineModuleBridge } from './SpineBridge';import { log } from '../util/logger';import { withMalloc, withScratch } from '../wasm/wasmScratch';import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';+import type { SkeletalProbe } from './spineMetrics';export interface RawSpineEvent {type: number;@@ -220,8 +221,8 @@ export class SpineModuleController {* way on the C++ side, so reading them differently per runtime would be two* copies of one contract.*/- forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor): void {- forEachMeshBatch(this.raw_, this.api_, instanceId, cb);+ forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor, probe?: SkeletalProbe): void {+ forEachMeshBatch(this.raw_, this.api_, instanceId, cb, probe);}// =========================================================================diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex a1714e48c..bae9bda62 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -8,6 +8,7 @@ import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } froimport type { SpineModuleFactory } from './SpineModuleLoader';import { SpineRuntime } from './SpineRuntime';import type { SpineEraBinding } from './prepareSpine';+import type { SpineFrameMetrics } from './spineMetrics';import { log } from '../util/logger';import type { SpineVersion } from '../sideModules/registry';@@ -44,6 +45,8 @@ export class SpineManager {* runtime can only see its own entities, so one handed an entity another is* posing cannot retire the binding it replaces. */private bindings_: Map<Entity, SpineRuntime> = new Map();+ /** So a runtime loaded after `observe(true)` reports too. */+ private observing_ = false;constructor(/** Whichever engine core is present (see ecs/engineApi.ts). */@@ -156,6 +159,28 @@ export class SpineManager {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.+ */+ observe(on: boolean): void {+ this.observing_ = on;+ for (const runtime of this.runtimes_.values()) runtime.observe(on);+ }++ /**+ * 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);}@@ -300,6 +325,7 @@ export class SpineManager {const promise = (async () => {try {const runtime = new SpineRuntime(version, await factory());+ if (this.observing_) runtime.observe(true);this.runtimes_.set(version, runtime);return runtime;} catch (e) {diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.tsindex f05876dbb..34e3bb699 100644--- a/sdk/src/spine/SpineRuntime.ts+++ b/sdk/src/spine/SpineRuntime.ts@@ -21,6 +21,8 @@ import { SpineModuleController } from './SpineController';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';import { wrapSpineModule, type SpineWasmModule } from './SpineModuleLoader';import type { SpineEraBinding, SpineEraClaim } from './prepareSpine';+import { beginSpineFrame, newSpineFrameMetrics, SpineTimeWindow,+ type SpineFrameMetrics } from './spineMetrics';import type { SpineVersion } from '../sideModules/registry';import { log } from '../util/logger';import { submitEntityMeshes, type SkeletalMaterialOf } from '../skeletal/submitMeshes';@@ -53,6 +55,11 @@ export class SpineRuntime {private disabledEntities_: Set<Entity> = new Set();// era -> the one native skeleton every entity of that era is posed by.private skeletons_: Map<string, SkeletonResidency> = new Map();+ /** Null unless someone asked. The one field every probe is behind. */+ private metrics_: SpineFrameMetrics | null = null;+ private readonly poseWindow_ = new SpineTimeWindow();+ private readonly readbackWindow_ = new SpineTimeWindow();+ private readonly totalWindow_ = new SpineTimeWindow();/** One runtime per loaded module: the ABI adapter is made here rather than* handed in, because nothing else has a reason to hold one. */@@ -261,6 +268,9 @@ export class SpineRuntime {}updateAll(dt: number): void {+ const m = this.metrics_;+ if (m) beginSpineFrame(m);+ const started = m ? performance.now() : 0;for (const [entity, info] of this.entities_) {// Disabled means out of the frame entirely, so it costs no posing// either — the same meaning the DragonBones manager gives it.@@ -268,7 +278,13 @@ export class SpineRuntime {// playing=false freezes the pose (skip advance, still submitted);// timeScale scales the advance (update() takes an arbitrary dt).if (info.playing) this.controller_.update(info.instanceId, dt * info.timeScale);+ if (m) m.abi.pose++;}+ if (!m) return;+ 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@@ -276,6 +292,8 @@ export class SpineRuntime {* host arena on a device. */extractAndSubmitMeshes(core: NonNullable<EngineApi>, registry: CppRegistry,materialOf?: SkeletalMaterialOf): void {+ const m = this.metrics_;+ const started = m ? performance.now() : 0;for (const [entity, info] of this.entities_) {if (this.disabledEntities_.has(entity)) continue;// Shared with every skeletal runtime (skeletal/submitMeshes): the core's@@ -283,9 +301,39 @@ export class SpineRuntime {// what posed them. A false means the core cannot take geometry at all,// so there is no point asking again for the next entity.const accepted = submitEntityMeshes(core, registry, entity, info, cb =>- this.controller_.forEachMeshBatch(info.instanceId, cb), materialOf);+ this.controller_.forEachMeshBatch(info.instanceId, cb, m ?? undefined),+ materialOf, m ?? undefined);if (!accepted) return;}+ if (!m) return;+ // ONE clock pair for the whole pass. What it is made of — discovering+ // batches, extracting them, copying them across — is counted rather than+ // timed here; see benchmarks/spine-readback-phases for the split.+ m.time.readback = performance.now() - started;+ m.time.total = m.time.pose + m.time.readback;+ this.readbackWindow_.push(m.time.readback);+ this.totalWindow_.push(m.time.total);+ }++ /**+ * Start or stop reporting what each frame costs. Off by default and off is+ * free: every counter and both clock reads are behind this one field, so a+ * runtime nobody is watching pays a branch per entity and nothing else.+ */+ observe(on: boolean): void {+ this.metrics_ = on ? (this.metrics_ ?? newSpineFrameMetrics()) : null;+ }++ /** The LIVE frame record — the same object every frame, so reading it costs+ * nothing and holding it shows the next frame. Null when not observing. */+ metrics(): SpineFrameMetrics | null {+ return this.metrics_;+ }++ /** The last 120 frames of each timed phase. 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_ };}removeEntity(entity: Entity): void {diff --git a/sdk/src/spine/spineMetrics.ts b/sdk/src/spine/spineMetrics.tsnew file mode 100644index 000000000..9fcf0801c--- /dev/null+++ b/sdk/src/spine/spineMetrics.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spineMetrics.ts+ * @brief What one runtime's frame cost, as facts rather than a number.+ *+ * @details Fine-grained is COUNTED, coarse-grained is TIMED. A clock read beside+ * each of the eleven crossings an entity makes is eleven thousand clock+ * reads at a thousand entities — the observer becoming the thing worth+ * observing. So the counts are exact and free, and the timers are two+ * per runtime per frame.+ *+ * Which is why `readback` is one phase here and not four. Splitting it+ * into discover / extract / transfer needs a clock at every batch+ * boundary; that experiment lives in benchmarks/spine-readback-phases,+ * where paying for it changes nothing anyone ships.+ *+ * Aggregated per RUNTIME, never per entity: the unit anything is done+ * about — a batch ABI, a shared buffer, a version that misbehaves — is+ * one loaded Spine version, and a map keyed by entity would allocate+ * per entity to say so.+ */++/** Every crossing a frame made into the module, by what it asked for. */+export interface SpineAbiCounts {+ pose: number;+ batchCount: number;+ vertexCount: number;+ indexCount: number;+ batchData: number;+ malloc: number;+ free: number;+ submit: number;+}++/** Bytes moved, which no call count can stand in for. */+export interface SpineByteCounts {+ /** Read out of the module's heap by the walk. */+ wasmRead: number;+ /** Written into the engine core's heap for submission. */+ coreWrite: number;+ /** Handed out by the module's allocator for one frame's batches. */+ scratchAllocated: number;+}++/** One runtime's frame. Mutated in place — a frame that allocates to say what a+ * frame cost is measuring itself. */+export interface SpineFrameMetrics {+ frame: number;+ entities: number;+ residencies: number;+ meshBatches: number;+ vertices: number;+ indices: number;+ abi: SpineAbiCounts;+ bytes: SpineByteCounts;+ /** Milliseconds. `readback` is the whole extract+submit pass; see the file+ * note for why it is not four numbers. */+ time: { pose: number; readback: number; total: number };+}++export function newSpineFrameMetrics(): SpineFrameMetrics {+ return {+ frame: 0, entities: 0, residencies: 0, meshBatches: 0, vertices: 0, indices: 0,+ abi: { pose: 0, batchCount: 0, vertexCount: 0, indexCount: 0, batchData: 0, malloc: 0, free: 0, submit: 0 },+ bytes: { wasmRead: 0, coreWrite: 0, scratchAllocated: 0 },+ time: { pose: 0, readback: 0, total: 0 },+ };+}++/** Start a frame's counts over, keeping the object. */+export function beginSpineFrame(m: SpineFrameMetrics): void {+ m.frame++;+ m.entities = 0; m.residencies = 0; m.meshBatches = 0; m.vertices = 0; m.indices = 0;+ m.abi.pose = 0; m.abi.batchCount = 0; m.abi.vertexCount = 0; m.abi.indexCount = 0;+ m.abi.batchData = 0; m.abi.malloc = 0; m.abi.free = 0; m.abi.submit = 0;+ m.bytes.wasmRead = 0; m.bytes.coreWrite = 0; m.bytes.scratchAllocated = 0;+ m.time.pose = 0; m.time.readback = 0; m.time.total = 0;+}++/** What a frame reports as it goes: counters only, incremented at the call sites+ * that make the crossings. Shared with every skeletal runtime — the walk is. */+export interface SkeletalProbe {+ meshBatches: number;+ vertices: number;+ indices: number;+ abi: SpineAbiCounts;+ bytes: SpineByteCounts;+}++/** The last N frames of one number, and what they were. A mean hides the frame+ * that missed: four at 4ms and one at 9ms averages to a budget nobody blew. */+export class SpineTimeWindow {+ private samples_: Float64Array;+ private count_ = 0;+ private at_ = 0;+ private scratch_: Float64Array;++ constructor(readonly capacity = 120) {+ this.samples_ = new Float64Array(capacity);+ this.scratch_ = new Float64Array(capacity);+ }++ push(ms: number): void {+ this.samples_[this.at_] = ms;+ this.at_ = (this.at_ + 1) % this.capacity;+ if (this.count_ < this.capacity) this.count_++;+ }++ get size(): number {+ return this.count_;+ }++ /** last / mean / p50 / p95 / max over the window. Allocates one object per+ * CALL, which is a diagnostic reading its own answer, not a frame. */+ stats(): { last: number; mean: number; p50: number; p95: number; max: number } {+ if (this.count_ === 0) return { last: 0, mean: 0, p50: 0, p95: 0, max: 0 };+ const sorted = this.scratch_.subarray(0, this.count_);+ sorted.set(this.samples_.subarray(0, this.count_));+ sorted.sort();+ let sum = 0;+ for (let i = 0; i < this.count_; i++) sum += sorted[i];+ const at = (q: number) => sorted[Math.min(this.count_ - 1, Math.floor(q * this.count_))];+ return {+ last: this.samples_[(this.at_ - 1 + this.capacity) % this.capacity],+ mean: sum / this.count_,+ p50: at(0.5),+ p95: at(0.95),+ max: sorted[this.count_ - 1],+ };+ }+}diff --git a/sdk/tests/spine-observability.test.ts b/sdk/tests/spine-observability.test.tsnew file mode 100644index 000000000..cdfb33ad6--- /dev/null+++ b/sdk/tests/spine-observability.test.ts@@ -0,0 +1,188 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-observability.test.ts+ * @brief A frame that can say what it cost, without costing it.+ *+ * @details The trap in profiling a path that crosses an ABI eleven times per+ * entity is measuring each crossing: a thousand entities then buy+ * twenty-two thousand clock reads to explain ten milliseconds. So the+ * rule is counted-fine, timed-coarse — and it is a judgment here, not+ * an intention: the clock is read a fixed number of times per runtime+ * per frame, whatever the entity count, and not at all when nobody is+ * watching.+ */+import { describe, it, expect, beforeAll, vi, afterEach } from 'vitest';+import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { WASM_DIR } from './helpers/loadWasm';+import type { SpineWasmModule } from '../src/spine/SpineModuleLoader';+import { SpineRuntime } from '../src/spine/SpineRuntime';+import { SpineTimeWindow } from '../src/spine/spineMetrics';+import type { SpineEraBinding } from '../src/spine/prepareSpine';+import type { Entity } from '../src/types';++const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');+const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine/spineboy-38');+const SKEL = resolve(FIXTURES, 'spineboy-pro.skel');+const ATLAS = resolve(FIXTURES, 'spineboy.atlas');+const HAS_ASSETS = existsSync(SPINE38_WASM) && existsSync(SKEL) && existsSync(ATLAS);++let module38: SpineWasmModule;+let skelData: Uint8Array;+let atlasText: string;++beforeAll(async () => {+ if (!HAS_ASSETS) return;+ const factory = (await import(SPINE38_JS)).default as (opts: unknown) => Promise<SpineWasmModule>;+ const bytes = readFileSync(SPINE38_WASM);+ module38 = await factory({+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));+ return {};+ },+ });+ skelData = new Uint8Array(readFileSync(SKEL));+ atlasText = readFileSync(ATLAS, 'utf-8');+});+afterEach(() => { vi.restoreAllMocks(); });++function era(id: string): SpineEraBinding {+ return {+ id,+ value: {+ skelData, atlasText, isBinary: true,+ textures: new Map([['spineboy.png', { glId: 1, w: 1024, h: 1024 }]]),+ },+ retain: () => ({ release: () => {} }),+ };+}++function fakeCore() {+ const heap = new Uint8Array(1 << 24);+ let top = 0;+ return {+ renderer_submitSkeletalBatchByEntity: () => {},+ _malloc: (size: number) => { const at = top; top += size; return at; },+ _free: () => { top = 0; },+ HEAPU8: heap,+ };+}++function populated(entities: number, eras = 1): SpineRuntime {+ const runtime = new SpineRuntime('3.8', module38);+ for (let i = 0; i < entities; i++) {+ const entity = (i + 1) as Entity;+ runtime.loadEntity(entity, era(`hero#${i % eras}`));+ runtime.setAnimation(entity, 'walk', true);+ }+ return runtime;+}++const core = fakeCore();+function frame(runtime: SpineRuntime): void {+ runtime.updateAll(1 / 60);+ runtime.extractAndSubmitMeshes(core as never, {} as never);+}++describe.skipIf(!HAS_ASSETS)('a frame can say what it cost', () => {+ it('the counts are the crossings, exactly', () => {+ // The same numbers spine-abi-cost.test.ts asserts from outside, reported+ // from inside: a diagnostic that has to be believed on its own word is+ // one nobody can act on.+ const runtime = populated(10);+ runtime.observe(true);+ frame(runtime);+ const m = runtime.metrics()!;++ expect(m.entities).toBe(10);+ expect(m.residencies).toBe(1);+ expect(m.abi.pose).toBe(10);+ expect(m.abi.batchCount).toBe(10);+ expect(m.abi.vertexCount).toBe(m.meshBatches);+ expect(m.abi.batchData).toBe(m.meshBatches);+ expect(m.abi.malloc).toBe(10 + m.meshBatches * 2);+ expect(m.abi.free).toBe(m.abi.malloc);+ expect(m.abi.submit).toBe(m.meshBatches);+ // The bytes no call count stands in for.+ expect(m.bytes.coreWrite).toBe(m.vertices * 8 * 4 + m.indices * 2);+ expect(m.bytes.wasmRead).toBe(m.bytes.coreWrite);+ runtime.dispose();+ });++ it('the clock is read a fixed number of times, whatever the entity count', () => {+ // The whole design in one judgment: eleven crossings per entity, two+ // clock reads per frame.+ const runtime = populated(200);+ runtime.observe(true);+ frame(runtime);++ const clock = vi.spyOn(performance, 'now');+ frame(runtime);+ expect(clock.mock.calls.length, 'the observer is timing the crossings').toBe(4);+ runtime.dispose();+ });++ it('not watching costs no clock read at all', () => {+ const runtime = populated(200);+ frame(runtime);++ const clock = vi.spyOn(performance, 'now');+ frame(runtime);+ expect(clock.mock.calls.length).toBe(0);+ expect(runtime.metrics()).toBeNull();+ runtime.dispose();+ });++ it('the record is one object, reused every frame', () => {+ // A frame that allocates to say what a frame cost is measuring itself.+ const runtime = populated(50);+ runtime.observe(true);+ frame(runtime);+ const first = runtime.metrics();+ frame(runtime);++ expect(runtime.metrics(), 'a fresh record per frame').toBe(first);+ expect(first!.frame).toBe(2);+ expect(first!.abi.pose, 'the counts carried over from the last frame').toBe(50);+ runtime.dispose();+ });++ it('aggregated per runtime, never per entity', () => {+ const runtime = populated(100, 10);+ runtime.observe(true);+ frame(runtime);+ const m = runtime.metrics()!;++ expect(m.entities).toBe(100);+ expect(m.residencies, 'ten eras, ten native skeletons').toBe(10);+ expect(Object.keys(m)).toEqual([+ 'frame', 'entities', 'residencies', 'meshBatches', 'vertices', 'indices',+ 'abi', 'bytes', 'time',+ ]);+ runtime.dispose();+ });+});++describe('the window keeps the frame that missed', () => {+ it('reports last, mean, p50, p95 and max — not just an average', () => {+ // Four at 4 and one at 9 average to a budget nobody blew.+ const window = new SpineTimeWindow(120);+ for (const ms of [4, 4, 4, 4, 9]) window.push(ms);++ const stats = window.stats();+ expect(stats.last).toBe(9);+ expect(stats.max).toBe(9);+ expect(stats.p50).toBe(4);+ expect(stats.mean).toBeCloseTo(5, 5);+ });++ it('keeps the last N frames and forgets the rest', () => {+ const window = new SpineTimeWindow(4);+ for (const ms of [99, 1, 1, 1, 1]) window.push(ms);++ expect(window.size).toBe(4);+ expect(window.stats().max, 'a spike outside the window still counted').toBe(1);+ });+});