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.

test(spine): what the 7.6ms inside extractBatches is made of

esengine6df099f03367
diff --git a/sdk/benchmarks/spine-extract-stages.bench.ts b/sdk/benchmarks/spine-extract-stages.bench.ts
new file mode 100644
index 000000000..b6a401256
--- /dev/null
+++ b/sdk/benchmarks/spine-extract-stages.bench.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-extract-stages.bench.ts
+ * @brief What the 7.6 ms inside `extractBatches` is made of.
+ *
+ * @details `spine_getMeshBatchCount` poses and rebuilds every vertex buffer
+ * before it can answer, and that is three quarters of a thousand-entity
+ * frame. This prices the steps of that walk the same way the readback
+ * split was priced — by running it to five depths and subtracting —
+ * rather than by putting a clock inside a loop that runs per slot.
+ *
+ * The staged walk is a separate compile-time instantiation
+ * (SpineRuntimeC.cpp, `renderImpl<STAGE, COUNT>`); the one a frame runs
+ * has no stage check and no counter in it. Every depth costs exactly
+ * one crossing per instance, so the boundary cancels in the differences.
+ */
+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 { 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');
+const SKELETON = process.env.SPINE_STAGE_ASSET ?? 'spineboy-38/spineboy-pro.skel';
+const ATLAS = SKELETON.replace(/[^/]+$/, '').concat(
+ SKELETON.includes('raptor') ? 'raptor.atlas' : SKELETON.includes('coin') ? 'coin.atlas' : 'spineboy.atlas');
+const HAS_ASSETS = existsSync(SPINE38_WASM) && existsSync(resolve(FIXTURES, SKELETON));
+
+const ENTITIES = 1000;
+const FRAMES = 20;
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+const instances: number[] = [];
+
+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, SKELETON)));
+ const atlasText = readFileSync(resolve(FIXTURES, 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);
+ });
+ for (let i = 0, pages = api.getAtlasPageCount(skelHandle); i < pages; i++) {
+ api.setAtlasPageTexture(skelHandle, i, 1, 1024, 1024);
+ }
+ const animation = api.getAnimations(skelHandle ? api.createInstance(skelHandle) : 0).split(',')[0];
+ for (let i = 0; i < ENTITIES; i++) {
+ const id = api.createInstance(skelHandle);
+ api.playAnimation(id, animation || 'walk', 1, 0);
+ api.update(id, 0.1 + i * 0.001);
+ instances.push(id);
+ }
+});
+
+/** One frame's worth of extraction, stopped at `stage`. */
+function pass(stage: number, useCollector: number): void {
+ for (let f = 0; f < FRAMES; f++) {
+ for (const id of instances) api.probeExtract(id, stage, useCollector);
+ }
+}
+
+describe.skipIf(!HAS_ASSETS)(`Spine extraction stages: ${ENTITIES} entities x${FRAMES}`, () => {
+ bench('S0 setup (the crossing and the instance lookup)', () => { pass(0, 0); });
+ bench('S1 + draw-order traversal', () => { pass(1, 0); });
+ bench('S2 + world vertices and tint', () => { pass(2, 0); });
+ bench('S3 + clipping', () => { pass(3, 0); });
+ bench('S4 + emit, counted and dropped', () => { pass(4, 0); });
+ bench('S4c + emit into the frame\'s batch vectors', () => { pass(4, 1); });
+});
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index 9c829671f..38870f4b7 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -58,6 +58,8 @@ export interface SpineWasmModule {
_spine_setTransformConstraintMix(instanceId: number, name: number, rotate: number, x: number, y: number, scaleX: number, scaleY: number, shearY: number): number;
_spine_getPathConstraintMix(instanceId: number, name: number): number;
_spine_setPathConstraintMix(instanceId: number, name: number, position: number, spacing: number, rotate: number, x: number, y: number): number;
+ _spine_probe_extract(instanceId: number, stage: number, useCollector: number): number;
+ _spine_probe_counts(out: number): void;
cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;
UTF8ToString(ptr: number): string;
@@ -116,6 +118,14 @@ export interface SpineWrappedAPI {
setTransformConstraintMix(instanceId: number, name: string, rotate: number, x: number, y: number, scaleX: number, scaleY: number, shearY: number): boolean;
getPathConstraintMix(instanceId: number, name: string): string;
setPathConstraintMix(instanceId: number, name: string, position: number, spacing: number, rotate: number, x: number, y: number): boolean;
+
+ /**
+ * BENCHMARK ONLY — run the extraction to `stage` and report what the walk
+ * did (see benchmarks/spine-extract-stages). Nothing on a frame path calls
+ * these: a frame's crossings are asserted in tests/spine-extract-stages.
+ */
+ probeExtract(instanceId: number, stage: number, useCollector: number): number;
+ probeCounts(out: number): void;
}
export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
@@ -164,6 +174,9 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
setTransformConstraintMix: cw('spine_setTransformConstraintMix', 'number', ['number', 'string', 'number', 'number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['setTransformConstraintMix'],
getPathConstraintMix: cw('spine_getPathConstraintMix', 'string', ['number', 'string']) as SpineWrappedAPI['getPathConstraintMix'],
setPathConstraintMix: cw('spine_setPathConstraintMix', 'number', ['number', 'string', 'number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['setPathConstraintMix'],
+
+ probeExtract: cw('spine_probe_extract', 'number', ['number', 'number', 'number']) as SpineWrappedAPI['probeExtract'],
+ probeCounts: cw('spine_probe_counts', null, ['number']) as SpineWrappedAPI['probeCounts'],
};
}
diff --git a/sdk/tests/spine-extract-stages.test.ts b/sdk/tests/spine-extract-stages.test.ts
new file mode 100644
index 000000000..e2439d686
--- /dev/null
+++ b/sdk/tests/spine-extract-stages.test.ts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-extract-stages.test.ts
+ * @brief The staged walk is the same walk — and it is not on a frame path.
+ *
+ * @details A decomposition is only worth acting on while its stages still add
+ * back to the thing they decompose. So the last stage is held to the
+ * production extraction's own output: same batches, same vertices, same
+ * indices, for the same pose. If the staged walk ever drifts from the
+ * shipped one, the numbers it produces stop meaning anything and this
+ * says so.
+ *
+ * And the instrumentation must stay where it was put: a real frame
+ * crosses into the module eleven times per entity, and none of those
+ * crossings may be a probe.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { WASM_DIR } from './helpers/loadWasm';
+import { wrapSpineModule } from '../src/spine/SpineModuleLoader';
+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';
+import { SpineRuntime } from '../src/spine/SpineRuntime';
+import { withScratch } from '../src/wasm/wasmScratch';
+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');
+const ASSETS = [
+ { name: 'spineboy', skel: 'spineboy-38/spineboy-pro.skel', atlas: 'spineboy-38/spineboy.atlas' },
+ { name: 'raptor', skel: 'raptor-38/raptor-pro.skel', atlas: 'raptor-38/raptor.atlas' },
+ { name: 'coin', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas' },
+];
+const HAS_ASSETS = existsSync(SPINE38_WASM)
+ && ASSETS.every((a) => existsSync(resolve(FIXTURES, a.skel)));
+
+/** The nine counters `spine_probe_counts` writes, in order. */
+const COUNTERS = [
+ 'slots', 'regionAttachments', 'meshAttachments', 'clipStarts', 'clippedEmits',
+ 'verticesGenerated', 'verticesEmitted', 'indicesEmitted', 'emits',
+] as const;
+type Counts = Record<(typeof COUNTERS)[number], number>;
+
+const STAGE_EMIT = 4;
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+
+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);
+
+});
+
+function posed(asset: { skel: string; atlas: string }): { skelHandle: number; instanceId: number } {
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, asset.skel)));
+ const atlasText = readFileSync(resolve(FIXTURES, asset.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);
+ });
+ for (let i = 0, pages = api.getAtlasPageCount(skelHandle); i < pages; i++) {
+ api.setAtlasPageTexture(skelHandle, i, 1, 1024, 1024);
+ }
+ const instanceId = api.createInstance(skelHandle);
+ const first = api.getAnimations(instanceId).split(',')[0];
+ if (first) api.playAnimation(instanceId, first, 1, 0);
+ api.update(instanceId, 0.35);
+ return { skelHandle, instanceId };
+}
+
+function countsOf(): Counts {
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(COUNTERS.length * 4);
+ api.probeCounts(ptr);
+ const out = {} as Counts;
+ COUNTERS.forEach((name, i) => { out[name] = raw.HEAPU32[(ptr >> 2) + i]; });
+ return out;
+ });
+}
+
+/** What the SHIPPED path produced for the pose it is looking at. */
+function production(instanceId: number): { batches: number; vertices: number; indices: number } {
+ const batches = api.getMeshBatchCount(instanceId);
+ let vertices = 0;
+ let indices = 0;
+ for (let b = 0; b < batches; b++) {
+ vertices += api.getMeshBatchVertexCount(instanceId, b);
+ indices += api.getMeshBatchIndexCount(instanceId, b);
+ }
+ return { batches, vertices, indices };
+}
+
+describe.skipIf(!HAS_ASSETS)('the staged walk is the shipped walk', () => {
+ it.each(ASSETS)('$name: the last stage produces what a frame produces', (asset) => {
+ const { instanceId } = posed(asset);
+
+ const shipped = production(instanceId);
+ expect(api.probeExtract(instanceId, STAGE_EMIT, 1)).toBe(1);
+ const counts = countsOf();
+
+ expect(counts.verticesEmitted, 'the staged walk drifted from the shipped one')
+ .toBe(shipped.vertices);
+ expect(counts.indicesEmitted).toBe(shipped.indices);
+ // Emits are attachments; batches are what they were grouped into.
+ expect(counts.emits).toBeGreaterThanOrEqual(shipped.batches);
+ expect(shipped.batches).toBeGreaterThan(0);
+ });
+
+ it.each(ASSETS)('$name: what it counted explains what it produced', (asset) => {
+ const { instanceId } = posed(asset);
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ const c = countsOf();
+
+ expect(c.slots).toBeGreaterThan(0);
+ expect(c.regionAttachments + c.meshAttachments + c.clipStarts).toBeLessThanOrEqual(c.slots);
+ expect(c.emits).toBeLessThanOrEqual(c.regionAttachments + c.meshAttachments);
+ // Clipping can only shrink geometry, never grow it.
+ expect(c.verticesEmitted).toBeLessThanOrEqual(c.verticesGenerated);
+ if (c.clippedEmits === 0) expect(c.verticesEmitted).toBe(c.verticesGenerated);
+ });
+
+ it('a frame makes no probe call at all', () => {
+ // The instrumentation is a separate compile-time instantiation; this is
+ // the half of that claim a test can see.
+ const probed: string[] = [];
+ const cwrap = raw.cwrap.bind(raw);
+ const watched = Object.create(raw) as SpineWasmModule;
+ watched.cwrap = ((name: string, ret: unknown, args: unknown) => {
+ const fn = cwrap(name, ret as never, args as never);
+ return (...called: unknown[]) => {
+ if (name.startsWith('spine_probe')) probed.push(name);
+ return (fn as (...a: unknown[]) => unknown)(...called);
+ };
+ }) as never;
+
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, ASSETS[0].skel)));
+ const atlasText = readFileSync(resolve(FIXTURES, ASSETS[0].atlas), 'utf-8');
+ const era: SpineEraBinding = {
+ id: 'probe#1',
+ value: { skelData, atlasText, isBinary: true, textures: new Map() },
+ retain: () => ({ release: () => {} }),
+ };
+ const runtime = new SpineRuntime('3.8', watched);
+ runtime.loadEntity(1 as Entity, era);
+ runtime.setAnimation(1 as Entity, 'walk', true);
+ runtime.updateAll(1 / 60);
+ runtime.extractAndSubmitMeshes({
+ renderer_submitSkeletalBatchByEntity: () => {},
+ _malloc: () => 0, _free: () => {}, HEAPU8: new Uint8Array(1 << 20),
+ } as never, {} as never);
+
+ expect(probed, 'the probe is on the frame path').toEqual([]);
+ runtime.dispose();
+ });
+
+ it('the geometry each asset carries, for reading', () => {
+ // What normalises the stage timings: a millisecond per frame means
+ // nothing until it is a millisecond per this much geometry.
+ const rows = ASSETS.map((asset) => {
+ const { instanceId } = posed(asset);
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ const c = countsOf();
+ return {
+ asset: asset.name, slots: c.slots,
+ regions: c.regionAttachments, meshes: c.meshAttachments,
+ clips: c.clipStarts, clipped: c.clippedEmits,
+ generated: c.verticesGenerated, emitted: c.verticesEmitted,
+ indices: c.indicesEmitted, batches: api.getMeshBatchCount(instanceId),
+ };
+ });
+ if (process.env.SPINE_STAGE_REPORT) {
+ const keys = Object.keys(rows[0]);
+ const width = (k: string) => Math.max(k.length, ...rows.map((r) => String((r as never)[k]).length));
+ const line = (cells: unknown[]) => cells.map((c, i) => String(c).padStart(width(keys[i]))).join(' ');
+ console.log(line(keys));
+ for (const row of rows) console.log(line(keys.map((k) => (row as never)[k])));
+ }
+ expect(rows).toHaveLength(3);
+ });
+});
diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hpp
index edf196d7b..6f5478822 100644
--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp
+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp
@@ -81,4 +81,12 @@ int spine_runtimeVersion();
// buffer is the module's own vector, so only the module can say how much is live.
size_t spine_eventBufferBytes();
+// BENCHMARK ONLY, never on a frame path — the extraction run to `stage`
+// (es::spine::RenderStage). `useCollector` stores the triangles as a frame does
+// or counts and drops them: the one way to price the buffers apart from the work.
+int spine_probe_extract(int instanceId, int stage, int useCollector);
+
+// The nine counters of the last probe run, into as many u32 slots.
+void spine_probe_counts(uint32_t* out);
+
} // extern "C"
diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
index f5836e670..c6fb905ed 100644
--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
@@ -91,6 +91,16 @@ void collectEvent(const Event& event) {
}
/// Re-poses `instanceId` and refills the batch list the getters below read.
+/** Takes what a stage emitted and keeps none of it: the walk without the cost of
+ * storing its output. Benchmark only — see spine_probe_extract. */
+struct CountingSink final : es::skeletal::TriangleSink {
+ void emit(const float*, const float*, int, const std::uint16_t*, int,
+ std::uint32_t, int, const float[4]) override {}
+};
+
+/** The last probe run's counts. Benchmark only; a frame never writes it. */
+es::spine::ProbeCounts g_probeCounts{};
+
void extractBatches(int instanceId) {
g_ctx.batches.clear();
auto* instance = g_ctx.instanceOf(instanceId);
@@ -253,6 +263,44 @@ void spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr,
// Mesh Extraction
// =============================================================================
+/**
+ * BENCHMARK ONLY — the extraction run to `stage`.
+ *
+ * `useCollector` 0 counts the emitted triangles and drops them, 1 stores them as
+ * a frame does; the difference at the last stage is what the collector's vectors
+ * cost. Not on any frame path: the staged walk is its own instantiation.
+ */
+EMSCRIPTEN_KEEPALIVE
+int spine_probe_extract(int instanceId, int stage, int useCollector) {
+ g_probeCounts = es::spine::ProbeCounts{};
+ auto* instance = g_ctx.instanceOf(instanceId);
+ if (!instance) return 0;
+ if (useCollector) {
+ g_ctx.batches.clear();
+ es::skeletal::BatchCollector collector(g_ctx.batches);
+ return es::spine::renderStage(instance, collector, g_ctx.clippingEnabled,
+ stage, &g_probeCounts) ? 1 : 0;
+ }
+ CountingSink sink;
+ return es::spine::renderStage(instance, sink, g_ctx.clippingEnabled,
+ stage, &g_probeCounts) ? 1 : 0;
+}
+
+/** The counts of the last {@link spine_probe_extract}, into nine u32 slots. */
+EMSCRIPTEN_KEEPALIVE
+void spine_probe_counts(std::uint32_t* out) {
+ if (!out) return;
+ out[0] = g_probeCounts.slots;
+ out[1] = g_probeCounts.regionAttachments;
+ out[2] = g_probeCounts.meshAttachments;
+ out[3] = g_probeCounts.clipStarts;
+ out[4] = g_probeCounts.clippedEmits;
+ out[5] = g_probeCounts.verticesGenerated;
+ out[6] = g_probeCounts.verticesEmitted;
+ out[7] = g_probeCounts.indicesEmitted;
+ out[8] = g_probeCounts.emits;
+}
+
EMSCRIPTEN_KEEPALIVE
int spine_getMeshBatchCount(int instanceId) {
extractBatches(instanceId);
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
index cd8687835..605287ce3 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
@@ -216,6 +216,39 @@ bool setSkeletonColor(Instance* instance, float r, float g, float b, float a);
/** Poses the skeleton's attachments into `sink`, applying clip regions when asked. */
void render(Instance* instance, TriangleSink& sink, bool clipping);
+/** How far {@link renderStage} runs. Each includes the ones before it, so what a
+ * stage costs is the difference between two runs — the only way to price a step
+ * of this walk without a clock inside it. */
+enum RenderStage {
+ STAGE_SETUP = 0, ///< The instance and the clipper; the loop does not run.
+ STAGE_TRAVERSE = 1, ///< Walk the draw order, resolving what each slot holds.
+ STAGE_VERTICES = 2, ///< …and compute world vertices and tint.
+ STAGE_CLIP = 3, ///< …and clip them where a clip region is open.
+ STAGE_EMIT = 4, ///< …and hand them to the sink. The full extraction.
+};
+
+/** What the walk did, so a time can be explained rather than only reported. */
+struct ProbeCounts {
+ std::uint32_t slots;
+ std::uint32_t regionAttachments;
+ std::uint32_t meshAttachments;
+ std::uint32_t clipStarts;
+ std::uint32_t clippedEmits;
+ std::uint32_t verticesGenerated;
+ std::uint32_t verticesEmitted;
+ std::uint32_t indicesEmitted;
+ std::uint32_t emits;
+};
+
+/**
+ * BENCHMARK ONLY — the same walk as {@link render}, stopped at `stage`, so its
+ * cost can be decomposed without a clock inside the loop being decomposed.
+ * False where a backend has no instrumented walk (2.1, spine-cpp), so a
+ * measurement cannot quietly report zeros for one.
+ */
+bool renderStage(Instance* instance, TriangleSink& sink, bool clipping,
+ int stage, ProbeCounts* counts);
+
/** 21 / 38 / 41 / 42 / 43 — whatever `spine_runtimeVersion()` should report. */
int version();
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
index 6bead368e..800205654 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
@@ -544,6 +544,13 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
}
}
+/** Not instrumented: the cost decomposition is measured on the spine-c walk
+ * (3.8 / 4.1 / 4.2). False rather than zeros, so a measurement cannot report
+ * this backend as free. */
+bool renderStage(Instance*, TriangleSink&, bool, int, ProbeCounts*) {
+ return false;
+}
+
int version() {
return ES_SPINE_VERSION;
}
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
index d747af7a7..00416aa9c 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
@@ -562,17 +562,19 @@ namespace {
* region when there is one. Clipping replaces the triangle set with the polygon
* intersection, so it can only shrink the geometry, never grow it.
*/
+template <int STAGE, bool COUNT>
void emit(TriangleSink& sink, bool clipping,
float* positions, int vertexCount, float* uvs,
unsigned short* triangles, int triangleCount,
- uint32_t texture, int blendMode, const float rgba[4]) {
+ uint32_t texture, int blendMode, const float rgba[4],
+ ProbeCounts* counts) {
float* outPositions = positions;
float* outUVs = uvs;
unsigned short* outTriangles = triangles;
int outVertices = vertexCount;
int outTriangleCount = triangleCount;
- if (clipping && spSkeletonClipping_isClipping(g_clipper)) {
+ if (STAGE >= STAGE_CLIP && clipping && spSkeletonClipping_isClipping(g_clipper)) {
spSkeletonClipping_clipTriangles(g_clipper, positions, vertexCount * 2,
triangles, triangleCount, uvs, 2);
outPositions = g_clipper->clippedVertices->items;
@@ -580,23 +582,38 @@ void emit(TriangleSink& sink, bool clipping,
outUVs = g_clipper->clippedUVs->items;
outTriangles = g_clipper->clippedTriangles->items;
outTriangleCount = g_clipper->clippedTriangles->size;
+ if constexpr (COUNT) counts->clippedEmits++;
}
if (outVertices == 0 || outTriangleCount == 0) return;
+ if constexpr (COUNT) {
+ counts->emits++;
+ counts->verticesEmitted += static_cast<std::uint32_t>(outVertices);
+ counts->indicesEmitted += static_cast<std::uint32_t>(outTriangleCount);
+ }
+ if constexpr (STAGE < STAGE_EMIT) return;
sink.emit(outPositions, outUVs, outVertices, outTriangles, outTriangleCount,
texture, blendMode, rgba);
}
} // namespace
-void render(Instance* instance, TriangleSink& sink, bool clipping) {
+/**
+ * The walk, once. `STAGE` and `COUNT` are compile-time: the shipped `render`
+ * instantiates it with the full stage and no counting, so every stage check and
+ * every counter below is gone before the module is linked.
+ */
+template <int STAGE, bool COUNT>
+void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCounts* counts) {
if (!instance) return;
if (!g_clipper) g_clipper = spSkeletonClipping_create();
+ if constexpr (STAGE < STAGE_TRAVERSE) return;
spSkeleton* skeleton = instance->skeleton;
const spColor& skeletonColor = skeleton->color;
for (int i = 0; i < skeleton->slotsCount; ++i) {
+ if constexpr (COUNT) counts->slots++;
spSlot* slot = skeleton->drawOrder[i];
if (!slot) continue;
@@ -605,7 +622,8 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
// A clipping attachment opens a region that runs until its end slot; it
// draws nothing itself.
if (attachment && attachment->type == SP_ATTACHMENT_CLIPPING) {
- if (clipping) {
+ if constexpr (COUNT) counts->clipStarts++;
+ if (clipping && STAGE >= STAGE_CLIP) {
spSkeletonClipping_clipStart(g_clipper, slot,
reinterpret_cast<spClippingAttachment*>(attachment));
}
@@ -622,6 +640,9 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
const int blendMode = blendModeOf(slot);
if (attachment->type == SP_ATTACHMENT_REGION) {
+ if constexpr (COUNT) counts->regionAttachments++;
+ // Nothing below this is what a traversal costs.
+ if constexpr (STAGE < STAGE_VERTICES) continue;
auto* region = reinterpret_cast<spRegionAttachment*>(attachment);
g_worldVertices.resize(8);
#if ES_SPINE_VERSION < 40
@@ -651,11 +672,15 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
};
premultiplyTint(rgba, pma);
+ if constexpr (COUNT) counts->verticesGenerated += 4;
static unsigned short quad[6] = {0, 1, 2, 2, 3, 0};
- emit(sink, clipping, g_worldVertices.data(), 4, region->uvs, quad, 6,
- texture, blendForPage(blendMode, pma), rgba);
+ emit<STAGE, COUNT>(sink, clipping, g_worldVertices.data(), 4, region->uvs,
+ quad, 6, texture, blendForPage(blendMode, pma), rgba,
+ counts);
}
} else if (attachment->type == SP_ATTACHMENT_MESH) {
+ if constexpr (COUNT) counts->meshAttachments++;
+ if constexpr (STAGE < STAGE_VERTICES) continue;
auto* mesh = reinterpret_cast<spMeshAttachment*>(attachment);
const int length = SUPER(mesh)->worldVerticesLength;
g_worldVertices.resize(length);
@@ -680,19 +705,37 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
};
premultiplyTint(rgba, pma);
- emit(sink, clipping, g_worldVertices.data(), length / 2, mesh->uvs,
- mesh->triangles, mesh->trianglesCount,
- texture, blendForPage(blendMode, pma), rgba);
+ if constexpr (COUNT) counts->verticesGenerated += length / 2;
+ emit<STAGE, COUNT>(sink, clipping, g_worldVertices.data(), length / 2,
+ mesh->uvs, mesh->triangles, mesh->trianglesCount,
+ texture, blendForPage(blendMode, pma), rgba, counts);
}
}
}
// Closes the region when this slot is the clip's end slot; a cheap no-op
// otherwise, which is why every non-clip slot passes through here.
- if (clipping) spSkeletonClipping_clipEnd(g_clipper, slot);
+ if (clipping && STAGE >= STAGE_CLIP) spSkeletonClipping_clipEnd(g_clipper, slot);
}
- if (clipping) spSkeletonClipping_clipEnd2(g_clipper);
+ if (clipping && STAGE >= STAGE_CLIP) spSkeletonClipping_clipEnd2(g_clipper);
+}
+
+void render(Instance* instance, TriangleSink& sink, bool clipping) {
+ renderImpl<STAGE_EMIT, false>(instance, sink, clipping, nullptr);
+}
+
+bool renderStage(Instance* instance, TriangleSink& sink, bool clipping,
+ int stage, ProbeCounts* counts) {
+ switch (stage) {
+ case STAGE_SETUP: renderImpl<STAGE_SETUP, true>(instance, sink, clipping, counts); break;
+ case STAGE_TRAVERSE: renderImpl<STAGE_TRAVERSE, true>(instance, sink, clipping, counts); break;
+ case STAGE_VERTICES: renderImpl<STAGE_VERTICES, true>(instance, sink, clipping, counts); break;
+ case STAGE_CLIP: renderImpl<STAGE_CLIP, true>(instance, sink, clipping, counts); break;
+ case STAGE_EMIT: renderImpl<STAGE_EMIT, true>(instance, sink, clipping, counts); break;
+ default: return false;
+ }
+ return true;
}
int version() {
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
index 81366c0de..e48836731 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
@@ -527,6 +527,13 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
}
}
+/** Not instrumented: the cost decomposition is measured on the spine-c walk
+ * (3.8 / 4.1 / 4.2). False rather than zeros, so a measurement cannot report
+ * this backend as free. */
+bool renderStage(Instance*, TriangleSink&, bool, int, ProbeCounts*) {
+ return false;
+}
+
int version() {
return ES_SPINE_VERSION;
}