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.

17.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    SpineController.ts
 * @brief   Spine animation control for the modular Spine WASM module
 */

import type { Vec2 } from '../types';
import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';
import { SpineModuleBridge } from './SpineBridge';
import { log } from '../util/logger';
import { withMalloc, withScratch } from '../wasm/wasmScratch';
import type { SkeletalBone } from '../skeletal/types';
import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';
import type { SpineClipBudget, SkeletalProbe } from './spineMetrics';
import type { SpineAABB } from './spineBounds';

export interface RawSpineEvent {
    type: number;
    track: number;
    floatValue: number;
    intValue: number;
    animationName: string;
    eventName: string;
    stringValue: string;
}

export interface ConstraintList {
    ik: string[];
    transform: string[];
    path: string[];
}

export interface TransformMixData {
    mixRotate: number;
    mixX: number;
    mixY: number;
    mixScaleX: number;
    mixScaleY: number;
    mixShearY: number;
}

export interface PathMixData {
    position: number;
    spacing: number;
    mixRotate: number;
    mixX: number;
    mixY: number;
}

export class SpineModuleController {
    private raw_: SpineWasmModule;
    private api_: SpineWrappedAPI;
    private bridge_ = new SpineModuleBridge();

    constructor(raw: SpineWasmModule, api: SpineWrappedAPI) {
        this.raw_ = raw;
        // Guard the API call surface; the raw side module is the abort authority
        // (it owns onAbort + the heap). Every `this.api_.*` call below is now
        // abort-safe with no per-call change; `this.raw_` stays raw for the heap
        // reads and withScratch allocations that must run even after an abort.
        this.bridge_.connect(api, raw);
        this.api_ = this.bridge_.module;
    }

    get raw(): SpineWasmModule {
        return this.raw_;
    }

    // =========================================================================
    // Skeleton Management
    // =========================================================================

    loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number {
        return withScratch(this.raw_, alloc => {
            const put = (bytes: Uint8Array, terminate: boolean): number => {
                const ptr = alloc(bytes.length + (terminate ? 1 : 0));
                this.raw_.HEAPU8.set(bytes, ptr);
                if (terminate) this.raw_.HEAPU8[ptr + bytes.length] = 0;
                return ptr;
            };
            const encoder = new TextEncoder();
            const skel = typeof skelData === 'string' ? encoder.encode(skelData) : skelData;
            const atlas = encoder.encode(atlasText);
            return this.api_.loadSkeleton(put(skel, typeof skelData === 'string'), skel.length, put(atlas, true), atlas.length, isBinary);
        });
    }

    getLastError(): string {
        return this.api_.getLastError();
    }

    unloadSkeleton(handle: number): void {
        this.api_.unloadSkeleton(handle);
    }

    getAtlasPageCount(handle: number): number {
        return this.api_.getAtlasPageCount(handle);
    }

    getAtlasPageTextureName(handle: number, pageIndex: number): string {
        return this.api_.getAtlasPageTextureName(handle, pageIndex);
    }

    setAtlasPageTexture(handle: number, pageIndex: number,
                         textureId: number, width: number, height: number): void {
        this.api_.setAtlasPageTexture(handle, pageIndex, textureId, width, height);
    }

    // =========================================================================
    // Instance Management
    // =========================================================================

    createInstance(skeletonHandle: number): number {
        return this.api_.createInstance(skeletonHandle);
    }

    destroyInstance(instanceId: number): void {
        this.api_.destroyInstance(instanceId);
        // Listeners are keyed by ENTITY, not instanceId — the entity-removal path
        // clears them via removeAllListeners(entity). Deleting by instanceId here
        // was a no-op at best and could evict a different entity's listeners when
        // an instanceId happened to equal an entity id.
    }

    // =========================================================================
    // Animation Control
    // =========================================================================

    /**
     * Back to where the skeleton's data says it starts, every track cleared.
     *
     * The one state a replay is reproducible from: `play` resets nothing, so a
     * bone the next animation does not key keeps whatever the last pose left it
     * at, and seeking twice to one time gives two poses.
     */
    setToSetupPose(instanceId: number): void {
        this.api_.setToSetupPose(instanceId);
    }

    play(instanceId: number, animation: string, loop: boolean = true, track: number = 0): boolean {
        return !!this.api_.playAnimation(instanceId, animation, loop, track);
    }

    addAnimation(instanceId: number, animation: string,
                  loop: boolean = true, delay: number = 0, track: number = 0): boolean {
        return !!this.api_.addAnimation(instanceId, animation, loop, delay, track);
    }

    setSkin(instanceId: number, skinName: string): void {
        this.api_.setSkin(instanceId, skinName);
    }

    update(instanceId: number, dt: number): void {
        this.api_.update(instanceId, dt);
    }

    // =========================================================================
    // Queries
    // =========================================================================

    getAnimations(instanceId: number): string[] {
        const json = this.api_.getAnimations(instanceId);
        try {
            return JSON.parse(json);
        } catch (e) {
            log.warn('spine', 'Failed to parse animations JSON', e);
            return [];
        }
    }

    getSkins(instanceId: number): string[] {
        const json = this.api_.getSkins(instanceId);
        try {
            return JSON.parse(json);
        } catch (e) {
            log.warn('spine', 'Failed to parse skins JSON', e);
            return [];
        }
    }

    getBonePosition(instanceId: number, boneName: string): Vec2 | null {
        return withScratch(this.raw_, alloc => {
            const xPtr = alloc(4);
            const yPtr = alloc(4);

            const found = this.api_.getBonePosition(instanceId, boneName, xPtr, yPtr);

            if (!found) {
                return null;
            }

            const x = this.raw_.HEAPF32[xPtr >> 2];
            const y = this.raw_.HEAPF32[yPtr >> 2];
            return { x, y };
        });
    }

    getBoneRotation(instanceId: number, boneName: string): number {
        return this.api_.getBoneRotation(instanceId, boneName);
    }

    /**
     * The skeleton as a tree in the pose the instance is in: each bone's name, parent
     * (-1 for a root), where it starts, the way it points in degrees and how long it is,
     * in skeleton space. Null from a module built before the call existed. @experimental
     */
    getBoneTree(instanceId: number): SkeletalBone[] | null {
        const api = this.api_;
        if (!api.getBones || !api.getBonePoses) return null;
        let names: string[];
        try {
            names = JSON.parse(api.getBones(instanceId));
        } catch (e) {
            log.warn('spine', 'Failed to parse bones JSON', e);
            return null;
        }
        if (names.length === 0) return [];
        return withMalloc(this.raw_, names.length * 5 * 4, (ptr) => {
            const n = api.getBonePoses!(instanceId, ptr, names.length);
            const heap = this.raw_.HEAPF32;
            const out: SkeletalBone[] = [];
            for (let i = 0; i < n; i++) {
                const at = (ptr >> 2) + i * 5;
                out.push({
                    name: names[i]!, parent: heap[at]! | 0,
                    x: heap[at + 1]!, y: heap[at + 2]!, degrees: heap[at + 3]!, length: heap[at + 4]!,
                });
            }
            return out;
        });
    }

    /**
     * What this instance's clipping costs the engine in the pose it is in, as
     * work rather than time: a coefficient measured on one machine and compiler
     * stops being true, and the three quantities below do not.
     *
     * `null` where the runtime cannot answer — 2.1 and 4.3 have no counted walk.
     */
    clipBudget(instanceId: number): SpineClipBudget | null {
        return withMalloc(this.raw_, 11 * 4, (ptr) => {
            if (!this.api_.clipBudget(instanceId, ptr)) return null;
            const u32 = this.raw_.HEAPU32;
            const at = ptr >> 2;
            const charged = u32[at + 6];
            const inputVertices = u32[at + 8];
            const outputVertices = u32[at + 9];
            const outputTriangles = u32[at + 10];
            return {
                rawVertices: u32[at],
                pieces: u32[at + 1],
                effectiveEdges: u32[at + 2],
                candidateTriangles: u32[at + 3],
                rejectedTriangles: u32[at + 4],
                bypassedTriangles: u32[at + 5],
                chargedTriangles: charged,
                edgeWork: u32[at + 7],
                inputVertices,
                outputVertices,
                outputTriangles,
                vertexAmplification: inputVertices > 0 ? outputVertices / inputVertices : 0,
                triangleAmplification: charged > 0 ? outputTriangles / charged : 0,
            };
        });
    }

    /** The animation clock onto the bones' LOCAL transforms — see spineBounds
     *  and the runtime's ensurePose for why this is not the whole pose. */
    advanceAndApply(instanceId: number, dt: number): void {
        this.api_.advanceAndApply(instanceId, dt);
    }

    /** The world transforms the local pose implies. */
    materializeWorldPose(instanceId: number, dt: number): void {
        this.api_.materializeWorldPose(instanceId, dt);
    }

    /** Seconds; negative where this skeleton has no such animation. */
    animationDuration(skeletonHandle: number, animation: string): number {
        return this.api_.getAnimationDuration(skeletonHandle, animation);
    }

    /** Whether this skeleton's world pose carries state and may not be deferred. */
    requiresContinuousWorldPose(skeletonHandle: number): boolean {
        return !!this.api_.requiresContinuousWorldPose(skeletonHandle);
    }

    /** What the skeleton was AUTHORED at, in its own space — no instance, no
     *  pose, and never an authority over culling. See spineBounds. */
    skeletonBounds(skeletonHandle: number): SpineAABB | null {
        return withMalloc(this.raw_, 16, (ptr) => {
            if (!this.api_.getSkeletonBounds(skeletonHandle, ptr, ptr + 4, ptr + 8, ptr + 12)) return null;
            const f32 = this.raw_.HEAPF32;
            const at = ptr >> 2;
            return { minX: f32[at], minY: f32[at + 1],
                     maxX: f32[at] + f32[at + 2], maxY: f32[at + 1] + f32[at + 3] };
        });
    }

    getBounds(instanceId: number): { x: number; y: number; width: number; height: number } {
        return withMalloc(this.raw_, 16, ptr => {
            this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);

            const f32 = this.raw_.HEAPF32;
            const base = ptr >> 2;
            return {
                x: f32[base],
                y: f32[base + 1],
                width: f32[base + 2],
                height: f32[base + 3],
            };
        });
    }

    // =========================================================================
    // Mesh Extraction
    // =========================================================================

    /**
     * Iterate this instance's mesh batches. The views point into wasm scratch and
     * are valid only for the duration of each call, so a consumer copies straight
     * into its own heap and nothing allocates a typed array per batch per frame.
     *
     * The walk itself is shared with every other skeletal module (see
     * skeletal/meshBatches) — the four readback entry points are packed the same
     * way on the C++ side, so reading them differently per runtime would be two
     * copies of one contract.
     */
    forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor, probe?: SkeletalProbe): void {
        forEachMeshBatch(this.raw_, this.api_, instanceId, cb, probe);
    }

    // =========================================================================
    // Mix / Crossfade
    // =========================================================================

    setDefaultMix(skeletonHandle: number, duration: number): void {
        this.api_.setDefaultMix(skeletonHandle, duration);
    }

    setMixDuration(skeletonHandle: number, fromAnim: string, toAnim: string, duration: number): void {
        this.api_.setMixDuration(skeletonHandle, fromAnim, toAnim, duration);
    }

    setTrackAlpha(instanceId: number, track: number, alpha: number): void {
        this.api_.setTrackAlpha(instanceId, track, alpha);
    }

    // =========================================================================
    // Attachments
    // =========================================================================

    setAttachment(instanceId: number, slotName: string, attachmentName: string): boolean {
        return !!this.api_.setAttachment(instanceId, slotName, attachmentName);
    }

    // =========================================================================
    // IK Constraints
    // =========================================================================

    setIKTarget(instanceId: number, constraintName: string, targetX: number, targetY: number, mix: number): boolean {
        return !!this.api_.setIKTarget(instanceId, constraintName, targetX, targetY, mix);
    }

    // =========================================================================
    // Slot Color
    // =========================================================================

    setSlotColor(instanceId: number, slotName: string, r: number, g: number, b: number, a: number): boolean {
        return !!this.api_.setSlotColor(instanceId, slotName, r, g, b, a);
    }

    /** Whole-skeleton tint, multiplied into every vertex — backs SpineAnimation.color.
     *  Optional-chained: a spine wasm without this export (a realm still on an older
     *  module — the SDK can lead the wasm) degrades to a no-op instead of crashing. */
    setSkeletonColor(instanceId: number, r: number, g: number, b: number, a: number): boolean {
        return !!this.api_.setSkeletonColor?.(instanceId, r, g, b, a);
    }

    // =========================================================================
    // Events
    // =========================================================================

    enableEvents(instanceId: number): void {
        this.api_.enableEvents(instanceId);
    }

    collectEvents(instanceId: number): RawSpineEvent[] {
        const count = this.api_.getEventCount(instanceId);
        if (count === 0) return [];

        const EVENT_STRIDE = 4;
        const bufferPtr = this.api_.getEventBuffer();
        const f32 = this.raw_.HEAPF32;
        const i32 = this.raw_.HEAPU32;
        const base = bufferPtr >> 2;

        const events: RawSpineEvent[] = [];
        for (let i = 0; i < count; i++) {
            const offset = base + i * EVENT_STRIDE;
            const typeNum = i32[offset] | 0;
            events.push({
                type: typeNum,
                track: i32[offset + 1] | 0,
                floatValue: f32[offset + 2],
                intValue: i32[offset + 3] | 0,
                animationName: this.api_.getEventAnimationName(i),
                eventName: typeNum === 5 ? this.api_.getEventName(i) : '',
                stringValue: typeNum === 5 ? this.api_.getEventStringValue(i) : '',
            });
        }
        this.api_.clearEvents();
        return events;
    }

    // =========================================================================
    // Constraints
    // =========================================================================

    listConstraints(instanceId: number): ConstraintList {
        const json = this.api_.listConstraints(instanceId);
        try {
            return JSON.parse(json);
        } catch {
            return { ik: [], transform: [], path: [] };
        }
    }

    getTransformConstraintMix(instanceId: number, name: string): TransformMixData | null {
        const json = this.api_.getTransformConstraintMix(instanceId, name);
        if (!json) return null;
        try {
            return JSON.parse(json);
        } catch {
            return null;
        }
    }

    setTransformConstraintMix(instanceId: number, name: string, mix: TransformMixData): boolean {
        return !!this.api_.setTransformConstraintMix(instanceId, name,
            mix.mixRotate, mix.mixX, mix.mixY, mix.mixScaleX, mix.mixScaleY, mix.mixShearY);
    }

    getPathConstraintMix(instanceId: number, name: string): PathMixData | null {
        const json = this.api_.getPathConstraintMix(instanceId, name);
        if (!json) return null;
        try {
            return JSON.parse(json);
        } catch {
            return null;
        }
    }

    setPathConstraintMix(instanceId: number, name: string, mix: PathMixData): boolean {
        return !!this.api_.setPathConstraintMix(instanceId, name,
            mix.position, mix.spacing, mix.mixRotate, mix.mixX, mix.mixY);
    }

    // =========================================================================
    // Listeners
    // =========================================================================

}