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): the 2µs before a triangle is cut is a quadratic triangulation

esenginef044028e0b75
diff --git a/sdk/benchmarks/spine-clip-start.bench.ts b/sdk/benchmarks/spine-clip-start.bench.ts
new file mode 100644
index 000000000..13f86df0f
--- /dev/null
+++ b/sdk/benchmarks/spine-clip-start.bench.ts
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-clip-start.bench.ts
+ * @brief Why opening a clip region costs 0.4 µs at sixteen vertices and 2.0 at
+ * thirty-nine.
+ *
+ * @details Half of coin's clipping is spent before a triangle is cut, and the
+ * growth is not linear in the vertex count. `clipStart` is a sequence
+ * of separable calls — world vertices, winding, triangulate, decompose,
+ * finish each piece — so this runs it to six depths and subtracts,
+ * which prices a step without a clock inside the step.
+ *
+ * The convex ladder is the one that decides it. If a 39-vertex polygon
+ * that decomposes to ONE piece is already superlinear, the answer is in
+ * preparation, not in the concavity everyone would blame. coin is here
+ * as the witness that any of it matters on a shipped asset, not as a
+ * point to fit the curve through: it has one polygon and one pose.
+ *
+ * `SPINE_CLIP_START_REPORT=1` prints the counters each row ran on, and
+ * tests/spine-clip-start holds the last depth to what the shipped
+ * `clipStart` produces — the ladder had to transcribe spine's static
+ * `_makeClockwise`, and the opposite winding would measure another
+ * algorithm without saying so.
+ *
+ * What it answered, µs per open (min of two runs):
+ *
+ * case world wind triangulate decomp pieces total
+ * convex 4 0.004 0.003 0.021 0.029 0.006 0.062
+ * convex 8 0.006 0.004 0.082 0.048 0.007 0.150
+ * convex 16 0.010 0.008 0.270 0.085 0.002 0.387
+ * convex 39 0.009 0.027 1.724 0.192 0.051 2.007
+ * concave 16 0.011 0.009 0.318 0.305 0.028 0.680
+ * concave 39 0.010 0.030 2.011 1.649 0.066 3.733
+ * coin 0.009 0.024 1.732 0.217 -0.036 2.015
+ *
+ * Triangulating the polygon is 86% of it at thirty-nine vertices, and
+ * it is quadratic: 1.05 to 1.33 ns per n² across the whole ladder,
+ * convex and concave alike. Computing the world vertices — the step a
+ * deforming clip attachment would make expensive — is 0.4%.
+ *
+ * The convex ladder is what makes that actionable. A 39-vertex polygon
+ * that decomposes to ONE piece still pays 1.72 µs to be ear-clipped
+ * into 37 triangles, and the only consumer of those triangles is a
+ * decomposition whose answer is the polygon itself.
+ *
+ * Concavity's share of the OPEN is the decomposition, not the
+ * triangulation: 0.085 -> 0.305 µs at sixteen vertices, 0.192 -> 1.649
+ * at thirty-nine. So a concave polygon pays at both ends — here, and
+ * again per triangle through the effective edges it multiplies.
+ *
+ * coin lands on the synthetic 39-gon to within 0.4%, which is what says
+ * none of this is an artefact of authored shapes.
+ */
+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';
+import { syntheticSkeleton } from '../tests/helpers/syntheticSpine';
+import type { SyntheticOptions } from '../tests/helpers/syntheticSpine';
+
+const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');
+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');
+const FIXTURES = resolve(__dirname, 'fixtures/spine');
+const HAS_WASM = existsSync(SPINE38_WASM);
+
+const OPENS = 2000;
+const STAGES = [
+ { depth: 0, label: 'C0 scratch sized' },
+ { depth: 1, label: 'C1 + world vertices' },
+ { depth: 2, label: 'C2 + winding' },
+ { depth: 3, label: 'C3 + triangulate' },
+ { depth: 4, label: 'C4 + decompose' },
+ { depth: 5, label: 'C5 + finish each piece' },
+ { depth: 6, label: 'C6 + publish bounds' },
+] as const;
+
+/** The polygon is the whole experiment; the strip it clips is incidental. */
+const POLYGON = (polygonVertices: number, concave = false): SyntheticOptions =>
+ ({ quads: 4, relation: 'inside', polygonVertices, concave });
+
+const CASES: Array<{ name: string; options?: SyntheticOptions; skel?: string; atlas?: string }> = [
+ { name: 'convex 4', options: POLYGON(4) },
+ { name: 'convex 8', options: POLYGON(8) },
+ { name: 'convex 16', options: POLYGON(16) },
+ { name: 'convex 39', options: POLYGON(39) },
+ { name: 'concave 8', options: POLYGON(8, true) },
+ { name: 'concave 16', options: POLYGON(16, true) },
+ { name: 'concave 39', options: POLYGON(39, true) },
+ { name: 'coin', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas' },
+];
+
+const COUNTERS = ['rawVertices', 'triangles', 'pieces', 'effectiveEdges', 'scratch'] as const;
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+const instances = new Map<string, number>();
+
+beforeAll(async () => {
+ if (!HAS_WASM) 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);
+
+ for (const test of CASES) {
+ const real = test.skel !== undefined;
+ if (real && !existsSync(resolve(FIXTURES, test.skel!))) continue;
+ const skelData = real
+ ? new Uint8Array(readFileSync(resolve(FIXTURES, test.skel!)))
+ : new TextEncoder().encode(syntheticSkeleton(test.options!).json);
+ const atlas = real
+ ? readFileSync(resolve(FIXTURES, test.atlas!), 'utf-8')
+ : syntheticSkeleton(test.options!).atlas;
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlas, atlas.length, real);
+ });
+ if (handle < 0) throw new Error(`${test.name}: ${api.getLastError()}`);
+ for (let i = 0, pages = api.getAtlasPageCount(handle); i < pages; i++) {
+ api.setAtlasPageTexture(handle, i, 1, 2048, 2048);
+ }
+ const instanceId = api.createInstance(handle);
+ if (real) {
+ const [first] = JSON.parse(api.getAnimations(instanceId)) as string[];
+ if (!api.playAnimation(instanceId, first, true, 0)) throw new Error(`${test.name}: no "${first}"`);
+ }
+ api.update(instanceId, real ? 0.35 : 0);
+ if (!api.probeClipStart(instanceId, 6)) throw new Error(`${test.name}: no clip region`);
+ instances.set(test.name, instanceId);
+ }
+
+ if (process.env.SPINE_CLIP_START_REPORT) report();
+});
+
+function countsOf(): Record<string, number> {
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(9 * 4);
+ api.probeClipStartCounts(ptr);
+ const out: Record<string, number> = {};
+ COUNTERS.forEach((name, i) => { out[name] = raw.HEAPU32[(ptr >> 2) + i]; });
+ return out;
+ });
+}
+
+function report(): void {
+ const rows = [...instances.keys()].map((name) => {
+ api.probeClipStart(instances.get(name)!, 6);
+ const c = countsOf();
+ return {
+ case: name, ...c,
+ edgesPerVertex: (c.effectiveEdges / Math.max(1, c.rawVertices)).toFixed(2),
+ };
+ });
+ 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])));
+}
+
+function pass(name: string, depth: number): void {
+ const instanceId = instances.get(name)!;
+ for (let i = 0; i < OPENS; i++) api.probeClipStart(instanceId, depth);
+}
+
+describe.skipIf(!HAS_WASM)(`Spine clip-start stages: x${OPENS} opens`, () => {
+ for (const test of CASES) {
+ for (const stage of STAGES) {
+ bench(`${stage.label} — ${test.name}`, () => { pass(test.name, stage.depth); });
+ }
+ }
+});
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index 0dc6cc623..bfa334592 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -62,6 +62,8 @@ export interface SpineWasmModule {
_spine_probe_counts(out: number): void;
_spine_probe_clip_storage(out: number): void;
_spine_clipBudget(instanceId: number, out: number): number;
+ _spine_probe_clip_start(instanceId: number, stage: number): number;
+ _spine_probe_clip_start_counts(out: number): void;
_spine_probe_storage(out: number): void;
_spine_probe_pose(instanceId: number, dt: number, stage: number): number;
_spine_probe_pose_counts(out: number): void;
@@ -132,6 +134,8 @@ export interface SpineWrappedAPI {
probeExtract(instanceId: number, stage: number, useCollector: number): number;
probeCounts(out: number): void;
probeClipStorage(out: number): void;
+ probeClipStart(instanceId: number, stage: number): number;
+ probeClipStartCounts(out: number): void;
/**
* What one instance's clipping costs this pose, in work rather than time.
@@ -193,6 +197,8 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
probeExtract: cw('spine_probe_extract', 'number', ['number', 'number', 'number']) as SpineWrappedAPI['probeExtract'],
probeCounts: cw('spine_probe_counts', null, ['number']) as SpineWrappedAPI['probeCounts'],
probeClipStorage: cw('spine_probe_clip_storage', null, ['number']) as SpineWrappedAPI['probeClipStorage'],
+ probeClipStart: cw('spine_probe_clip_start', 'number', ['number', 'number']) as SpineWrappedAPI['probeClipStart'],
+ probeClipStartCounts: cw('spine_probe_clip_start_counts', null, ['number']) as SpineWrappedAPI['probeClipStartCounts'],
clipBudget: cw('spine_clipBudget', 'number', ['number', 'number']) as SpineWrappedAPI['clipBudget'],
probeStorage: cw('spine_probe_storage', null, ['number']) as SpineWrappedAPI['probeStorage'],
probePose: cw('spine_probe_pose', 'number', ['number', 'number', 'number']) as SpineWrappedAPI['probePose'],
diff --git a/sdk/tests/spine-clip-start.test.ts b/sdk/tests/spine-clip-start.test.ts
new file mode 100644
index 000000000..4efaab6df
--- /dev/null
+++ b/sdk/tests/spine-clip-start.test.ts
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-clip-start.test.ts
+ * @brief The staged open is the shipped open, on the shapes it says it is.
+ *
+ * @details The ladder in benchmarks/spine-clip-start runs the same sequence the
+ * shipped `clipStart` runs, one call at a time — and it had to
+ * transcribe spine's `_makeClockwise`, which is static there. A wrong
+ * transcription would hand the triangulator the opposite winding and
+ * quietly measure a different algorithm, so the full depth is held to
+ * what the shipped path produces.
+ *
+ * The rest is the axis: a benchmark that says "39 vertices" while
+ * running a four-vertex polygon would fit a curve through nothing.
+ */
+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 type { SpineEraBinding } from '../src/spine/prepareSpine';
+import type { Entity } from '../src/types';
+import { withScratch } from '../src/wasm/wasmScratch';
+import { syntheticSkeleton } from './helpers/syntheticSpine';
+import type { SyntheticOptions } from './helpers/syntheticSpine';
+
+const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');
+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');
+const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');
+const HAS_WASM = existsSync(SPINE38_WASM);
+
+const CLIP_START_FULL = 6;
+const STAGE_EMIT = 5;
+/** The five counts `spine_probe_clip_start_counts` writes before the bounds. */
+const COUNTERS = ['rawVertices', 'triangles', 'pieces', 'effectiveEdges', 'scratch'] as const;
+type Counts = Record<(typeof COUNTERS)[number], number>;
+/** Where `clipPolygons` and `clipPolygonEdges` sit in the extraction's counters. */
+const PRODUCTION_PIECES = 9;
+const PRODUCTION_EDGES = 11;
+
+const POLYGON = (polygonVertices: number, concave = false): SyntheticOptions =>
+ ({ quads: 4, relation: 'inside', polygonVertices, concave });
+
+let raw: SpineWasmModule;
+let api: SpineWrappedAPI;
+
+beforeAll(async () => {
+ if (!HAS_WASM) 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 instanceOf(options: SyntheticOptions): number {
+ const { json, atlas } = syntheticSkeleton(options);
+ const skelData = new TextEncoder().encode(json);
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlas, atlas.length, false);
+ });
+ if (handle < 0) throw new Error(api.getLastError());
+ api.setAtlasPageTexture(handle, 0, 1, 64, 64);
+ const instanceId = api.createInstance(handle);
+ api.update(instanceId, 0);
+ return instanceId;
+}
+
+function stagedOpen(instanceId: number, stage = CLIP_START_FULL): Counts & { bounds: number[] } {
+ expect(api.probeClipStart(instanceId, stage), 'the instance has no clip region').toBe(1);
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(9 * 4);
+ api.probeClipStartCounts(ptr);
+ const out = {} as Counts & { bounds: number[] };
+ COUNTERS.forEach((name, i) => { out[name] = raw.HEAPU32[(ptr >> 2) + i]; });
+ out.bounds = [5, 6, 7, 8].map((i) => raw.HEAPF32[(ptr >> 2) + i]);
+ return out;
+ });
+}
+
+/** What the SHIPPED clipStart made of the same polygon. */
+function production(instanceId: number): { pieces: number; effectiveEdges: number } {
+ api.probeExtract(instanceId, STAGE_EMIT, 1);
+ return withScratch(raw, (alloc) => {
+ const ptr = alloc(22 * 4);
+ api.probeCounts(ptr);
+ return {
+ pieces: raw.HEAPU32[(ptr >> 2) + PRODUCTION_PIECES],
+ effectiveEdges: raw.HEAPU32[(ptr >> 2) + PRODUCTION_EDGES],
+ };
+ });
+}
+
+const SHAPES = [
+ { name: 'convex 4', options: POLYGON(4), vertices: 4, pieces: 1 },
+ { name: 'convex 8', options: POLYGON(8), vertices: 8, pieces: 1 },
+ { name: 'convex 16', options: POLYGON(16), vertices: 16, pieces: 1 },
+ { name: 'convex 39', options: POLYGON(39), vertices: 39, pieces: 1 },
+ { name: 'concave 8', options: POLYGON(8, true), vertices: 8, pieces: 3 },
+ { name: 'concave 16', options: POLYGON(16, true), vertices: 16, pieces: 9 },
+ { name: 'concave 39', options: POLYGON(39, true), vertices: 39, pieces: 27 },
+];
+
+describe.skipIf(!HAS_WASM)('the staged open is the shipped open', () => {
+ it.each(SHAPES)('$name: the last depth is what clipStart produces', (shape) => {
+ const instanceId = instanceOf(shape.options);
+ const staged = stagedOpen(instanceId);
+ const shipped = production(instanceId);
+
+ expect(staged.pieces, 'the ladder decomposed to a different shape').toBe(shipped.pieces);
+ expect(staged.effectiveEdges).toBe(shipped.effectiveEdges);
+ expect(staged.bounds[2]).toBeGreaterThan(staged.bounds[0]);
+ expect(staged.bounds[3]).toBeGreaterThan(staged.bounds[1]);
+ });
+
+ it.each(SHAPES)('$name: the ladder ran the polygon it says it ran', (shape) => {
+ // A curve fitted through a benchmark that quietly ran a four-vertex
+ // polygon for every row would look just as convincing.
+ const staged = stagedOpen(instanceOf(shape.options));
+ expect(staged.rawVertices).toBe(shape.vertices);
+ expect(staged.triangles, 'an n-gon triangulates into n-2').toBe(shape.vertices - 2);
+ expect(staged.pieces).toBe(shape.pieces);
+ });
+
+ it('the same authored count decomposes differently when it is concave', () => {
+ const convex = stagedOpen(instanceOf(POLYGON(16)));
+ const concave = stagedOpen(instanceOf(POLYGON(16, true)));
+
+ expect(convex.rawVertices).toBe(concave.rawVertices);
+ expect(convex.triangles, 'both triangulate into the same count').toBe(concave.triangles);
+ expect(convex.pieces).toBe(1);
+ expect(concave.pieces).toBeGreaterThan(1);
+ expect(concave.effectiveEdges).toBeGreaterThan(convex.effectiveEdges);
+ });
+
+ it('coin opens the same way a synthetic 39-gon does', () => {
+ // The witness that any of this reaches a shipped asset — and the reason
+ // the curve is fitted on the synthetic ladder rather than on coin: coin
+ // is one polygon at one pose, which is a point, not a slope.
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'coin-38/coin-pro.skel')));
+ const atlasText = readFileSync(resolve(FIXTURES, 'coin-38/coin.atlas'), 'utf-8');
+ const handle = withScratch(raw, (alloc) => {
+ const ptr = alloc(skelData.length);
+ raw.HEAPU8.set(skelData, ptr);
+ return api.loadSkeleton(ptr, skelData.length, atlasText, atlasText.length, true);
+ });
+ api.setAtlasPageTexture(handle, 0, 1, 1024, 1024);
+ const instanceId = api.createInstance(handle);
+ api.playAnimation(instanceId, 'animation', true, 0);
+ api.update(instanceId, 0.35);
+
+ const coin = stagedOpen(instanceId);
+ expect(coin.rawVertices).toBe(39);
+ expect(coin.pieces, 'coin is concave').toBe(1);
+ expect(coin.effectiveEdges).toBe(40);
+ expect(coin).toMatchObject(
+ { rawVertices: 39, triangles: 37, pieces: 1, effectiveEdges: 40 });
+ });
+
+ it('a frame opens no clip region through the probe', () => {
+ // The ladder and the budget both pose; neither may be on a frame path.
+ 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') || name === 'spine_clipBudget') probed.push(name);
+ return (fn as (...a: unknown[]) => unknown)(...called);
+ };
+ }) as never;
+
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'coin-38/coin-pro.skel')));
+ const atlasText = readFileSync(resolve(FIXTURES, 'coin-38/coin.atlas'), 'utf-8');
+ const era: SpineEraBinding = {
+ id: 'clip-start#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, 'animation', true);
+ runtime.updateAll(1 / 60);
+ runtime.extractAndSubmitMeshes({
+ renderer_submitSkeletalBatchByEntity: () => {},
+ _malloc: () => 0, _free: () => {}, HEAPU8: new Uint8Array(1 << 20),
+ } as never, {} as never);
+
+ expect(probed, 'a diagnostic is on the frame path').toEqual([]);
+ runtime.dispose();
+ });
+});
diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hpp
index c16fd81d1..f4ad1df18 100644
--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp
+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp
@@ -89,6 +89,12 @@ int spine_probe_extract(int instanceId, int stage, int useCollector);
// The twenty-two counters of the last probe run, into as many u32 slots.
void spine_probe_counts(uint32_t* out);
+// BENCHMARK ONLY — open the first clip region to `stage` (es::spine::ClipStartStage).
+int spine_probe_clip_start(int instanceId, int stage);
+
+// Five counts then the region's bounds as four floats, into nine u32 slots.
+void spine_probe_clip_start_counts(uint32_t* out);
+
// What one instance's clipping costs this pose, in work rather than time, into
// eleven u32 slots. Poses and extracts; zero where the runtime cannot count.
int spine_clipBudget(int instanceId, uint32_t* out);
diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
index 09c140bec..dc0251213 100644
--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
@@ -317,6 +317,38 @@ void spine_probe_counts(std::uint32_t* out) {
out[21] = g_probeCounts.clipOutputVertices;
}
+/** The last staged open's counts. Benchmark only; a frame never writes it. */
+es::spine::ClipStartCounts g_clipStartCounts{};
+
+/**
+ * BENCHMARK ONLY — open the instance's first clip region to `stage`
+ * (es::spine::ClipStartStage), so what a 39-vertex polygon costs before a single
+ * triangle is cut can be priced without a clock inside the preparation.
+ */
+EMSCRIPTEN_KEEPALIVE
+int spine_probe_clip_start(int instanceId, int stage) {
+ g_clipStartCounts = es::spine::ClipStartCounts{};
+ auto* instance = g_ctx.instanceOf(instanceId);
+ if (!instance) return 0;
+ const bool ran = es::spine::clipStartStage(instance, stage, &g_clipStartCounts);
+ return ran ? 1 : 0;
+}
+
+/** Nine slots: five counts, then the region's bounds as four floats. */
+EMSCRIPTEN_KEEPALIVE
+void spine_probe_clip_start_counts(std::uint32_t* out) {
+ if (!out) return;
+ out[0] = g_clipStartCounts.rawVertices;
+ out[1] = g_clipStartCounts.triangulationTriangles;
+ out[2] = g_clipStartCounts.pieces;
+ out[3] = g_clipStartCounts.effectiveEdges;
+ out[4] = g_clipStartCounts.triangulatorScratch;
+ std::memcpy(out + 5, &g_clipStartCounts.minX, sizeof(float));
+ std::memcpy(out + 6, &g_clipStartCounts.minY, sizeof(float));
+ std::memcpy(out + 7, &g_clipStartCounts.maxX, sizeof(float));
+ std::memcpy(out + 8, &g_clipStartCounts.maxY, sizeof(float));
+}
+
/**
* What one instance's clipping costs THIS pose, in work not time, into eleven
* u32 slots: the polygon as authored, what it decomposed into, the triangles
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
index 8cd9316d2..37c827cc3 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
@@ -282,6 +282,37 @@ struct ClipStorage {
/** False where a backend has no clipper of its own to report on. */
bool clipStorage(ClipStorage* out);
+/** How far {@link clipStartStage} runs. The shipped `clipStart` is a sequence of
+ * separable calls, and each depth here is a prefix of it: nothing later feeds
+ * anything earlier, so stopping short prices a step without a clock inside it. */
+enum ClipStartStage {
+ CLIP_START_RESET = 0, ///< The scratch sized for the polygon.
+ CLIP_START_WORLD = 1, ///< …and its world vertices computed.
+ CLIP_START_WINDING = 2, ///< …made clockwise.
+ CLIP_START_TRIANGULATE = 3, ///< …triangulated.
+ CLIP_START_DECOMPOSE = 4, ///< …decomposed into convex pieces.
+ CLIP_START_PIECES = 5, ///< …each piece wound and closed. spine ends here.
+ CLIP_START_PUBLISH = 6, ///< …and this module's bounds and edges captured.
+};
+
+/** What opening a region had to do, so its time can be explained. */
+struct ClipStartCounts {
+ std::uint32_t rawVertices;
+ std::uint32_t triangulationTriangles;
+ std::uint32_t pieces;
+ std::uint32_t effectiveEdges;
+ /// The triangulator's own arrays, so a second storage problem inside the
+ /// preparation cannot hide the way the collector's did.
+ std::uint32_t triangulatorScratch;
+ float minX, minY, maxX, maxY;
+};
+
+/**
+ * BENCHMARK ONLY — open the instance's first clip region to `stage`. False when
+ * the instance has no clipping attachment or the backend has no staged open.
+ */
+bool clipStartStage(Instance* instance, int stage, ClipStartCounts* counts);
+
/**
* The whole walk with its counters on — what a diagnostic asks for, as opposed
* to {@link renderStage}, which stops short and is for pricing steps. False
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
index 391bb7f09..e0f3fd99c 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
@@ -565,6 +565,10 @@ bool renderCounted(Instance*, TriangleSink&, bool, ProbeCounts*) {
return false;
}
+bool clipStartStage(Instance*, int, ClipStartCounts*) {
+ 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 d0a915b80..fb570123b 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
@@ -927,6 +927,116 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {
renderImpl<STAGE_EMIT, false>(instance, sink, clipping, nullptr);
}
+namespace {
+
+/**
+ * spine's own `_makeClockwise`, which is static there, transcribed so the ladder
+ * below can stop before it. The full depth is held to the shipped clipStart's
+ * result, which is what says this stayed a transcription.
+ */
+void makeClockwise(spFloatArray* polygon) {
+ float* vertices = polygon->items;
+ const int length = polygon->size;
+ float area = vertices[length - 2] * vertices[1] - vertices[0] * vertices[length - 1];
+ for (int i = 0, n = length - 3; i < n; i += 2) {
+ const float p1x = vertices[i], p1y = vertices[i + 1];
+ const float p2x = vertices[i + 2], p2y = vertices[i + 3];
+ area += p1x * p2y - p2x * p1y;
+ }
+ if (area < 0) return;
+ for (int i = 0, lastX = length - 2, n = length >> 1; i < n; i += 2) {
+ const float x = vertices[i], y = vertices[i + 1];
+ const int other = lastX - i;
+ vertices[i] = vertices[other];
+ vertices[i + 1] = vertices[other + 1];
+ vertices[other] = x;
+ vertices[other + 1] = y;
+ }
+}
+
+/// The first clip region in draw order — the one every fixture here has one of.
+spSlot* firstClipSlot(spSkeleton* skeleton, spClippingAttachment** clip) {
+ for (int i = 0; i < skeleton->slotsCount; ++i) {
+ spSlot* slot = skeleton->drawOrder[i];
+ if (!slot || !slot->attachment) continue;
+ if (slot->attachment->type != SP_ATTACHMENT_CLIPPING) continue;
+ *clip = reinterpret_cast<spClippingAttachment*>(slot->attachment);
+ return slot;
+ }
+ return nullptr;
+}
+
+} // namespace
+
+namespace {
+
+bool openToStage(Instance* instance, int stage, ClipStartCounts* counts) {
+ spClippingAttachment* clip = nullptr;
+ spSlot* slot = firstClipSlot(instance->skeleton, &clip);
+ if (!slot) return false;
+
+ const int length = clip->super.worldVerticesLength;
+ counts->rawVertices = static_cast<std::uint32_t>(length / 2);
+ float* vertices = spFloatArray_setSize(g_clipper->clippingPolygon, length)->items;
+ if (stage < CLIP_START_WORLD) return true;
+
+ g_clipper->clipAttachment = clip;
+ spVertexAttachment_computeWorldVertices(&clip->super, slot, 0, length, vertices, 0, 2);
+ if (stage < CLIP_START_WINDING) return true;
+
+ makeClockwise(g_clipper->clippingPolygon);
+ if (stage < CLIP_START_TRIANGULATE) return true;
+
+ spShortArray* triangles =
+ spTriangulator_triangulate(g_clipper->triangulator, g_clipper->clippingPolygon);
+ counts->triangulationTriangles = static_cast<std::uint32_t>(triangles->size / 3);
+ counts->triangulatorScratch = static_cast<std::uint32_t>(
+ g_clipper->triangulator->indicesArray->capacity
+ + g_clipper->triangulator->isConcaveArray->capacity
+ + g_clipper->triangulator->triangles->capacity);
+ if (stage < CLIP_START_DECOMPOSE) return true;
+
+ g_clipper->clippingPolygons =
+ spTriangulator_decompose(g_clipper->triangulator, g_clipper->clippingPolygon, triangles);
+ counts->pieces = static_cast<std::uint32_t>(g_clipper->clippingPolygons->size);
+ if (stage < CLIP_START_PIECES) return true;
+
+ for (int i = 0; i < g_clipper->clippingPolygons->size; ++i) {
+ spFloatArray* polygon = g_clipper->clippingPolygons->items[i];
+ makeClockwise(polygon);
+ spFloatArray_add(polygon, polygon->items[0]);
+ spFloatArray_add(polygon, polygon->items[1]);
+ }
+ for (int i = 0; i < g_clipper->clippingPolygons->size; ++i) {
+ counts->effectiveEdges +=
+ static_cast<std::uint32_t>(g_clipper->clippingPolygons->items[i]->size / 2);
+ }
+ if (stage < CLIP_START_PUBLISH) return true;
+
+ captureClipRegion();
+ counts->minX = g_clipRegion.minX;
+ counts->minY = g_clipRegion.minY;
+ counts->maxX = g_clipRegion.maxX;
+ counts->maxY = g_clipRegion.maxY;
+ return true;
+}
+
+} // namespace
+
+bool clipStartStage(Instance* instance, int stage, ClipStartCounts* counts) {
+ if (!instance || !counts) return false;
+ *counts = ClipStartCounts{};
+ if (!g_clipper) g_clipper = spSkeletonClipping_create();
+
+ // Closed on both sides. A region left open makes the next real extraction's
+ // clipStart return immediately, so the ladder would be measuring one thing
+ // and poisoning another.
+ spSkeletonClipping_clipEnd2(g_clipper);
+ const bool opened = openToStage(instance, stage, counts);
+ spSkeletonClipping_clipEnd2(g_clipper);
+ return opened;
+}
+
bool renderCounted(Instance* instance, TriangleSink& sink, bool clipping, ProbeCounts* counts) {
if (!instance || !counts) return false;
*counts = ProbeCounts{};
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
index d10d6655a..ad99f713c 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
@@ -546,6 +546,10 @@ bool renderCounted(Instance*, TriangleSink&, bool, ProbeCounts*) {
return false;
}
+bool clipStartStage(Instance*, int, ClipStartCounts*) {
+ return false;
+}
+
int version() {
return ES_SPINE_VERSION;
}