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(animation): the animator gains two ways out — what happened, and how far it asks to move
esengine1810520fc307
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 5cea48bad..1252e4da3 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1560 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1578 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -455,7 +455,7 @@ setFloat: (entity: Entity, name: string, value: number) => voidsetSpineDriver: (driver: SpineAnimationDriver | null) => voidsetTrigger: (entity: Entity, name: string) => voidunregisterController: (name: string) => void-update: (world: World, dt?: number) => void+update: (world: World, dt?: number, events?: AnimatorEventSink) => voidstatic new (): AnimatorControllerAPIstatic prototype: AnimatorControllerAPI```@@ -490,6 +490,24 @@ consumedTriggers: string[]next: string | null```+## AnimatorEvent — const @experimental+```+EventDef<AnimatorEventPayload>+```++## AnimatorEventPayload — interface @experimental+```+entity: number+name: string+text: string+value: number+```++## AnimatorEventSink — interface @experimental+```+send: (event: AnimatorEventPayload) => void+```+## AnimatorMotion — type @experimental```AnimatorClipMotion | AnimatorBlend1DMotion@@ -519,6 +537,20 @@ fadeDuration: numbernextPath: string | null```+## AnimatorRootMotion — const @experimental+```+ComponentDef<AnimatorRootMotionData>+```++## AnimatorRootMotionData — interface @experimental+```+active: boolean+deltaPosition: Vec3+deltaRotation: Quat+deltaTime: number+enabled: boolean+```+## AnimatorScope — type @experimental```Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>@@ -537,6 +569,7 @@ clip: string | undefinedloop: boolean | undefinedmotion: AnimatorMotion | undefinedname: string+rootMotion: boolean | undefinedspeed: number | undefinedspine: AnimatorSpineMotion | undefinedstateMachine: AnimatorSubMachine | undefined@@ -2352,6 +2385,21 @@ Front = 2None = 0```+## CustomEvent — interface @experimental+```+name: string+payload: Record<string, unknown>+time: number+```++## CustomEventTrack — interface @experimental+```+childPath: string+events: CustomEvent[]+name: string+type: "customEvent"+```+## DARK_TOKENS — const @experimental```ThemeTokens@@ -4853,9 +4901,12 @@ shift: booleandrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number+events: (motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]) => void+extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World```@@ -4864,11 +4915,20 @@ world: World```apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefinedduration: ((ctx: MotionContext, motion: M) => number) | undefined+events: ((ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]) => void) | undefinedisFinished: ((ctx: MotionContext, motion: M) => boolean) | undefinedloops: ((ctx: MotionContext, motion: M) => boolean) | undefined+rootMotion: ((ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta) => boolean) | undefinedsample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined```+## MotionEvent — interface @experimental+```+name: string+text: string+value: number+```+## MotionRegistry — class @experimental```context: (world: World, entity: Entity, params: MotionParams) => MotionContext@@ -4880,6 +4940,13 @@ static new (): MotionRegistrystatic prototype: MotionRegistry```+## MotionSpan — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## MotorJoint2D — const @experimental```ComponentDef<MotorJoint2DData>@@ -5968,6 +6035,13 @@ uiThemeOverrides: ThemeOverrides | undefinedySortLayers: number | undefined```+## PlayheadRun — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## Plugin — interface @experimental```after: string[] | undefined@@ -6824,6 +6898,18 @@ layer: numberlinearDamping: number```+## RootMotionDelta — interface @experimental+```+position: Vec3+rotation: Quat+```++## RootPlacement — interface @experimental+```+position: Vec3+rotation: Quat+```+## RunCondition — type @public```() => boolean@@ -10300,6 +10386,11 @@ BtPlugin(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```+## collectCustomEvents — function @experimental+```+(asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[]): void+```+## collectExternalEntityRefs — function @experimental```(entities: readonly ExtractEntity[]): ExternalEntityRef[]@@ -10495,6 +10586,11 @@ Plugin(opts: ProgressOptions): ProgressHandle```+## createRootPlacement — function @experimental+```+(): RootPlacement+```+## createRuntimeSceneConfig — function @experimental```(name: string, sceneData: SceneData | undefined, options: Omit<LoadRuntimeSceneOptions, "sceneData" | "sceneName">, scenePath?: string): SceneConfig@@ -11410,6 +11506,11 @@ InputRouter(): boolean```+## isRootPlacementChannel — function @experimental+```+(childPath: string, component: string, property: string): boolean+```+## isRuntime — function @experimental```(): boolean@@ -11915,6 +12016,11 @@ PerceptionPlugin(): void```+## playheadRuns — function @experimental+```+(from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean): PlayheadRun[]+```+## pointInHitArea — function @experimental```(px: number, py: number, area: HitAreaShape): boolean@@ -12265,6 +12371,11 @@ ReplicationPlugin(rot: Quat, v: Vec3): Vec3```+## runCrosses — function @experimental+```+(run: PlayheadRun, at: number): boolean+```+## runHeadless — function @beta```(app: App, options?: { fps?: number; }): () => void@@ -12275,6 +12386,11 @@ ReplicationPluginSafeAreaPlugin```+## sampleRootPlacement — function @experimental+```+(asset: TimelineAsset, time: number, out: RootPlacement): boolean+```+## sampleTimeline — function @experimental```(asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7a9e216f4..d53821829 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 89 beta · 1579 experimental · 3 deprecated+Symbols: 113 public · 89 beta · 1597 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -455,7 +455,7 @@ setFloat: (entity: Entity, name: string, value: number) => voidsetSpineDriver: (driver: SpineAnimationDriver | null) => voidsetTrigger: (entity: Entity, name: string) => voidunregisterController: (name: string) => void-update: (world: World, dt?: number) => void+update: (world: World, dt?: number, events?: AnimatorEventSink) => voidstatic new (): AnimatorControllerAPIstatic prototype: AnimatorControllerAPI```@@ -490,6 +490,24 @@ consumedTriggers: string[]next: string | null```+## AnimatorEvent — const @experimental+```+EventDef<AnimatorEventPayload>+```++## AnimatorEventPayload — interface @experimental+```+entity: number+name: string+text: string+value: number+```++## AnimatorEventSink — interface @experimental+```+send: (event: AnimatorEventPayload) => void+```+## AnimatorMotion — type @experimental```AnimatorClipMotion | AnimatorBlend1DMotion@@ -519,6 +537,20 @@ fadeDuration: numbernextPath: string | null```+## AnimatorRootMotion — const @experimental+```+ComponentDef<AnimatorRootMotionData>+```++## AnimatorRootMotionData — interface @experimental+```+active: boolean+deltaPosition: Vec3+deltaRotation: Quat+deltaTime: number+enabled: boolean+```+## AnimatorScope — type @experimental```Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>@@ -537,6 +569,7 @@ clip: string | undefinedloop: boolean | undefinedmotion: AnimatorMotion | undefinedname: string+rootMotion: boolean | undefinedspeed: number | undefinedspine: AnimatorSpineMotion | undefinedstateMachine: AnimatorSubMachine | undefined@@ -2360,6 +2393,21 @@ Front = 2None = 0```+## CustomEvent — interface @experimental+```+name: string+payload: Record<string, unknown>+time: number+```++## CustomEventTrack — interface @experimental+```+childPath: string+events: CustomEvent[]+name: string+type: "customEvent"+```+## DARK_TOKENS — const @experimental```ThemeTokens@@ -4866,9 +4914,12 @@ shift: booleandrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number+events: (motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]) => void+extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World```@@ -4877,11 +4928,20 @@ world: World```apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefinedduration: ((ctx: MotionContext, motion: M) => number) | undefined+events: ((ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]) => void) | undefinedisFinished: ((ctx: MotionContext, motion: M) => boolean) | undefinedloops: ((ctx: MotionContext, motion: M) => boolean) | undefined+rootMotion: ((ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta) => boolean) | undefinedsample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined```+## MotionEvent — interface @experimental+```+name: string+text: string+value: number+```+## MotionRegistry — class @experimental```context: (world: World, entity: Entity, params: MotionParams) => MotionContext@@ -4893,6 +4953,13 @@ static new (): MotionRegistrystatic prototype: MotionRegistry```+## MotionSpan — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## MotorJoint2D — const @experimental```ComponentDef<MotorJoint2DData>@@ -6151,6 +6218,13 @@ uiThemeOverrides: ThemeOverrides | undefinedySortLayers: number | undefined```+## PlayheadRun — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## Plugin — interface @experimental```after: string[] | undefined@@ -7017,6 +7091,18 @@ layer: numberlinearDamping: number```+## RootMotionDelta — interface @experimental+```+position: Vec3+rotation: Quat+```++## RootPlacement — interface @experimental+```+position: Vec3+rotation: Quat+```+## RunCondition — type @public```() => boolean@@ -10508,6 +10594,11 @@ BtPlugin(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```+## collectCustomEvents — function @experimental+```+(asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[]): void+```+## collectExternalEntityRefs — function @experimental```(entities: readonly ExtractEntity[]): ExternalEntityRef[]@@ -10728,6 +10819,11 @@ Plugin(opts: ProgressOptions): ProgressHandle```+## createRootPlacement — function @experimental+```+(): RootPlacement+```+## createRuntimeSceneConfig — function @experimental```(name: string, sceneData: SceneData | undefined, options: Omit<LoadRuntimeSceneOptions, "sceneData" | "sceneName">, scenePath?: string): SceneConfig@@ -11653,6 +11749,11 @@ InputRouter(): boolean```+## isRootPlacementChannel — function @experimental+```+(childPath: string, component: string, property: string): boolean+```+## isRuntime — function @experimental```(): boolean@@ -12158,6 +12259,11 @@ PerceptionPlugin(): void```+## playheadRuns — function @experimental+```+(from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean): PlayheadRun[]+```+## pointInHitArea — function @experimental```(px: number, py: number, area: HitAreaShape): boolean@@ -12508,6 +12614,11 @@ ReplicationPlugin(rot: Quat, v: Vec3): Vec3```+## runCrosses — function @experimental+```+(run: PlayheadRun, at: number): boolean+```+## runHeadless — function @beta```(app: App, options?: { fps?: number; }): () => void@@ -12518,6 +12629,11 @@ ReplicationPluginSafeAreaPlugin```+## sampleRootPlacement — function @experimental+```+(asset: TimelineAsset, time: number, out: RootPlacement): boolean+```+## sampleTimeline — function @experimental```(asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex bd2c5da92..3ab0cebd3 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 86 beta · 1559 experimental · 3 deprecated+Symbols: 113 public · 86 beta · 1577 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => voidsetSpineDriver: (driver: SpineAnimationDriver | null) => voidsetTrigger: (entity: Entity, name: string) => voidunregisterController: (name: string) => void-update: (world: World, dt?: number) => void+update: (world: World, dt?: number, events?: AnimatorEventSink) => voidstatic new (): AnimatorControllerAPIstatic prototype: AnimatorControllerAPI```@@ -485,6 +485,24 @@ consumedTriggers: string[]next: string | null```+## AnimatorEvent — const @experimental+```+EventDef<AnimatorEventPayload>+```++## AnimatorEventPayload — interface @experimental+```+entity: number+name: string+text: string+value: number+```++## AnimatorEventSink — interface @experimental+```+send: (event: AnimatorEventPayload) => void+```+## AnimatorMotion — type @experimental```AnimatorClipMotion | AnimatorBlend1DMotion@@ -514,6 +532,20 @@ fadeDuration: numbernextPath: string | null```+## AnimatorRootMotion — const @experimental+```+ComponentDef<AnimatorRootMotionData>+```++## AnimatorRootMotionData — interface @experimental+```+active: boolean+deltaPosition: Vec3+deltaRotation: Quat+deltaTime: number+enabled: boolean+```+## AnimatorScope — type @experimental```Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>@@ -532,6 +564,7 @@ clip: string | undefinedloop: boolean | undefinedmotion: AnimatorMotion | undefinedname: string+rootMotion: boolean | undefinedspeed: number | undefinedspine: AnimatorSpineMotion | undefinedstateMachine: AnimatorSubMachine | undefined@@ -2347,6 +2380,21 @@ Front = 2None = 0```+## CustomEvent — interface @experimental+```+name: string+payload: Record<string, unknown>+time: number+```++## CustomEventTrack — interface @experimental+```+childPath: string+events: CustomEvent[]+name: string+type: "customEvent"+```+## DARK_TOKENS — const @experimental```ThemeTokens@@ -4848,9 +4896,12 @@ shift: booleandrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number+events: (motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]) => void+extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World```@@ -4859,11 +4910,20 @@ world: World```apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefinedduration: ((ctx: MotionContext, motion: M) => number) | undefined+events: ((ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]) => void) | undefinedisFinished: ((ctx: MotionContext, motion: M) => boolean) | undefinedloops: ((ctx: MotionContext, motion: M) => boolean) | undefined+rootMotion: ((ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta) => boolean) | undefinedsample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined```+## MotionEvent — interface @experimental+```+name: string+text: string+value: number+```+## MotionRegistry — class @experimental```context: (world: World, entity: Entity, params: MotionParams) => MotionContext@@ -4875,6 +4935,13 @@ static new (): MotionRegistrystatic prototype: MotionRegistry```+## MotionSpan — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## MotorJoint2D — const @experimental```ComponentDef<MotorJoint2DData>@@ -5963,6 +6030,13 @@ uiThemeOverrides: ThemeOverrides | undefinedySortLayers: number | undefined```+## PlayheadRun — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## Plugin — interface @experimental```after: string[] | undefined@@ -6819,6 +6893,18 @@ layer: numberlinearDamping: number```+## RootMotionDelta — interface @experimental+```+position: Vec3+rotation: Quat+```++## RootPlacement — interface @experimental+```+position: Vec3+rotation: Quat+```+## RunCondition — type @public```() => boolean@@ -10295,6 +10381,11 @@ BtPlugin(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```+## collectCustomEvents — function @experimental+```+(asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[]): void+```+## collectExternalEntityRefs — function @experimental```(entities: readonly ExtractEntity[]): ExternalEntityRef[]@@ -10490,6 +10581,11 @@ Plugin(opts: ProgressOptions): ProgressHandle```+## createRootPlacement — function @experimental+```+(): RootPlacement+```+## createRuntimeSceneConfig — function @experimental```(name: string, sceneData: SceneData | undefined, options: Omit<LoadRuntimeSceneOptions, "sceneData" | "sceneName">, scenePath?: string): SceneConfig@@ -11405,6 +11501,11 @@ InputRouter(): boolean```+## isRootPlacementChannel — function @experimental+```+(childPath: string, component: string, property: string): boolean+```+## isRuntime — function @experimental```(): boolean@@ -11920,6 +12021,11 @@ PerceptionPlugin(): void```+## playheadRuns — function @experimental+```+(from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean): PlayheadRun[]+```+## pointInHitArea — function @experimental```(px: number, py: number, area: HitAreaShape): boolean@@ -12270,6 +12376,11 @@ ReplicationPlugin(rot: Quat, v: Vec3): Vec3```+## runCrosses — function @experimental+```+(run: PlayheadRun, at: number): boolean+```+## runHeadless — function @beta```(app: App, options?: { fps?: number; }): () => void@@ -12280,6 +12391,11 @@ ReplicationPluginSafeAreaPlugin```+## sampleRootPlacement — function @experimental+```+(asset: TimelineAsset, time: number, out: RootPlacement): boolean+```+## sampleTimeline — function @experimental```(asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5b53bf9d9..f82353e59 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1581 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1599 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => voidsetSpineDriver: (driver: SpineAnimationDriver | null) => voidsetTrigger: (entity: Entity, name: string) => voidunregisterController: (name: string) => void-update: (world: World, dt?: number) => void+update: (world: World, dt?: number, events?: AnimatorEventSink) => voidstatic new (): AnimatorControllerAPIstatic prototype: AnimatorControllerAPI```@@ -485,6 +485,24 @@ consumedTriggers: string[]next: string | null```+## AnimatorEvent — const @experimental+```+EventDef<AnimatorEventPayload>+```++## AnimatorEventPayload — interface @experimental+```+entity: number+name: string+text: string+value: number+```++## AnimatorEventSink — interface @experimental+```+send: (event: AnimatorEventPayload) => void+```+## AnimatorMotion — type @experimental```AnimatorClipMotion | AnimatorBlend1DMotion@@ -514,6 +532,20 @@ fadeDuration: numbernextPath: string | null```+## AnimatorRootMotion — const @experimental+```+ComponentDef<AnimatorRootMotionData>+```++## AnimatorRootMotionData — interface @experimental+```+active: boolean+deltaPosition: Vec3+deltaRotation: Quat+deltaTime: number+enabled: boolean+```+## AnimatorScope — type @experimental```Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>@@ -532,6 +564,7 @@ clip: string | undefinedloop: boolean | undefinedmotion: AnimatorMotion | undefinedname: string+rootMotion: boolean | undefinedspeed: number | undefinedspine: AnimatorSpineMotion | undefinedstateMachine: AnimatorSubMachine | undefined@@ -2347,6 +2380,21 @@ Front = 2None = 0```+## CustomEvent — interface @experimental+```+name: string+payload: Record<string, unknown>+time: number+```++## CustomEventTrack — interface @experimental+```+childPath: string+events: CustomEvent[]+name: string+type: "customEvent"+```+## DARK_TOKENS — const @experimental```ThemeTokens@@ -5094,9 +5142,12 @@ shift: booleandrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number+events: (motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]) => void+extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World```@@ -5105,11 +5156,20 @@ world: World```apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefinedduration: ((ctx: MotionContext, motion: M) => number) | undefined+events: ((ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]) => void) | undefinedisFinished: ((ctx: MotionContext, motion: M) => boolean) | undefinedloops: ((ctx: MotionContext, motion: M) => boolean) | undefined+rootMotion: ((ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta) => boolean) | undefinedsample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined```+## MotionEvent — interface @experimental+```+name: string+text: string+value: number+```+## MotionRegistry — class @experimental```context: (world: World, entity: Entity, params: MotionParams) => MotionContext@@ -5121,6 +5181,13 @@ static new (): MotionRegistrystatic prototype: MotionRegistry```+## MotionSpan — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## MotorJoint2D — const @experimental```ComponentDef<MotorJoint2DData>@@ -6209,6 +6276,13 @@ uiThemeOverrides: ThemeOverrides | undefinedySortLayers: number | undefined```+## PlayheadRun — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## Plugin — interface @experimental```after: string[] | undefined@@ -7065,6 +7139,18 @@ layer: numberlinearDamping: number```+## RootMotionDelta — interface @experimental+```+position: Vec3+rotation: Quat+```++## RootPlacement — interface @experimental+```+position: Vec3+rotation: Quat+```+## RunCondition — type @public```() => boolean@@ -10547,6 +10633,11 @@ BtPlugin(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```+## collectCustomEvents — function @experimental+```+(asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[]): void+```+## collectExternalEntityRefs — function @experimental```(entities: readonly ExtractEntity[]): ExternalEntityRef[]@@ -10747,6 +10838,11 @@ Plugin(opts: ProgressOptions): ProgressHandle```+## createRootPlacement — function @experimental+```+(): RootPlacement+```+## createRuntimeSceneConfig — function @experimental```(name: string, sceneData: SceneData | undefined, options: Omit<LoadRuntimeSceneOptions, "sceneData" | "sceneName">, scenePath?: string): SceneConfig@@ -11672,6 +11768,11 @@ InputRouter(): boolean```+## isRootPlacementChannel — function @experimental+```+(childPath: string, component: string, property: string): boolean+```+## isRuntime — function @experimental```(): boolean@@ -12177,6 +12278,11 @@ PerceptionPlugin(): void```+## playheadRuns — function @experimental+```+(from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean): PlayheadRun[]+```+## pointInHitArea — function @experimental```(px: number, py: number, area: HitAreaShape): boolean@@ -12527,6 +12633,11 @@ ReplicationPlugin(rot: Quat, v: Vec3): Vec3```+## runCrosses — function @experimental+```+(run: PlayheadRun, at: number): boolean+```+## runHeadless — function @beta```(app: App, options?: { fps?: number; }): () => void@@ -12537,6 +12648,11 @@ ReplicationPluginSafeAreaPlugin```+## sampleRootPlacement — function @experimental+```+(asset: TimelineAsset, time: number, out: RootPlacement): boolean+```+## sampleTimeline — function @experimental```(asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c4fc2ac2a..a145f27f5 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1571 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1589 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => voidsetSpineDriver: (driver: SpineAnimationDriver | null) => voidsetTrigger: (entity: Entity, name: string) => voidunregisterController: (name: string) => void-update: (world: World, dt?: number) => void+update: (world: World, dt?: number, events?: AnimatorEventSink) => voidstatic new (): AnimatorControllerAPIstatic prototype: AnimatorControllerAPI```@@ -485,6 +485,24 @@ consumedTriggers: string[]next: string | null```+## AnimatorEvent — const @experimental+```+EventDef<AnimatorEventPayload>+```++## AnimatorEventPayload — interface @experimental+```+entity: number+name: string+text: string+value: number+```++## AnimatorEventSink — interface @experimental+```+send: (event: AnimatorEventPayload) => void+```+## AnimatorMotion — type @experimental```AnimatorClipMotion | AnimatorBlend1DMotion@@ -514,6 +532,20 @@ fadeDuration: numbernextPath: string | null```+## AnimatorRootMotion — const @experimental+```+ComponentDef<AnimatorRootMotionData>+```++## AnimatorRootMotionData — interface @experimental+```+active: boolean+deltaPosition: Vec3+deltaRotation: Quat+deltaTime: number+enabled: boolean+```+## AnimatorScope — type @experimental```Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>@@ -532,6 +564,7 @@ clip: string | undefinedloop: boolean | undefinedmotion: AnimatorMotion | undefinedname: string+rootMotion: boolean | undefinedspeed: number | undefinedspine: AnimatorSpineMotion | undefinedstateMachine: AnimatorSubMachine | undefined@@ -2347,6 +2380,21 @@ Front = 2None = 0```+## CustomEvent — interface @experimental+```+name: string+payload: Record<string, unknown>+time: number+```++## CustomEventTrack — interface @experimental+```+childPath: string+events: CustomEvent[]+name: string+type: "customEvent"+```+## DARK_TOKENS — const @experimental```ThemeTokens@@ -4855,9 +4903,12 @@ shift: booleandrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number+events: (motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]) => void+extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World```@@ -4866,11 +4917,20 @@ world: World```apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefinedduration: ((ctx: MotionContext, motion: M) => number) | undefined+events: ((ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]) => void) | undefinedisFinished: ((ctx: MotionContext, motion: M) => boolean) | undefinedloops: ((ctx: MotionContext, motion: M) => boolean) | undefined+rootMotion: ((ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta) => boolean) | undefinedsample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined```+## MotionEvent — interface @experimental+```+name: string+text: string+value: number+```+## MotionRegistry — class @experimental```context: (world: World, entity: Entity, params: MotionParams) => MotionContext@@ -4882,6 +4942,13 @@ static new (): MotionRegistrystatic prototype: MotionRegistry```+## MotionSpan — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## MotorJoint2D — const @experimental```ComponentDef<MotorJoint2DData>@@ -5970,6 +6037,13 @@ uiThemeOverrides: ThemeOverrides | undefinedySortLayers: number | undefined```+## PlayheadRun — interface @experimental+```+from: number+inclusiveStart: boolean+to: number+```+## Plugin — interface @experimental```after: string[] | undefined@@ -6826,6 +6900,18 @@ layer: numberlinearDamping: number```+## RootMotionDelta — interface @experimental+```+position: Vec3+rotation: Quat+```++## RootPlacement — interface @experimental+```+position: Vec3+rotation: Quat+```+## RunCondition — type @public```() => boolean@@ -10323,6 +10409,11 @@ BtPlugin(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```+## collectCustomEvents — function @experimental+```+(asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[]): void+```+## collectExternalEntityRefs — function @experimental```(entities: readonly ExtractEntity[]): ExternalEntityRef[]@@ -10518,6 +10609,11 @@ Plugin(opts: ProgressOptions): ProgressHandle```+## createRootPlacement — function @experimental+```+(): RootPlacement+```+## createRuntimeSceneConfig — function @experimental```(name: string, sceneData: SceneData | undefined, options: Omit<LoadRuntimeSceneOptions, "sceneData" | "sceneName">, scenePath?: string): SceneConfig@@ -11438,6 +11534,11 @@ InputRouter(): boolean```+## isRootPlacementChannel — function @experimental+```+(childPath: string, component: string, property: string): boolean+```+## isRuntime — function @experimental```(): boolean@@ -11943,6 +12044,11 @@ PerceptionPlugin(): void```+## playheadRuns — function @experimental+```+(from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean): PlayheadRun[]+```+## pointInHitArea — function @experimental```(px: number, py: number, area: HitAreaShape): boolean@@ -12293,6 +12399,11 @@ ReplicationPlugin(rot: Quat, v: Vec3): Vec3```+## runCrosses — function @experimental+```+(run: PlayheadRun, at: number): boolean+```+## runHeadless — function @beta```(app: App, options?: { fps?: number; }): () => void@@ -12303,6 +12414,11 @@ ReplicationPluginSafeAreaPlugin```+## sampleRootPlacement — function @experimental+```+(asset: TimelineAsset, time: number, out: RootPlacement): boolean+```+## sampleTimeline — function @experimental```(asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions): voiddiff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.tsindex 43adc7e96..54a10fdf3 100644--- a/sdk/src/animation/AnimationPlugin.ts+++ b/sdk/src/animation/AnimationPlugin.ts@@ -8,6 +8,8 @@import type { App, Plugin } from '../app/app';import { defineSystem, Schedule } from '../ecs/system';import { Res } from '../ecs/resource';+import { EventWriter, type EventWriterInstance } from '../ecs/event';+import { AnimatorEvent, type AnimatorEventPayload } from './animatorEvent';import { Time, type TimeData } from '../ecs/resource';import type { Entity } from '../types';import type { CppRegistry } from '../wasm';@@ -67,9 +69,12 @@ export class AnimationPlugin implements Plugin {// The state machine runs before the sprite animator so a transition's// clip switch applies the same frame it fires.app.addSystemToSchedule(Schedule.Update, defineSystem(- [Res(Time), Res(AnimatorController)],- (time: TimeData, ctrl: AnimatorControllerAPI) => {- ctrl.update(world, time.delta);+ [Res(Time), Res(AnimatorController), EventWriter(AnimatorEvent)],+ (+ time: TimeData, ctrl: AnimatorControllerAPI,+ events: EventWriterInstance<AnimatorEventPayload>,+ ) => {+ ctrl.update(world, time.delta, events);},{ name: 'AnimatorSystem' }), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsindex f9d1c1ee9..b2a9840f8 100644--- a/sdk/src/animation/Animator.ts+++ b/sdk/src/animation/Animator.ts@@ -24,11 +24,16 @@ import type { World } from '../ecs/world';import {MotionRegistry, blend1DMotionDriver,type AnimatorMotion, type AnimatorClipMotion, type AnimatorBlend1DMotion,- type MotionContext, type MotionDriver,+ type MotionContext, type MotionDriver, type MotionEvent, type MotionSpan,+ type RootMotionDelta,} from './motion';import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';import { Pose } from './pose';import { mixPoses } from './poseMix';+import { AnimatorRootMotion, type AnimatorRootMotionData } from './animatorRootMotion';+import type { AnimatorEventSink } from './animatorEvent';+import { Transform, type TransformData } from '../ecs/component';+import { q } from '../math/quat';// =============================================================================// Controller definition (the graph data)@@ -134,6 +139,13 @@ export interface AnimatorState {spine?: AnimatorSpineMotion;/** Nested machine — makes this a container state (no motion of its own). */stateMachine?: AnimatorSubMachine;+ /**+ * This state's motion states where the CHARACTER goes, not how it is posed:+ * its root track leaves the pose and becomes a request on+ * {@link AnimatorRootMotion}. Per state, because a locomotion state is+ * stick-driven and a lunge is not, and the export cannot say which.+ */+ rootMotion?: boolean;speed?: number;loop?: boolean;transitions: AnimatorTransition[];@@ -614,9 +626,13 @@ export class AnimatorControllerAPI {// -- per-frame system ------------------------------------------------------ /** `dt` seconds advance the animator's own clock, which is what a sampled- * motion is evaluated against and what a crossfade progresses on. */- update(world: World, dt: number = 0): void {+ /**+ * `dt` seconds advance the animator's own clock, which is what a sampled+ * motion is evaluated against and what a crossfade progresses on. `events`+ * is where what the clips declared is posted; without one the animator still+ * runs and simply says nothing, which is what a bare App is.+ */+ update(world: World, dt: number = 0, events?: AnimatorEventSink): void {const entities = world.getEntitiesWithComponents([Animator]);for (const entity of entities) {const a = world.get(entity, Animator) as AnimatorData;@@ -665,12 +681,77 @@ export class AnimatorControllerAPI {const motion = targetLeaf === leaf ? leafMotion : motionOf(targetLeaf);if (stateChanged) {- this.beginState(rt, leafMotion, motion, fadeDuration);+ this.beginState(rt, leafMotion, leaf.rootMotion === true, motion, fadeDuration);}- if (motion) this.driveMotion(ctx, world, rt, motion, stateChanged);+ const drivesRoot = targetLeaf.rootMotion === true;+ if (motion) this.driveMotion(ctx, world, rt, motion, drivesRoot, stateChanged);++ // What the state's own clock covered this frame. Empty on the frame it+ // was entered, and closed there rather than half-open: an event+ // authored at the very start of a clip happens on that frame or never.+ const span: MotionSpan = {+ from: rt.prevTime, to: rt.time, inclusiveStart: rt.entered,+ };+ if (motion && events) this.emitEvents(ctx, entity, motion, span, events);+ this.publishRootMotion(world, entity, ctx, motion, span, drivesRoot);+ }+ }++ /**+ * Post what the ACTIVE motion crossed. A motion being faded out states+ * nothing: its clock is still running, so an attack cancelled into a dodge+ * would go on landing its hit, and "how much of it is still on screen" is not+ * an answer to whether it happened.+ */+ private emitEvents(+ ctx: MotionContext, entity: Entity,+ motion: AnimatorMotion, span: MotionSpan, events: AnimatorEventSink,+ ): void {+ const crossed = this.eventScratch_;+ crossed.length = 0;+ ctx.events(motion, span, crossed);+ for (const e of crossed) {+ events.send({ entity, name: e.name, value: e.value, text: e.text });}}+ /**+ * State what the animation asks to move, for gameplay to hand on. World space,+ * because a consumer wants "move me this way" rather than a vector in a frame+ * it has to reconstruct; and paired with the seconds it covers, because the+ * consumer usually steps on a different clock than this one.+ */+ private publishRootMotion(+ world: World, entity: Entity, ctx: MotionContext,+ motion: AnimatorMotion | null, span: MotionSpan, drivesRoot: boolean,+ ): void {+ if (!world.has(entity, AnimatorRootMotion)) return;+ const out = this.rootScratch_;+ const active = drivesRoot+ && (world.get(entity, AnimatorRootMotion) as AnimatorRootMotionData).enabled;+ // A state that declares root motion whose clip states none asks to move+ // nowhere — which is still the animation driving, not the stick.+ const stated = active && motion !== null && ctx.rootDelta(motion, span, out);+ const local = stated ? out.position : ZERO_VEC;+ const turn = stated ? out.rotation : IDENTITY_QUAT;+ const rotation = world.has(entity, Transform)+ ? (world.get(entity, Transform) as TransformData).rotation+ : null;+ const moved = rotation ? q.rotate(rotation, local) : local;++ world.update(entity, AnimatorRootMotion, (data: AnimatorRootMotionData) => {+ data.active = active;+ data.deltaPosition.x = moved.x;+ data.deltaPosition.y = moved.y;+ data.deltaPosition.z = moved.z;+ data.deltaRotation.w = turn.w;+ data.deltaRotation.x = turn.x;+ data.deltaRotation.y = turn.y;+ data.deltaRotation.z = turn.z;+ data.deltaTime = active ? span.to - span.from : 0;+ });+ }+/*** Enter a state: the clock restarts, and the motion being left keeps running* as the thing to fade out of. Only when BOTH can be sampled - a switched@@ -678,12 +759,14 @@ export class AnimatorControllerAPI {*/private beginState(rt: AnimatorRuntime,- leaving: AnimatorMotion | null, entering: AnimatorMotion | null, fadeDuration: number,+ leaving: AnimatorMotion | null, leavingDrivesRoot: boolean,+ entering: AnimatorMotion | null, fadeDuration: number,): void {const blendable = fadeDuration > 0 && leaving !== null && entering !== null&& this.canSample(leaving) && this.canSample(entering);if (blendable) {rt.fadeFrom = leaving;+ rt.fadeFromRoot = leavingDrivesRoot;rt.fadeFromTime = rt.time;rt.fadeElapsed = 0;rt.fadeDuration = fadeDuration;@@ -691,10 +774,14 @@ export class AnimatorControllerAPI {rt.fadeFrom = null;}rt.time = 0;+ rt.prevTime = 0;+ rt.entered = true;}/** Advance the state's clock, and the fade's if one is running. */private advance(rt: AnimatorRuntime, dt: number): void {+ rt.prevTime = rt.time;+ rt.entered = false;rt.time += dt;if (rt.fadeFrom === null) return;rt.fadeFromTime += dt;@@ -708,12 +795,14 @@ export class AnimatorControllerAPI {*/private driveMotion(ctx: MotionContext, world: World, rt: AnimatorRuntime,- motion: AnimatorMotion, enter: boolean,+ motion: AnimatorMotion, drivesRoot: boolean, enter: boolean,): void {if (rt.fadeFrom !== null) {rt.poseFrom.reset();rt.poseTo.reset();+ ctx.extractRootMotion = rt.fadeFromRoot;const from = ctx.sample(rt.fadeFrom, rt.fadeFromTime, rt.poseFrom);+ ctx.extractRootMotion = drivesRoot;const to = ctx.sample(motion, rt.time, rt.poseTo);if (from && to) {const t = Math.min(rt.fadeElapsed / rt.fadeDuration, 1);@@ -729,6 +818,7 @@ export class AnimatorControllerAPI {}rt.poseTo.reset();+ ctx.extractRootMotion = drivesRoot;if (ctx.sample(motion, rt.time, rt.poseTo)) {rt.poseTo.applyTo(world);return;@@ -752,22 +842,43 @@ export class AnimatorControllerAPI {let rt = this.runtimes_.get(entity);if (!rt) {rt = {- time: 0, fadeFrom: null, fadeFromTime: 0, fadeElapsed: 0, fadeDuration: 0,+ time: 0, prevTime: 0, entered: true,+ fadeFrom: null, fadeFromRoot: false,+ fadeFromTime: 0, fadeElapsed: 0, fadeDuration: 0,poseFrom: new Pose(), poseTo: new Pose(), mixed: new Pose(),};this.runtimes_.set(entity, rt);}return rt;}++ /** Reused across entities and frames: a steady animation states no events,+ * and an array per animated entity per frame would be the only allocation. */+ private readonly eventScratch_: MotionEvent[] = [];+ private readonly rootScratch_: RootMotionDelta = {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ };}+const ZERO_VEC = { x: 0, y: 0, z: 0 };+const IDENTITY_QUAT = { w: 1, x: 0, y: 0, z: 0 };+/** One entity's playback state: transient, so it lives here and not on the* component, which is what a scene saves and an inspector shows. */interface AnimatorRuntime {/** Seconds the current state's motion has been playing. */time: number;+ /** What {@link time} was before this frame's advance — the other end of the+ * window an event has to fall inside to have happened. */+ prevTime: number;+ /** Whether this frame is the one the state was entered on. */+ entered: boolean;/** The motion being faded out, or null when nothing is. */fadeFrom: AnimatorMotion | null;+ /** Whether the state being faded out was itself driving the character, so its+ * pose is sampled the way it was while it was the active one. */+ fadeFromRoot: boolean;fadeFromTime: number;fadeElapsed: number;fadeDuration: number;diff --git a/sdk/src/animation/animatorEvent.ts b/sdk/src/animation/animatorEvent.tsnew file mode 100644index 000000000..8218cd6fa--- /dev/null+++ b/sdk/src/animation/animatorEvent.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file animatorEvent.ts+ * @brief What the animator says happened, for anything that cares to hear it.+ *+ * @details The animator's job ends at "the clip declared `hit` and the playhead+ * just crossed it". Dealing damage, playing a footstep, bursting dust —+ * those belong to the systems that own damage, sound and particles, and+ * an animator that called them would be a state machine that imports the+ * combat rules. So it states the event and stops, and the dependency+ * runs the other way: gameplay reads the animator, never the reverse.+ *+ * One channel, the engine's own event bus, rather than a listener list+ * beside it: a callback fires inside the animator's own loop over+ * entities, and a handler that spawns or despawns there is mutating the+ * set being iterated.+ */++import { defineEvent, type EventDef } from '../ecs/event';+import type { Entity } from '../types';++/**+ * One event a clip declared, and who it happened to.+ *+ * The payload is two scalars rather than an open object: what crosses this bus+ * is also what a compiled system reads, and a shape that varies per clip has no+ * layout to bake in. A clip states them as `value` and `text` on the event.+ *+ * @experimental+ */+export interface AnimatorEventPayload {+ /** The animated entity — the character this happened to. */+ entity: Entity;+ /** The event's name as the clip declared it (`footstep`, `hit`). */+ name: string;+ /** Its numeric payload; 0 when the clip states none. */+ value: number;+ /** Its string payload; empty when the clip states none. */+ text: string;+}++/**+ * The bus every animation event arrives on. Read it with+ * `EventReader(AnimatorEvent)` in a system of your own.+ *+ * @experimental+ */+export const AnimatorEvent: EventDef<AnimatorEventPayload> =+ defineEvent<AnimatorEventPayload>('AnimatorEvent', {+ entity: 0 as Entity, name: '', value: 0, text: '',+ });++/**+ * Where the animator posts what it saw. `EventWriter(AnimatorEvent)` satisfies+ * it, and so does a test's array — the animator states events without knowing+ * whether an App is listening.+ *+ * @experimental+ */+export interface AnimatorEventSink {+ send(event: AnimatorEventPayload): void;+}diff --git a/sdk/src/animation/animatorRootMotion.ts b/sdk/src/animation/animatorRootMotion.tsnew file mode 100644index 000000000..1749033c7--- /dev/null+++ b/sdk/src/animation/animatorRootMotion.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file animatorRootMotion.ts+ * @brief How far the animation asks the character to move — a request, never a+ * result.+ *+ * @details A clip that animates the entity it is played ON is not posing a+ * skeleton; it is saying where the character travels. Writing that to+ * the Transform would put the animator in charge of movement, and an+ * animator in charge of movement walks through walls: the world's+ * answer is the character controller's to give.+ *+ * So the animator states the request here and touches nothing. Gameplay+ * reads it, hands it to whatever moves the character, and the character+ * ends up wherever collision allowed — which is what the pattern beside+ * it already does with the stick.+ *+ * The deltas come with the SECONDS they cover because the animator runs+ * on the frame clock and a character controller usually steps on a fixed+ * one. A consumer forms a rate from the pair; a consumer that just added+ * the delta would move twice on a frame with two steps and not at all on+ * a frame with none.+ */++import { defineComponent, type ComponentDef } from '../ecs/component';+import type { Quat, Vec3 } from '../types';++/** The fields of the `AnimatorRootMotion` component. @experimental */+export interface AnimatorRootMotionData {+ /** Whether the animator publishes this entity's root motion at all. */+ enabled: boolean;+ /**+ * Engine-written: whether a state that DECLARES root motion is driving this+ * frame. The switch a consumer reads — not "is the delta non-zero", which is+ * also true of the still moment in the middle of a dodge.+ */+ active: boolean;+ /** Engine-written: the displacement asked for, in world space. */+ deltaPosition: Vec3;+ /** Engine-written: the turn asked for, in the character's own frame. */+ deltaRotation: Quat;+ /** Engine-written: seconds the deltas cover; 0 when nothing was asked. */+ deltaTime: number;+}++/**+ * Publishes what the active animation asks to move, for gameplay to hand to a+ * character controller. Add it to a character whose animations drive movement;+ * without it, a root-motion state still refuses to pose the character's own+ * Transform — it simply plays on the spot.+ *+ * @experimental+ */+export const AnimatorRootMotion: ComponentDef<AnimatorRootMotionData> =+ defineComponent<AnimatorRootMotionData>('AnimatorRootMotion', {+ enabled: true,+ active: false,+ deltaPosition: { x: 0, y: 0, z: 0 },+ deltaRotation: { w: 1, x: 0, y: 0, z: 0 },+ deltaTime: 0,+ }, {+ readonlyFields: ['active', 'deltaPosition', 'deltaRotation', 'deltaTime'],+ fields: {+ active: { advanced: true },+ deltaPosition: { advanced: true },+ deltaRotation: { advanced: true },+ deltaTime: { advanced: true, unit: 's' },+ },+ });diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex 8a0fb9442..7eeb765d8 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -146,8 +146,22 @@ export {type MotionContext,type MotionDriver,type MotionParams,+ type MotionSpan,+ type MotionEvent,+ type RootMotionDelta,} from './motion';+export {+ AnimatorEvent,+ type AnimatorEventPayload,+ type AnimatorEventSink,+} from './animatorEvent';++export {+ AnimatorRootMotion,+ type AnimatorRootMotionData,+} from './animatorRootMotion';+export {SPRITE_MOTION,spriteMotionDriver,diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.tsindex 7a6c5027e..289443633 100644--- a/sdk/src/animation/motion.ts+++ b/sdk/src/animation/motion.ts@@ -19,7 +19,7 @@* animation core from importing it.*/-import type { Entity } from '../types';+import type { Entity, Quat, Vec3 } from '../types';import type { World } from '../ecs/world';import type { Pose } from './pose';@@ -60,6 +60,41 @@ export function isBlend1D(m: AnimatorMotion): m is AnimatorBlend1DMotion {return m.kind === 'blend1d';}+// =============================================================================+// What a motion says happened, and how far it asks to move+// =============================================================================++/**+ * A window of a motion's own playback, in ANIMATOR seconds. Half-open — an event+ * at `from` belongs to the window before this one — except on the frame a state+ * was entered, where `from` and `to` are both 0 and a closed window is the only+ * one that can contain an event authored at the very start of a clip.+ */+export interface MotionSpan {+ from: number;+ to: number;+ inclusiveStart: boolean;+}++/** Something a clip declares happened at a point in its own time. */+export interface MotionEvent {+ name: string;+ /** The event's numeric payload; 0 when it carries none. */+ value: number;+ /** The event's string payload; empty when it carries none. */+ text: string;+}++/**+ * How far a motion asks to move over a span, in the animated entity's OWN frame.+ * A request, not a result: what the character ends up doing with it is the+ * character controller's answer, and this never reaches a Transform.+ */+export interface RootMotionDelta {+ position: Vec3;+ rotation: Quat;+}+// =============================================================================// Driver seam// =============================================================================@@ -83,6 +118,17 @@ export interface MotionContext {duration(motion: AnimatorMotion): number;/** Whether a nested motion repeats, and so never ends on its own. */loops(motion: AnimatorMotion): boolean;+ /** Append a nested motion's events over `span` to `out`. */+ events(motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]): void;+ /** A nested motion's displacement over `span`; false when it states none. */+ rootDelta(motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta): boolean;+ /**+ * Whether the animator is taking this motion's root track as DISPLACEMENT.+ * A driver that can state a root pose must then leave the root's position and+ * rotation out of what it samples: the same movement written to the entity and+ * handed to the character controller moves it twice.+ */+ extractRootMotion: boolean;}/**@@ -109,6 +155,18 @@ export interface MotionDriver<M extends AnimatorMotion = AnimatorMotion> {duration?(ctx: MotionContext, motion: M): number;/** Whether the motion repeats. A looping motion never finishes. */loops?(ctx: MotionContext, motion: M): boolean;+ /**+ * Append every event `motion` crossed over `span` to `out`, in the order the+ * clip declares them. Wrapping belongs here for the same reason sampling does:+ * only the driver knows how long its clip runs and whether it repeats, and a+ * caller differencing two absolute times cannot tell a loop from a rewind.+ */+ events?(ctx: MotionContext, motion: M, span: MotionSpan, out: MotionEvent[]): void;+ /**+ * How far `motion` asks to move over `span`, into `out`. False when the motion+ * states no root motion — which is not the same as stating none this frame.+ */+ rootMotion?(ctx: MotionContext, motion: M, span: MotionSpan, out: RootMotionDelta): boolean;/*** Whether the motion has ended — what gates a `hasExitTime` transition. For* a driver whose end is no clock the animator keeps (a sprite clip, a spine@@ -152,6 +210,7 @@ export class MotionRegistry {ctx.world = world;ctx.entity = entity;ctx.params = params;+ ctx.extractRootMotion = false;return ctx;}@@ -159,12 +218,18 @@ export class MotionRegistry {world: null!,entity: 0 as Entity,params: {},+ extractRootMotion: false,drive: (motion, enter) => { this.driverFor(motion)?.apply?.(this.ctx_, motion, enter); },finished: (motion) => this.driverFor(motion)?.isFinished?.(this.ctx_, motion) ?? false,sample: (motion, time, pose) =>this.driverFor(motion)?.sample?.(this.ctx_, motion, time, pose) ?? false,duration: (motion) => this.driverFor(motion)?.duration?.(this.ctx_, motion) ?? 0,loops: (motion) => this.driverFor(motion)?.loops?.(this.ctx_, motion) ?? false,+ events: (motion, span, out) => {+ this.driverFor(motion)?.events?.(this.ctx_, motion, span, out);+ },+ rootDelta: (motion, span, out) =>+ this.driverFor(motion)?.rootMotion?.(this.ctx_, motion, span, out) ?? false,};}@@ -223,4 +288,12 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {const selected = blendSelection(ctx, blend);return selected ? ctx.finished(selected) : false;},+ events(ctx, blend, span, out) {+ const selected = blendSelection(ctx, blend);+ if (selected) ctx.events(selected, span, out);+ },+ rootMotion(ctx, blend, span, out) {+ const selected = blendSelection(ctx, blend);+ return selected !== null && ctx.rootDelta(selected, span, out);+ },};diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex f83813427..8bd28762e 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -372,6 +372,14 @@ export {type AnimatorBlendStop,type MotionContext,type MotionDriver,+ type MotionSpan,+ type MotionEvent,+ type RootMotionDelta,+ AnimatorEvent,+ type AnimatorEventPayload,+ type AnimatorEventSink,+ AnimatorRootMotion,+ type AnimatorRootMotionData,type AnimatorData,type AnimatorBlend1D,type AnimatorBlendThreshold,@@ -906,6 +914,10 @@ export {sampleTimeline, sampleTimelineInWorld, evaluateChannel, applyWrapMode,serializeTimelineAsset, serializeTimelineToJson, resolveChildEntity, parseAnimationClip,TrackType, InterpType, WrapMode, TIMELINE_FORMAT_VERSION,+ isRootPlacementChannel, sampleRootPlacement, createRootPlacement,+ playheadRuns, runCrosses, collectCustomEvents,+ type RootPlacement, type PlayheadRun,+ type CustomEvent, type CustomEventTrack,type SampleWorld, type SampleDeps, type SampleOptions,type TimelineAsset, type Track, type PropertyTrack, type PropertyChannel, type Keyframe,type SpriteAnimTrack, type AudioTrack, type ActivationTrack, type SpineTrack, type AnimFramesTrack,diff --git a/sdk/src/timeline/TimelineEvaluator.ts b/sdk/src/timeline/TimelineEvaluator.tsindex 2282e1543..34fbd68d3 100644--- a/sdk/src/timeline/TimelineEvaluator.ts+++ b/sdk/src/timeline/TimelineEvaluator.ts@@ -25,7 +25,7 @@ import { setNestedProperty, resolveChildEntity } from './TimelineRuntime';import { getComponent, type AnyComponentDef } from '../ecs/component';import type { Pose, PoseTrack, PoseWorld } from '../animation/pose';import { q } from '../math/quat';-import type { Entity } from '../types';+import type { Entity, Quat, Vec3 } from '../types';import type { World } from '../ecs/world';const RAD2DEG = 180 / Math.PI;@@ -161,6 +161,71 @@ function applyField(data: any, component: string, property: string, value: numbereturn setNestedProperty(data, property, value);}+// ---------------------------------------------------------------------------+// The root track — where the clip says the ENTITY goes, not how it is posed+// ---------------------------------------------------------------------------++/**+ * Whether a channel states the placement of the entity the clip is played ON —+ * the whole of root motion: a channel aimed at a child poses a bone, one aimed at+ * nothing says where the character travels. Read by both the sampler that leaves+ * these out of the pose and the extractor, so the two cannot disagree.+ */+export function isRootPlacementChannel(+ childPath: string, component: string, property: string,+): boolean {+ return childPath === '' && component === 'Transform'+ && (property.startsWith('position') || property.startsWith('rotation'));+}++/** Where a clip says its entity stands, over a base that states nothing. */+export interface RootPlacement {+ position: Vec3;+ rotation: Quat;+}++/** A placement holder to sample into; the base is neutral, see below. */+export function createRootPlacement(): RootPlacement {+ return { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } };+}++function resetRootPlacement(out: RootPlacement): void {+ out.position.x = 0; out.position.y = 0; out.position.z = 0;+ out.rotation = { w: 1, x: 0, y: 0, z: 0 };+}++/**+ * The root placement `asset` states at `time`, into `out`. Over a NEUTRAL base:+ * two of these are only ever subtracted, so the entity's own values would cancel+ * anyway while making the answer depend on where the character stood.+ *+ * False when the clip states no root track — not the same as one holding still.+ */+export function sampleRootPlacement(+ asset: TimelineAsset, time: number, out: RootPlacement,+): boolean {+ resetRootPlacement(out);+ let stated = false;+ for (const track of asset.tracks) {+ if (track.type !== TrackType.Property) continue;+ if (track.childPath !== '' || track.component !== 'Transform') continue;++ const touched = new Set<string>();+ for (const ch of track.channels) {+ if (!ch.keyframes || ch.keyframes.length === 0) continue;+ if (!isRootPlacementChannel(track.childPath, track.component, ch.property)) continue;+ if (applyField(out, 'Transform', ch.property, evaluateChannel(ch, time))) {+ touched.add(ch.property.split('.')[0]!);+ }+ }+ if (touched.size > 0) {+ finishQuaternions(out, 'Transform', touched);+ stated = true;+ }+ }+ return stated;+}+// ---------------------------------------------------------------------------// Sampler// ---------------------------------------------------------------------------diff --git a/sdk/src/timeline/index.ts b/sdk/src/timeline/index.tsindex 69017c208..fcdbcf1a1 100644--- a/sdk/src/timeline/index.ts+++ b/sdk/src/timeline/index.ts@@ -49,11 +49,22 @@ export {sampleTimelineInWorld,evaluateChannel,applyWrapMode,+ isRootPlacementChannel,+ sampleRootPlacement,+ createRootPlacement,type SampleWorld,type SampleDeps,type SampleOptions,+ type RootPlacement,} from './TimelineEvaluator';+export {+ playheadRuns,+ runCrosses,+ collectCustomEvents,+ type PlayheadRun,+} from './timelineEvents';+export {serializeTimelineAsset,serializeTimelineToJson,diff --git a/sdk/src/timeline/timelineEvents.ts b/sdk/src/timeline/timelineEvents.tsnew file mode 100644index 000000000..61e082f1a--- /dev/null+++ b/sdk/src/timeline/timelineEvents.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file timelineEvents.ts+ * @brief Which stretches of a clip a playhead covered between two times, and+ * which authored events that crossed.+ *+ * @details A fixed step never lands on an event's time, so "did it happen" is a+ * question about an INTERVAL, and the interval is not always one piece:+ * a looping clip advancing past its end covered the tail and then the+ * head, with a discontinuity between them that a single (from, to] span+ * reads as a rewind. {@link playheadRuns} is the one place that knows+ * the shape of that, so events and root motion answer the same question+ * the same way — the alternative is two wrap handlers that agree until+ * one of them is fixed.+ *+ * Pure: no world, no asset state. What a run means in clip time is all+ * that is here, so the loop seam is a unit test rather than a frame.+ */++import { WrapMode, TrackType, type TimelineAsset } from './TimelineTypes';+import type { MotionEvent } from '../animation/motion';++/**+ * A stretch of clip time the playhead covered, in the direction it covered it —+ * `to` below `from` is a ping-pong clip running backwards. `inclusiveStart` marks+ * a run that BEGINS an instant rather than continuing one: the frame a state was+ * entered, and each lap of a loop.+ */+export interface PlayheadRun {+ from: number;+ to: number;+ inclusiveStart: boolean;+}++/** Where a phase within a ping-pong cycle sits in clip time. */+function pingPongPhase(phase: number, duration: number): number {+ const cycle = duration * 2;+ const p = phase % cycle;+ return p <= duration ? p : cycle - p;+}++/**+ * The stretches of clip time a playhead covered going from `from` to `to` (both+ * in clip seconds, `to` at or after `from`) under `mode`.+ *+ * A span at least a whole pass long collapses to ONE covering run: a frame long+ * enough to lap the clip twice reporting everything twice is a stutter.+ */+export function playheadRuns(+ from: number, to: number, duration: number, mode: WrapMode, inclusiveStart: boolean,+): PlayheadRun[] {+ if (duration <= 0 || to < from) return [];+ const span = to - from;++ if (mode === WrapMode.Once) {+ const a = Math.min(Math.max(from, 0), duration);+ const b = Math.min(Math.max(to, 0), duration);+ return [{ from: a, to: b, inclusiveStart }];+ }++ if (mode === WrapMode.Loop) {+ if (span >= duration) return [{ from: 0, to: duration, inclusiveStart: true }];+ const a = from % duration;+ // Landing exactly on a lap boundary BEGINS that lap, so an event authored+ // at 0 belongs to it — the one case where the caller's half-open window+ // would drop an event rather than hand it to the run before.+ const opens = inclusiveStart || (a === 0 && from > 0);+ const b = a + span;+ if (b <= duration) return [{ from: a, to: b, inclusiveStart: opens }];+ // The playhead JUMPED from the end to the start; the head of the clip is a+ // new lap, so an event authored at 0 belongs to it.+ return [+ { from: a, to: duration, inclusiveStart: opens },+ { from: 0, to: b - duration, inclusiveStart: true },+ ];+ }++ const cycle = duration * 2;+ if (span >= cycle) return [{ from: 0, to: duration, inclusiveStart: true }];+ const runs: PlayheadRun[] = [];+ let phase = from % cycle;+ const end = phase + span;+ let first = inclusiveStart;+ while (phase < end) {+ // A turn-around is continuous in clip time — the playhead reaches the end+ // and comes back through the same instant — so only the first run of the+ // call can be inclusive.+ const next = Math.min(end, (Math.floor(phase / duration) + 1) * duration);+ runs.push({+ from: pingPongPhase(phase, duration),+ to: pingPongPhase(next, duration),+ inclusiveStart: first,+ });+ first = false;+ phase = next;+ }+ return runs;+}++/** Whether a moment at `at` falls inside `run`, in the direction it runs. */+export function runCrosses(run: PlayheadRun, at: number): boolean {+ const { from, to, inclusiveStart } = run;+ if (to > from) return (at > from || (inclusiveStart && at === from)) && at <= to;+ if (to < from) return (at < from || (inclusiveStart && at === from)) && at >= to;+ return inclusiveStart && at === from;+}++/** The event's numeric payload, or 0 where it carries none. */+function payloadValue(payload: Record<string, unknown> | undefined): number {+ const v = payload?.value;+ return typeof v === 'number' ? v : 0;+}++/** The event's string payload, or empty where it carries none. */+function payloadText(payload: Record<string, unknown> | undefined): string {+ const v = payload?.text;+ return typeof v === 'string' ? v : '';+}++/**+ * Append every custom event `asset` declares within `runs` to `out`, run by run+ * and then in declaration order, so a long frame still reports swing before hit.+ * `childPath` is not read: the event happened to the character the clip plays on.+ */+export function collectCustomEvents(+ asset: TimelineAsset, runs: readonly PlayheadRun[], out: MotionEvent[],+): void {+ for (const run of runs) {+ for (const track of asset.tracks) {+ if (track.type !== TrackType.CustomEvent) continue;+ for (const event of track.events) {+ if (!runCrosses(run, event.time)) continue;+ out.push({+ name: event.name,+ value: payloadValue(event.payload),+ text: payloadText(event.payload),+ });+ }+ }+ }+}diff --git a/sdk/src/timeline/timelineMotion.ts b/sdk/src/timeline/timelineMotion.tsindex 04bd72a2d..d8c7fa1e6 100644--- a/sdk/src/timeline/timelineMotion.ts+++ b/sdk/src/timeline/timelineMotion.ts@@ -18,12 +18,19 @@* animator is involved.*/-import type { MotionDriver, AnimatorClipMotion, MotionContext } from '../animation/motion';+import type {+ MotionDriver, AnimatorClipMotion, MotionContext, MotionSpan, MotionEvent, RootMotionDelta,+} from '../animation/motion';import type { Pose } from '../animation/pose';import { getComponent } from '../ecs/component';-import { applyWrapMode, sampleTimelineIntoPose, type SampleDeps } from './TimelineEvaluator';+import {+ applyWrapMode, sampleTimelineIntoPose, isRootPlacementChannel,+ sampleRootPlacement, createRootPlacement, type SampleDeps, type SampleOptions,+} from './TimelineEvaluator';+import { playheadRuns, collectCustomEvents } from './timelineEvents';import { resolveChildEntity } from './TimelineRuntime';import { WrapMode, type TimelineAsset } from './TimelineTypes';+import { q } from '../math/quat';import type { TimelineAPI } from './TimelineControl';export const TIMELINE_MOTION = 'timeline';@@ -36,11 +43,32 @@ function wrapOf(motion: AnimatorClipMotion, asset: TimelineAsset): WrapMode {const speedOf = (motion: AnimatorClipMotion): number => Math.max(motion.speed ?? 1, 1e-4);+/**+ * What the pose must not state while the animator is taking the root track as+ * displacement. Not a filter the animator passes in: which channels those are is+ * the evaluator's own answer, and the extractor reads the same one.+ */+const WITHOUT_ROOT: SampleOptions = { skipChannel: isRootPlacementChannel };+/*** The driver, over the app's own {@link TimelineAPI}: which clip a name resolves* to is per App, so this is built per App rather than being a module value.*/export function createTimelineMotionDriver(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion> {+ // Two placements, reused: extraction runs per animated entity per frame, and+ // one of these per call is an allocation the steady state does not need.+ const before = createRootPlacement();+ const after = createRootPlacement();++ /** The span in the CLIP's own time, split where its wrap makes it discontinuous. */+ const runsOf = (asset: TimelineAsset, motion: AnimatorClipMotion, span: MotionSpan) => {+ const speed = speedOf(motion);+ return playheadRuns(+ span.from * speed, span.to * speed,+ asset.duration, wrapOf(motion, asset), span.inclusiveStart,+ );+ };+// One deps record, re-aimed per call. The sampler asks it for the world and// the child resolver; both are the same for every entity in a frame except// the world reference, which the context supplies.@@ -56,7 +84,45 @@ export function createTimelineMotionDriver(timeline: TimelineAPI): MotionDriver<if (!asset) return false;const local = applyWrapMode(time * speedOf(motion), asset.duration, wrapOf(motion, asset));deps.world = ctx.world;- sampleTimelineIntoPose(asset, local.time, ctx.entity, deps, pose);+ sampleTimelineIntoPose(+ asset, local.time, ctx.entity, deps, pose,+ ctx.extractRootMotion ? WITHOUT_ROOT : undefined,+ );+ return true;+ },++ events(+ ctx: MotionContext, motion: AnimatorClipMotion, span: MotionSpan, out: MotionEvent[],+ ): void {+ const asset = timeline.getAsset(motion.clip);+ if (!asset) return;+ collectCustomEvents(asset, runsOf(asset, motion, span), out);+ },++ /**+ * The clip's own displacement over the span, summed run by run: a lap+ * boundary is a jump in clip time and a difference across it would read+ * as the character teleporting back to where the clip starts.+ */+ rootMotion(+ _ctx: MotionContext, motion: AnimatorClipMotion,+ span: MotionSpan, out: RootMotionDelta,+ ): boolean {+ const asset = timeline.getAsset(motion.clip);+ if (!asset || !sampleRootPlacement(asset, 0, before)) return false;++ out.position.x = 0; out.position.y = 0; out.position.z = 0;+ let turn = { w: 1, x: 0, y: 0, z: 0 };+ for (const run of runsOf(asset, motion, span)) {+ sampleRootPlacement(asset, run.from, before);+ sampleRootPlacement(asset, run.to, after);+ out.position.x += after.position.x - before.position.x;+ out.position.y += after.position.y - before.position.y;+ out.position.z += after.position.z - before.position.z;+ turn = q.mul(q.mul(after.rotation, q.conjugate(before.rotation)), turn);+ }+ out.rotation.w = turn.w; out.rotation.x = turn.x;+ out.rotation.y = turn.y; out.rotation.z = turn.z;return true;},diff --git a/sdk/tests/animatorEvents.test.ts b/sdk/tests/animatorEvents.test.tsnew file mode 100644index 000000000..abbbb2b03--- /dev/null+++ b/sdk/tests/animatorEvents.test.ts@@ -0,0 +1,341 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The claim: a clip can say what happened, and the animator says it once, on the+ * step that CROSSED it — never twice on a loop, never from a fading motion.+ */+import { describe, it, expect } from 'vitest';+import {+ Animator, AnimatorControllerAPI,+ type AnimatorData, type AnimatorControllerDef, type AnimatorEventPayload,+} from '../src/animation';+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';+import { TimelineAPI } from '../src/timeline/TimelineControl';+import { playheadRuns, collectCustomEvents } from '../src/timeline/timelineEvents';+import { defineComponent } from '../src/ecs/component';+import {+ WrapMode, TrackType, InterpType, type TimelineAsset,+} from '../src/timeline/TimelineTypes';++const E = 1;++/** Registry is per context and reset between tests, so this is taken per call. */+const probeDef = () => defineComponent('EventProbe', { x: 0 });++function makeWorld() {+ const store = new Map<unknown, Map<number, unknown>>();+ const mapOf = (c: unknown) => {+ let m = store.get(c);+ if (!m) { m = new Map(); store.set(c, m); }+ return m;+ };+ return {+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ get(e: number, c: unknown) { return mapOf(c).get(e); },+ has(e: number, c: unknown) { return mapOf(c).has(e); },+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ tryGet(e: number, c: unknown) { return mapOf(c).get(e) ?? null; },+ update(e: number, c: unknown, edit: (d: any) => void) {+ const d = mapOf(c).get(e);+ if (d === undefined) throw new Error('update: entity does not carry it');+ edit(d); mapOf(c).set(e, d);+ },+ getEntitiesWithComponents(comps: unknown[]) {+ const [first, ...rest] = comps;+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));+ },+ } as any;+}++/** A clip holding the probe at `value`, carrying the events it is given. */+function clipWith(+ value: number, events: { time: number; name: string; payload?: Record<string, unknown> }[],+ duration = 1, wrapMode: WrapMode = WrapMode.Loop,+): TimelineAsset {+ return {+ version: '1.2', type: 'timeline', duration, wrapMode,+ tracks: [+ {+ type: TrackType.Property, component: 'EventProbe', childPath: '',+ name: 'probe', channels: [{+ property: 'x',+ keyframes: [{+ time: 0, value, inTangent: 0, outTangent: 0,+ interpolation: InterpType.Linear,+ }],+ }],+ },+ {+ type: TrackType.CustomEvent, name: 'events', childPath: '',+ events: events.map(e => ({ time: e.time, name: e.name, payload: e.payload ?? {} })),+ },+ ],+ } as TimelineAsset;+}++/** The events an animator posted, in order. */+function sink(): { got: AnimatorEventPayload[]; send(e: AnimatorEventPayload): void } {+ const got: AnimatorEventPayload[] = [];+ return { got, send(e) { got.push({ ...e }); } };+}++function controllerOver(clips: Record<string, TimelineAsset>): AnimatorControllerAPI {+ const timeline = new TimelineAPI();+ for (const [name, asset] of Object.entries(clips)) timeline.registerAsset(name, asset);+ const ctrl = new AnimatorControllerAPI();+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));+ return ctrl;+}++function seed(world: any, controller: string): void {+ world.insert(E, Animator, { controller, currentState: '', enabled: true } as AnimatorData);+ world.insert(E, probeDef(), { x: 0 });+}++const oneState = (clip: string, loop = true): AnimatorControllerDef => ({+ parameters: [],+ initialState: 'Play',+ states: [{ name: 'Play', motion: { kind: TIMELINE_MOTION, clip, loop }, transitions: [] }],+});++// =============================================================================+// The window, on its own+// =============================================================================++describe('the stretch of clip a step covered', () => {+ it('is the interval, not the instant a step happened to land on', () => {+ // 0.20 → 0.25 contains 0.23; no step ever lands on 0.23 itself.+ const runs = playheadRuns(0.20, 0.25, 1, WrapMode.Loop, false);+ expect(runs).toEqual([{ from: 0.20, to: 0.25, inclusiveStart: false }]);+ });++ it('splits at a loop seam rather than reading the wrap as a rewind', () => {+ const runs = playheadRuns(0.95, 1.05, 1, WrapMode.Loop, false);+ expect(runs.length).toBe(2);+ expect(runs[0]).toEqual({ from: 0.95, to: 1, inclusiveStart: false });+ // The head of the clip is a NEW lap, so an event authored at 0 is in it.+ expect(runs[1].from).toBe(0);+ expect(runs[1].to).toBeCloseTo(0.05, 12);+ expect(runs[1].inclusiveStart).toBe(true);+ });++ it('opens a lap that a step begins exactly on', () => {+ const runs = playheadRuns(2, 2.1, 1, WrapMode.Loop, false);+ expect(runs.length).toBe(1);+ expect(runs[0].from).toBe(0);+ expect(runs[0].to).toBeCloseTo(0.1, 12);+ expect(runs[0].inclusiveStart).toBe(true);+ });++ it('closes the frame a state was entered on, which is the only zero-length one', () => {+ expect(playheadRuns(0, 0, 1, WrapMode.Loop, true))+ .toEqual([{ from: 0, to: 0, inclusiveStart: true }]);+ expect(playheadRuns(0, 0, 1, WrapMode.Loop, false))+ .toEqual([{ from: 0, to: 0, inclusiveStart: false }]);+ });++ it('covers a whole pass once however long the step was', () => {+ expect(playheadRuns(0, 7.5, 1, WrapMode.Loop, false))+ .toEqual([{ from: 0, to: 1, inclusiveStart: true }]);+ });++ it('stops at the end of a clip that does not repeat', () => {+ expect(playheadRuns(0.9, 3, 1, WrapMode.Once, false))+ .toEqual([{ from: 0.9, to: 1, inclusiveStart: false }]);+ // And says nothing more once it is parked there.+ expect(playheadRuns(3, 4, 1, WrapMode.Once, false))+ .toEqual([{ from: 1, to: 1, inclusiveStart: false }]);+ });++ it('turns around with a ping-pong clip, so a pass back crosses the same events', () => {+ const runs = playheadRuns(0.9, 1.2, 1, WrapMode.PingPong, false);+ expect(runs).toEqual([+ { from: 0.9, to: 1, inclusiveStart: false },+ { from: 1, to: 0.8, inclusiveStart: false },+ ]);+ });+});++describe('which events a window crossed', () => {+ const asset = clipWith(1, [+ { time: 0.23, name: 'swing' },+ { time: 0.31, name: 'hit' },+ { time: 0.58, name: 'recover' },+ ]);++ it('reports several in one step, in the order the clip declares them', () => {+ const out: { name: string }[] = [];+ collectCustomEvents(asset, playheadRuns(0.20, 0.40, 1, WrapMode.Loop, false), out as never);+ expect(out.map(e => e.name)).toEqual(['swing', 'hit']);+ });++ it('reports none for a window that crossed nothing', () => {+ const out: { name: string }[] = [];+ collectCustomEvents(asset, playheadRuns(0.35, 0.40, 1, WrapMode.Loop, false), out as never);+ expect(out).toEqual([]);+ });+});++// =============================================================================+// Through the animator+// =============================================================================++describe('an animator over a clip that declares events', () => {+ it('fires each one exactly once on the way past', () => {+ const world = makeWorld();+ const ctrl = controllerOver({+ 'attack.estimeline': clipWith(1, [+ { time: 0, name: 'start' },+ { time: 0.23, name: 'swing' },+ { time: 0.31, name: 'hit' },+ { time: 0.58, name: 'recover' },+ ], 1, WrapMode.Once),+ });+ ctrl.registerController('a', oneState('attack.estimeline', false));+ seed(world, 'a');++ const events = sink();+ for (let i = 0; i < 40; i++) ctrl.update(world, 0.05, events);++ expect(events.got.map(e => e.name)).toEqual(['start', 'swing', 'hit', 'recover']);+ });++ it('carries the payload the clip authored', () => {+ const world = makeWorld();+ const ctrl = controllerOver({+ 'attack.estimeline': clipWith(1, [+ { time: 0.2, name: 'hit', payload: { value: 12, text: 'blade' } },+ ], 1, WrapMode.Once),+ });+ ctrl.registerController('a', oneState('attack.estimeline', false));+ seed(world, 'a');++ const events = sink();+ for (let i = 0; i < 10; i++) ctrl.update(world, 0.05, events);+ expect(events.got).toEqual([{ entity: E, name: 'hit', value: 12, text: 'blade' }]);+ });++ it('fires once per lap of a looping clip, including at the boundary', () => {+ const world = makeWorld();+ const ctrl = controllerOver({+ 'walk.estimeline': clipWith(1, [+ { time: 0, name: 'left' },+ { time: 0.5, name: 'right' },+ ]),+ });+ ctrl.registerController('w', oneState('walk.estimeline'));+ seed(world, 'w');++ const events = sink();+ // Ten laps at a step that never lands on either event.+ for (let i = 0; i < 1000; i++) ctrl.update(world, 0.01, events);++ const left = events.got.filter(e => e.name === 'left').length;+ const right = events.got.filter(e => e.name === 'right').length;+ // The first `left` is the frame the state was entered on, then one a lap.+ expect(left).toBe(10);+ expect(right).toBe(10);+ // And they alternate: a seam handler that fired the head of the lap early+ // would report two lefts in a row.+ expect(events.got.map(e => e.name).slice(0, 4))+ .toEqual(['left', 'right', 'left', 'right']);+ });++ it('says nothing when nobody is listening, and still plays', () => {+ const world = makeWorld();+ const ctrl = controllerOver({ 'walk.estimeline': clipWith(7, [{ time: 0.2, name: 'x' }]) });+ ctrl.registerController('w', oneState('walk.estimeline'));+ seed(world, 'w');+ for (let i = 0; i < 10; i++) ctrl.update(world, 0.05);+ expect((world.get(E, probeDef()) as { x: number }).x).toBe(7);+ });+});++describe('a crossfade decides whose events those are', () => {+ /** Idle → Attack on a trigger, blending over `fade` seconds. */+ const graph = (fade: number): AnimatorControllerDef => ({+ parameters: [{ name: 'go', type: 'trigger' }],+ initialState: 'Idle',+ states: [+ {+ name: 'Idle',+ motion: { kind: TIMELINE_MOTION, clip: 'idle.estimeline', loop: true },+ transitions: [{+ to: 'Attack', conditions: [{ param: 'go', op: 'trigger' }], duration: fade,+ }],+ },+ {+ name: 'Attack',+ motion: { kind: TIMELINE_MOTION, clip: 'attack.estimeline', loop: false },+ transitions: [],+ },+ ],+ });++ function run(fade: number): AnimatorEventPayload[] {+ const world = makeWorld();+ const ctrl = controllerOver({+ // Idle keeps declaring events all the way through the fade.+ 'idle.estimeline': clipWith(1, [+ { time: 0.1, name: 'idle-tick' }, { time: 0.3, name: 'idle-tick' },+ { time: 0.5, name: 'idle-tick' }, { time: 0.7, name: 'idle-tick' },+ { time: 0.9, name: 'idle-tick' },+ ]),+ 'attack.estimeline': clipWith(2, [+ { time: 0, name: 'attack-start' }, { time: 0.2, name: 'attack-hit' },+ ], 1, WrapMode.Once),+ });+ ctrl.registerController('g', graph(fade));+ seed(world, 'g');++ const events = sink();+ for (let i = 0; i < 10; i++) ctrl.update(world, 0.05, events);+ events.got.length = 0;+ ctrl.setTrigger(E, 'go');+ for (let i = 0; i < 10; i++) ctrl.update(world, 0.05, events);+ return events.got;+ }++ it('gives them to the state being entered, from its own first frame', () => {+ expect(run(0.3).map(e => e.name)).toEqual(['attack-start', 'attack-hit']);+ });++ it('and the answer does not depend on how long the blend is', () => {+ expect(run(0).map(e => e.name)).toEqual(run(0.3).map(e => e.name));+ });+});++describe('a 1D blend', () => {+ it('reports the events of the stop it is playing, and only those', () => {+ const world = makeWorld();+ const ctrl = controllerOver({+ 'walk.estimeline': clipWith(1, [{ time: 0.4, name: 'walk-step' }]),+ 'run.estimeline': clipWith(2, [{ time: 0.4, name: 'run-step' }]),+ });+ ctrl.registerController('b', {+ parameters: [{ name: 'speed', type: 'float', default: 0 }],+ initialState: 'Loco',+ states: [{+ name: 'Loco',+ motion: {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: { kind: TIMELINE_MOTION, clip: 'walk.estimeline', loop: true } },+ { value: 5, motion: { kind: TIMELINE_MOTION, clip: 'run.estimeline', loop: true } },+ ],+ },+ transitions: [],+ }],+ });+ seed(world, 'b');++ const events = sink();+ for (let i = 0; i < 20; i++) ctrl.update(world, 0.05, events);+ expect(events.got.map(e => e.name)).toEqual(['walk-step']);++ events.got.length = 0;+ ctrl.setFloat(E, 'speed', 9);+ for (let i = 0; i < 20; i++) ctrl.update(world, 0.05, events);+ expect(events.got.map(e => e.name)).toEqual(['run-step']);+ });+});diff --git a/sdk/tests/animatorRootMotion.test.ts b/sdk/tests/animatorRootMotion.test.tsnew file mode 100644index 000000000..cc0ee89e0--- /dev/null+++ b/sdk/tests/animatorRootMotion.test.ts@@ -0,0 +1,263 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The claim: a clip that moves the character states a REQUEST and moves nothing;+ * the same clip in a state not declaring it stays an ordinary property animation.+ */+import { describe, it, expect } from 'vitest';+import {+ Animator, AnimatorControllerAPI, AnimatorRootMotion,+ type AnimatorData, type AnimatorControllerDef, type AnimatorRootMotionData,+} from '../src/animation';+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';+import { TimelineAPI } from '../src/timeline/TimelineControl';+import { sampleRootPlacement, createRootPlacement } from '../src/timeline/TimelineEvaluator';+import { Transform, defineComponent, type TransformData } from '../src/ecs/component';+import { q } from '../src/math/quat';+import {+ WrapMode, TrackType, InterpType, type TimelineAsset, type Keyframe,+} from '../src/timeline/TimelineTypes';++const E = 1;++/** Registry is per context and reset between tests, so this is taken per call. */+const probeDef = () => defineComponent('RootProbe', { x: 0 });++function makeWorld() {+ const store = new Map<unknown, Map<number, unknown>>();+ const mapOf = (c: unknown) => {+ let m = store.get(c);+ if (!m) { m = new Map(); store.set(c, m); }+ return m;+ };+ return {+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ get(e: number, c: unknown) { return mapOf(c).get(e); },+ has(e: number, c: unknown) { return mapOf(c).has(e); },+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ tryGet(e: number, c: unknown) { return mapOf(c).get(e) ?? null; },+ update(e: number, c: unknown, edit: (d: any) => void) {+ const d = mapOf(c).get(e);+ if (d === undefined) throw new Error('update: entity does not carry it');+ edit(d); mapOf(c).set(e, d);+ },+ getEntitiesWithComponents(comps: unknown[]) {+ const [first, ...rest] = comps;+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));+ },+ } as any;+}++const key = (time: number, value: number): Keyframe =>+ ({ time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear });++/**+ * A clip that walks its OWN entity `forward` units along -Z and turns it `yawDeg`+ * about world up, while holding a probe at 5 — the probe being the part of the+ * same clip that is an ordinary pose and must land whatever the root does.+ */+function travelClip(+ forward: number, duration = 1, wrapMode: WrapMode = WrapMode.Once, yawDeg = 0,+): TimelineAsset {+ const half = (yawDeg * Math.PI) / 360;+ return {+ version: '1.2', type: 'timeline', duration, wrapMode,+ tracks: [+ {+ type: TrackType.Property, component: 'Transform', childPath: '',+ name: 'root', channels: [+ { property: 'position.z', keyframes: [key(0, 0), key(duration, -forward)] },+ { property: 'rotation.w', keyframes: [key(0, 1), key(duration, Math.cos(half))] },+ { property: 'rotation.y', keyframes: [key(0, 0), key(duration, Math.sin(half))] },+ ],+ },+ {+ type: TrackType.Property, component: 'RootProbe', childPath: '',+ name: 'probe', channels: [{ property: 'x', keyframes: [key(0, 5)] }],+ },+ ],+ } as TimelineAsset;+}++function controllerOver(asset: TimelineAsset): AnimatorControllerAPI {+ const timeline = new TimelineAPI();+ timeline.registerAsset('travel.estimeline', asset);+ const ctrl = new AnimatorControllerAPI();+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));+ return ctrl;+}++const graph = (rootMotion: boolean, loop: boolean): AnimatorControllerDef => ({+ parameters: [],+ initialState: 'Travel',+ states: [{+ name: 'Travel',+ motion: { kind: TIMELINE_MOTION, clip: 'travel.estimeline', loop },+ rootMotion,+ transitions: [],+ }],+});++interface Setup {+ world: any;+ ctrl: AnimatorControllerAPI;+}++function seed(asset: TimelineAsset, rootMotion: boolean, opts: {+ loop?: boolean; publish?: boolean; enabled?: boolean; yaw?: number;+} = {}): Setup {+ const world = makeWorld();+ const ctrl = controllerOver(asset);+ ctrl.registerController('g', graph(rootMotion, opts.loop ?? false));+ world.insert(E, Animator, { controller: 'g', currentState: '', enabled: true } as AnimatorData);+ world.insert(E, probeDef(), { x: 0 });+ world.insert(E, Transform, {+ position: { x: 0, y: 0, z: 0 },+ rotation: q.axis('y', ((opts.yaw ?? 0) * Math.PI) / 180),+ scale: { x: 1, y: 1, z: 1 },+ } as unknown as TransformData);+ if (opts.publish !== false) {+ world.insert(E, AnimatorRootMotion, {+ enabled: opts.enabled ?? true,+ active: false,+ deltaPosition: { x: 0, y: 0, z: 0 },+ deltaRotation: { w: 1, x: 0, y: 0, z: 0 },+ deltaTime: 0,+ } as AnimatorRootMotionData);+ }+ return { world, ctrl };+}++/** Run `frames` steps, summing what the animator asked for on the way. */+function drive(setup: Setup, frames: number, dt = 0.05): {+ asked: { x: number; y: number; z: number };+ turn: { w: number; x: number; y: number; z: number };+ seconds: number;+ activeFrames: number;+} {+ const asked = { x: 0, y: 0, z: 0 };+ let turn = { w: 1, x: 0, y: 0, z: 0 };+ let seconds = 0;+ let activeFrames = 0;+ for (let i = 0; i < frames; i++) {+ setup.ctrl.update(setup.world, dt);+ if (!setup.world.has(E, AnimatorRootMotion)) continue;+ const rm = setup.world.get(E, AnimatorRootMotion) as AnimatorRootMotionData;+ asked.x += rm.deltaPosition.x;+ asked.y += rm.deltaPosition.y;+ asked.z += rm.deltaPosition.z;+ turn = q.mul(rm.deltaRotation, turn);+ seconds += rm.deltaTime;+ if (rm.active) activeFrames++;+ }+ return { asked, turn, seconds, activeFrames };+}++const positionOf = (world: any) => (world.get(E, Transform) as TransformData).position;+const probeX = (world: any) => (world.get(E, probeDef()) as { x: number }).x;++// =============================================================================+// The root track, read on its own+// =============================================================================++describe('what a clip says about its own entity', () => {+ it('is read over a neutral base, so an unanimated channel contributes nothing', () => {+ const out = createRootPlacement();+ expect(sampleRootPlacement(travelClip(300), 0.5, out)).toBe(true);+ expect(out.position.z).toBeCloseTo(-150, 6);+ expect(out.position.x).toBe(0);+ });++ it('is absent from a clip that only poses bones', () => {+ const bonesOnly: TimelineAsset = {+ version: '1.2', type: 'timeline', duration: 1, wrapMode: WrapMode.Loop,+ tracks: [{+ type: TrackType.Property, component: 'Transform', childPath: 'Bone',+ name: 'bone', channels: [{ property: 'position.z', keyframes: [key(0, 9)] }],+ }],+ } as TimelineAsset;+ expect(sampleRootPlacement(bonesOnly, 0.5, createRootPlacement())).toBe(false);+ });+});++// =============================================================================+// Through the animator+// =============================================================================++describe('a state that declares root motion', () => {+ it('asks to move the whole way and moves the entity none of it', () => {+ const setup = seed(travelClip(300), true);+ const { asked, seconds } = drive(setup, 30);++ expect(asked.z).toBeCloseTo(-300, 4);+ expect(positionOf(setup.world).z).toBe(0);+ // The same clip's other channels still land: "the entity did not move"+ // is also what a clip nobody sampled looks like.+ expect(probeX(setup.world)).toBe(5);+ // Every step but the one the state was entered on, which covered no time.+ expect(seconds).toBeCloseTo(29 * 0.05, 4);+ });++ it('is what suppresses the write, not the component that publishes it', () => {+ const setup = seed(travelClip(300), true, { publish: false });+ drive(setup, 30);+ expect(positionOf(setup.world).z).toBe(0);+ expect(probeX(setup.world)).toBe(5);+ });++ it('keeps asking across a loop seam instead of unwinding at it', () => {+ const setup = seed(travelClip(300, 1, WrapMode.Loop), true, { loop: true });+ // 59 steps of 0.05s past the entry frame: 2.95 laps of 300 units.+ const { asked } = drive(setup, 60);+ expect(asked.z).toBeCloseTo(-300 * 2.95, 3);+ });++ it('states the turn the clip asks for, in the character’s own frame', () => {+ const setup = seed(travelClip(0, 1, WrapMode.Once, 90), true);+ const { turn } = drive(setup, 30);+ expect(q.toEuler(q.normalize(turn))[1]).toBeCloseTo(90, 3);+ });++ it('states the displacement in world space, so a turned character asks the other way', () => {+ const setup = seed(travelClip(300), true, { yaw: 180 });+ const { asked } = drive(setup, 30);+ expect(asked.z).toBeCloseTo(300, 3);+ expect(Math.abs(asked.x)).toBeLessThan(1e-6);+ });++ it('says it is driving on every frame of the state, still moment or not', () => {+ // Nothing moves in the second half; `active` is the state's declaration.+ const held: TimelineAsset = {+ version: '1.2', type: 'timeline', duration: 1, wrapMode: WrapMode.Once,+ tracks: [{+ type: TrackType.Property, component: 'Transform', childPath: '',+ name: 'root', channels: [{+ property: 'position.z', keyframes: [key(0, 0), key(0.5, -100), key(1, -100)],+ }],+ }],+ } as TimelineAsset;+ const setup = seed(held, true);+ const { activeFrames } = drive(setup, 30);+ expect(activeFrames).toBe(30);+ });+});++describe('the same clip in a state that does not', () => {+ it('is an ordinary property animation and moves the entity', () => {+ const setup = seed(travelClip(300), false);+ const { asked, activeFrames } = drive(setup, 30);+ expect(positionOf(setup.world).z).toBeCloseTo(-300, 4);+ expect(activeFrames).toBe(0);+ expect(asked.z).toBe(0);+ });+});++describe('publishing turned off', () => {+ it('stops the request without letting the clip move the entity instead', () => {+ const setup = seed(travelClip(300), true, { enabled: false });+ const { asked, activeFrames } = drive(setup, 30);+ expect(activeFrames).toBe(0);+ expect(asked.z).toBe(0);+ expect(positionOf(setup.world).z).toBe(0);+ });+});