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.

feat(anim): a blend over a plane, by the operation the line already used

esenginebe89f77346ae
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 580938592..e998db0dc 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 114,
"beta": 101,
- "experimental": 1841,
+ "experimental": 1847,
"deprecated": 3
},
- "total": 2056,
+ "total": 2062,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 48a00655e..d26297254 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: 114 public · 94 beta · 1680 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1686 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -410,6 +410,20 @@ parameter: string
thresholds: AnimatorBlendStop[]
```
+## AnimatorBlend2DMotion — interface @experimental
+```
+kind: "blend2d"
+parameterX: string
+parameterY: string
+points: AnimatorBlendPoint[]
+```
+
+## AnimatorBlendPoint — interface @experimental
+```
+motion: AnimatorMotion
+position: { x: number; y: number; }
+```
+
## AnimatorBlendStop — interface @experimental
```
motion: AnimatorMotion
@@ -515,7 +529,7 @@ send: (event: AnimatorEventPayload) => void
## AnimatorMotion — type @experimental
```
-AnimatorClipMotion | AnimatorBlend1DMotion
+| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
```
## AnimatorParam — interface @experimental
@@ -5128,6 +5142,7 @@ shift: boolean
## MotionContext — interface @experimental
```
+borrowMix: () => WeightedPose[]
borrowPose: () => Pose
drive: (motion: AnimatorMotion, enter: boolean) => void
duration: (motion: AnimatorMotion) => number
@@ -5137,6 +5152,7 @@ extractRootMotion: boolean
finished: (motion: AnimatorMotion) => boolean
loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+releaseMix: (mix: WeightedPose[]) => void
releasePose: (pose: Pose) => void
rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => boolean
sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
@@ -10826,6 +10842,16 @@ MotionDriver<AnimatorBlend1DMotion>
(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>
```
+## blend2DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend2DMotion>
+```
+
+## blend2DWeights — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -11471,6 +11497,11 @@ DiagnosticsPlugin
(cell: WorldCell, x: number, z: number): number
```
+## dominantBlendPoint — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number): AnimatorBlendPoint | null
+```
+
## dragPlugin — const @experimental
```
DragPlugin
@@ -12121,6 +12152,11 @@ InputRouter
(d: Dimension) => boolean
```
+## isBlend2D — function @experimental
+```
+(m: AnimatorMotion): m is AnimatorBlend2DMotion
+```
+
## isBuiltinComponent — function @experimental
```
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 67843b099..4c31d723c 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: 114 public · 99 beta · 1699 experimental · 3 deprecated
+Symbols: 114 public · 99 beta · 1705 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -410,6 +410,20 @@ parameter: string
thresholds: AnimatorBlendStop[]
```
+## AnimatorBlend2DMotion — interface @experimental
+```
+kind: "blend2d"
+parameterX: string
+parameterY: string
+points: AnimatorBlendPoint[]
+```
+
+## AnimatorBlendPoint — interface @experimental
+```
+motion: AnimatorMotion
+position: { x: number; y: number; }
+```
+
## AnimatorBlendStop — interface @experimental
```
motion: AnimatorMotion
@@ -515,7 +529,7 @@ send: (event: AnimatorEventPayload) => void
## AnimatorMotion — type @experimental
```
-AnimatorClipMotion | AnimatorBlend1DMotion
+| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
```
## AnimatorParam — interface @experimental
@@ -5141,6 +5155,7 @@ shift: boolean
## MotionContext — interface @experimental
```
+borrowMix: () => WeightedPose[]
borrowPose: () => Pose
drive: (motion: AnimatorMotion, enter: boolean) => void
duration: (motion: AnimatorMotion) => number
@@ -5150,6 +5165,7 @@ extractRootMotion: boolean
finished: (motion: AnimatorMotion) => boolean
loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+releaseMix: (mix: WeightedPose[]) => void
releasePose: (pose: Pose) => void
rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => boolean
sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
@@ -11034,6 +11050,16 @@ MotionDriver<AnimatorBlend1DMotion>
(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>
```
+## blend2DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend2DMotion>
+```
+
+## blend2DWeights — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -11704,6 +11730,11 @@ DiagnosticsPlugin
(cell: WorldCell, x: number, z: number): number
```
+## dominantBlendPoint — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number): AnimatorBlendPoint | null
+```
+
## dragPlugin — const @experimental
```
DragPlugin
@@ -12364,6 +12395,11 @@ InputRouter
(d: Dimension) => boolean
```
+## isBlend2D — function @experimental
+```
+(m: AnimatorMotion): m is AnimatorBlend2DMotion
+```
+
## isBuiltinComponent — function @experimental
```
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 6181f6f73..8dd8b54ea 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: 114 public · 96 beta · 1679 experimental · 3 deprecated
+Symbols: 114 public · 96 beta · 1685 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -405,6 +405,20 @@ parameter: string
thresholds: AnimatorBlendStop[]
```
+## AnimatorBlend2DMotion — interface @experimental
+```
+kind: "blend2d"
+parameterX: string
+parameterY: string
+points: AnimatorBlendPoint[]
+```
+
+## AnimatorBlendPoint — interface @experimental
+```
+motion: AnimatorMotion
+position: { x: number; y: number; }
+```
+
## AnimatorBlendStop — interface @experimental
```
motion: AnimatorMotion
@@ -510,7 +524,7 @@ send: (event: AnimatorEventPayload) => void
## AnimatorMotion — type @experimental
```
-AnimatorClipMotion | AnimatorBlend1DMotion
+| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
```
## AnimatorParam — interface @experimental
@@ -5123,6 +5137,7 @@ shift: boolean
## MotionContext — interface @experimental
```
+borrowMix: () => WeightedPose[]
borrowPose: () => Pose
drive: (motion: AnimatorMotion, enter: boolean) => void
duration: (motion: AnimatorMotion) => number
@@ -5132,6 +5147,7 @@ extractRootMotion: boolean
finished: (motion: AnimatorMotion) => boolean
loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+releaseMix: (mix: WeightedPose[]) => void
releasePose: (pose: Pose) => void
rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => boolean
sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
@@ -10821,6 +10837,16 @@ MotionDriver<AnimatorBlend1DMotion>
(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>
```
+## blend2DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend2DMotion>
+```
+
+## blend2DWeights — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -11466,6 +11492,11 @@ DiagnosticsPlugin
(cell: WorldCell, x: number, z: number): number
```
+## dominantBlendPoint — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number): AnimatorBlendPoint | null
+```
+
## dragPlugin — const @experimental
```
DragPlugin
@@ -12116,6 +12147,11 @@ InputRouter
(d: Dimension) => boolean
```
+## isBlend2D — function @experimental
+```
+(m: AnimatorMotion): m is AnimatorBlend2DMotion
+```
+
## isBuiltinComponent — function @experimental
```
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ecc9526f2..b85533fd8 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: 114 public · 94 beta · 1701 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1707 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -405,6 +405,20 @@ parameter: string
thresholds: AnimatorBlendStop[]
```
+## AnimatorBlend2DMotion — interface @experimental
+```
+kind: "blend2d"
+parameterX: string
+parameterY: string
+points: AnimatorBlendPoint[]
+```
+
+## AnimatorBlendPoint — interface @experimental
+```
+motion: AnimatorMotion
+position: { x: number; y: number; }
+```
+
## AnimatorBlendStop — interface @experimental
```
motion: AnimatorMotion
@@ -510,7 +524,7 @@ send: (event: AnimatorEventPayload) => void
## AnimatorMotion — type @experimental
```
-AnimatorClipMotion | AnimatorBlend1DMotion
+| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
```
## AnimatorParam — interface @experimental
@@ -5371,6 +5385,7 @@ shift: boolean
## MotionContext — interface @experimental
```
+borrowMix: () => WeightedPose[]
borrowPose: () => Pose
drive: (motion: AnimatorMotion, enter: boolean) => void
duration: (motion: AnimatorMotion) => number
@@ -5380,6 +5395,7 @@ extractRootMotion: boolean
finished: (motion: AnimatorMotion) => boolean
loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+releaseMix: (mix: WeightedPose[]) => void
releasePose: (pose: Pose) => void
rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => boolean
sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
@@ -11075,6 +11091,16 @@ MotionDriver<AnimatorBlend1DMotion>
(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>
```
+## blend2DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend2DMotion>
+```
+
+## blend2DWeights — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -11725,6 +11751,11 @@ DiagnosticsPlugin
(cell: WorldCell, x: number, z: number): number
```
+## dominantBlendPoint — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number): AnimatorBlendPoint | null
+```
+
## dragPlugin — const @experimental
```
DragPlugin
@@ -12385,6 +12416,11 @@ InputRouter
(d: Dimension) => boolean
```
+## isBlend2D — function @experimental
+```
+(m: AnimatorMotion): m is AnimatorBlend2DMotion
+```
+
## isBuiltinComponent — function @experimental
```
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e4f80674b..e07a83d4f 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: 114 public · 94 beta · 1691 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1697 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -405,6 +405,20 @@ parameter: string
thresholds: AnimatorBlendStop[]
```
+## AnimatorBlend2DMotion — interface @experimental
+```
+kind: "blend2d"
+parameterX: string
+parameterY: string
+points: AnimatorBlendPoint[]
+```
+
+## AnimatorBlendPoint — interface @experimental
+```
+motion: AnimatorMotion
+position: { x: number; y: number; }
+```
+
## AnimatorBlendStop — interface @experimental
```
motion: AnimatorMotion
@@ -510,7 +524,7 @@ send: (event: AnimatorEventPayload) => void
## AnimatorMotion — type @experimental
```
-AnimatorClipMotion | AnimatorBlend1DMotion
+| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
```
## AnimatorParam — interface @experimental
@@ -5130,6 +5144,7 @@ shift: boolean
## MotionContext — interface @experimental
```
+borrowMix: () => WeightedPose[]
borrowPose: () => Pose
drive: (motion: AnimatorMotion, enter: boolean) => void
duration: (motion: AnimatorMotion) => number
@@ -5139,6 +5154,7 @@ extractRootMotion: boolean
finished: (motion: AnimatorMotion) => boolean
loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+releaseMix: (mix: WeightedPose[]) => void
releasePose: (pose: Pose) => void
rootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => boolean
sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
@@ -10849,6 +10865,16 @@ MotionDriver<AnimatorBlend1DMotion>
(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>
```
+## blend2DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend2DMotion>
+```
+
+## blend2DWeights — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -11494,6 +11520,11 @@ DiagnosticsPlugin
(cell: WorldCell, x: number, z: number): number
```
+## dominantBlendPoint — function @experimental
+```
+(blend: AnimatorBlend2DMotion, x: number, y: number): AnimatorBlendPoint | null
+```
+
## dragPlugin — const @experimental
```
DragPlugin
@@ -12149,6 +12180,11 @@ InputRouter
(d: Dimension) => boolean
```
+## isBlend2D — function @experimental
+```
+(m: AnimatorMotion): m is AnimatorBlend2DMotion
+```
+
## isBuiltinComponent — function @experimental
```
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index b2a9840f8..c38b817af 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -22,7 +22,7 @@ import { isUuidRef } from '../asset/AssetRegistry';
import type { Entity } from '../types';
import type { World } from '../ecs/world';
import {
- MotionRegistry, blend1DMotionDriver,
+ MotionRegistry, blend1DMotionDriver, blend2DMotionDriver,
type AnimatorMotion, type AnimatorClipMotion, type AnimatorBlend1DMotion,
type MotionContext, type MotionDriver, type MotionEvent, type MotionSpan,
type RootMotionDelta,
@@ -511,6 +511,7 @@ export class AnimatorControllerAPI {
// which is what keeps this file from importing them.
this.motions_.register(SPRITE_MOTION, spriteMotionDriver);
this.motions_.register('blend1d', blend1DMotionDriver);
+ this.motions_.register('blend2d', blend2DMotionDriver);
}
/**
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index bf29256ef..d1ad7a483 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -139,10 +139,16 @@ export {
selectBlendStop,
blend1DPair,
blend1DMotionDriver,
+ blend2DMotionDriver,
+ blend2DWeights,
+ dominantBlendPoint,
isBlend1D,
+ isBlend2D,
type AnimatorMotion,
type AnimatorClipMotion,
type AnimatorBlend1DMotion,
+ type AnimatorBlend2DMotion,
+ type AnimatorBlendPoint,
type AnimatorBlendStop,
type Blend1DPair,
type MotionContext,
diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.ts
index 1143e2368..de516f88c 100644
--- a/sdk/src/animation/motion.ts
+++ b/sdk/src/animation/motion.ts
@@ -55,12 +55,36 @@ export interface AnimatorBlend1DMotion {
thresholds: AnimatorBlendStop[];
}
-export type AnimatorMotion = AnimatorClipMotion | AnimatorBlend1DMotion;
+/** One stop of a 2D blend, placed in the plane the two parameters span. */
+export interface AnimatorBlendPoint {
+ position: { x: number; y: number };
+ motion: AnimatorMotion;
+}
+
+/**
+ * Selection among motions by TWO parameters. What a 1D blend cannot say is any
+ * locomotion that turns: forward speed and strafe are one motion here, where
+ * stacking two 1D blends would make the character pick a direction and a speed
+ * independently and land between the clips that describe neither.
+ */
+export interface AnimatorBlend2DMotion {
+ kind: 'blend2d';
+ parameterX: string;
+ parameterY: string;
+ points: AnimatorBlendPoint[];
+}
+
+export type AnimatorMotion =
+ | AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion;
export function isBlend1D(m: AnimatorMotion): m is AnimatorBlend1DMotion {
return m.kind === 'blend1d';
}
+export function isBlend2D(m: AnimatorMotion): m is AnimatorBlend2DMotion {
+ return m.kind === 'blend2d';
+}
+
// =============================================================================
// What a motion says happened, and how far it asks to move
// =============================================================================
@@ -130,6 +154,12 @@ export interface MotionContext {
*/
borrowPose(): Pose;
releasePose(pose: Pose): void;
+ /**
+ * Borrow a list to gather weighted poses into. Its entries are reused, so a
+ * caller fills a PREFIX and passes the count on rather than truncating it.
+ */
+ borrowMix(): WeightedPose[];
+ releaseMix(mix: WeightedPose[]): void;
/**
* 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
@@ -191,10 +221,10 @@ export interface MotionDriver<M extends AnimatorMotion = AnimatorMotion> {
*/
export class MotionRegistry {
private readonly drivers_ = new Map<string, MotionDriver<never>>();
- /** Scratch poses lent to composite motions. A pool and not one buffer per
- * driver: nesting decides how many are live at once, and only the stack
- * knows that. */
+ /** Scratch lent to composite motions. Pools and not one buffer per driver:
+ * nesting decides how many are live at once, and only the stack knows that. */
private readonly posePool_: Pose[] = [];
+ private readonly mixPool_: WeightedPose[][] = [];
register<M extends AnimatorMotion>(kind: M['kind'], driver: MotionDriver<M>): void {
this.drivers_.set(kind, driver as MotionDriver<never>);
@@ -244,6 +274,8 @@ export class MotionRegistry {
this.driverFor(motion)?.rootMotion?.(this.ctx_, motion, span, out) ?? false,
borrowPose: () => this.posePool_.pop() ?? new Pose(),
releasePose: (pose) => { this.posePool_.push(pose); },
+ borrowMix: () => this.mixPool_.pop() ?? [],
+ releaseMix: (mix) => { this.mixPool_.push(mix); },
};
}
@@ -320,9 +352,10 @@ function blendValue(ctx: MotionContext, blend: AnimatorBlend1DMotion): number {
* cannot find its parent's operands here. Reused for the same reason {@link PAIR}
* is: mixing is the steady state of an animated entity, not an event.
*/
-const MIX: [WeightedPose, WeightedPose] = [
- { pose: null!, weight: 0 }, { pose: null!, weight: 0 },
-];
+/** Grow `mix` to hold `count` weighted poses, keeping the entries already in it. */
+function mixCapacity(mix: WeightedPose[], count: number): void {
+ while (mix.length < count) mix.push({ pose: null!, weight: 0 });
+}
/**
* A blend states values, so it MIXES: at 0.5 between walk and run the character
@@ -354,6 +387,7 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {
const from = ctx.borrowPose();
const to = ctx.borrowPose();
+ const mix = ctx.borrowMix();
try {
from.reset();
to.reset();
@@ -365,11 +399,13 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {
if (!sampledTo) return sampledFrom && ctx.sample(lower.motion, ta, pose);
if (!sampledFrom) return ctx.sample(upper.motion, tb, pose);
- MIX[0].pose = from; MIX[0].weight = 1 - t;
- MIX[1].pose = to; MIX[1].weight = t;
- mixPoses(MIX, pose, ctx.world);
+ mixCapacity(mix, 2);
+ mix[0]!.pose = from; mix[0]!.weight = 1 - t;
+ mix[1]!.pose = to; mix[1]!.weight = t;
+ mixPoses(mix, pose, ctx.world, 2);
return true;
} finally {
+ ctx.releaseMix(mix);
ctx.releasePose(to);
ctx.releasePose(from);
}
@@ -402,3 +438,180 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {
return selected !== null && ctx.rootDelta(selected, span, out);
},
};
+
+// =============================================================================
+// 2D blend — the same mixing, over a plane instead of a line
+// =============================================================================
+
+/**
+ * Gradient-band weights, normalized to sum to one: each point keeps what the
+ * neighbour nearest to pushing it out leaves it. That puts a sample standing on a
+ * clip entirely on that clip, and holds one outside the hull by its nearest edge
+ * rather than letting it fall to nothing. Only `weight` is written.
+ */
+export function blend2DWeights(
+ blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number }[],
+): void {
+ const points = blend.points;
+ let total = 0;
+ for (let i = 0; i < points.length; i++) {
+ const pi = points[i]!.position;
+ let weight = 1;
+ for (let j = 0; j < points.length && weight > 0; j++) {
+ if (j === i) continue;
+ const ijx = points[j]!.position.x - pi.x;
+ const ijy = points[j]!.position.y - pi.y;
+ const span = ijx * ijx + ijy * ijy;
+ if (span <= 0) continue;
+ const along = ((x - pi.x) * ijx + (y - pi.y) * ijy) / span;
+ if (1 - along < weight) weight = 1 - along;
+ }
+ out[i]!.weight = weight > 0 ? weight : 0;
+ total += out[i]!.weight;
+ }
+ // Two points at the same place, or none: nothing said where the sample is,
+ // so the first point answers rather than the pose collapsing to the world.
+ if (total <= 0) {
+ if (points.length > 0) out[0]!.weight = 1;
+ return;
+ }
+ for (let i = 0; i < points.length; i++) out[i]!.weight /= total;
+}
+
+/** Read into on every call and consumed before anything re-enters — this module
+ * never calls out while it holds a claim on this. */
+const DOMINANT: { weight: number }[] = [];
+
+/** The point carrying the most weight: what a motion that can only be SWITCHED
+ * to gets, and who speaks for the blend's events and its end. */
+export function dominantBlendPoint(
+ blend: AnimatorBlend2DMotion, x: number, y: number,
+): AnimatorBlendPoint | null {
+ const points = blend.points;
+ if (points.length === 0) return null;
+ while (DOMINANT.length < points.length) DOMINANT.push({ weight: 0 });
+ blend2DWeights(blend, x, y, DOMINANT);
+ let best = 0;
+ for (let i = 1; i < points.length; i++) {
+ if (DOMINANT[i]!.weight > DOMINANT[best]!.weight) best = i;
+ }
+ return points[best]!;
+}
+
+/** Where this blend sits in its plane, both parameters being floats even when
+ * nothing set them. */
+function blend2DAt(ctx: MotionContext, blend: AnimatorBlend2DMotion): { x: number; y: number } {
+ AT.x = Number(ctx.params[blend.parameterX] ?? 0);
+ AT.y = Number(ctx.params[blend.parameterY] ?? 0);
+ return AT;
+}
+
+const AT = { x: 0, y: 0 };
+
+function dominantOf(
+ ctx: MotionContext, blend: AnimatorBlend2DMotion,
+): AnimatorMotion | null {
+ const { x, y } = blend2DAt(ctx, blend);
+ return dominantBlendPoint(blend, x, y)?.motion ?? null;
+}
+
+/**
+ * The same operation the 1D blend performs, with the weights coming from a plane
+ * rather than a line — which is why this shares the pose mixer and the phase
+ * synchronisation rather than restating either.
+ */
+export const blend2DMotionDriver: MotionDriver<AnimatorBlend2DMotion> = {
+ apply(ctx, blend, enter) {
+ const dominant = dominantOf(ctx, blend);
+ if (dominant) ctx.drive(dominant, enter);
+ },
+ sample(ctx, blend, time, pose) {
+ const points = blend.points;
+ if (points.length === 0) return false;
+ if (points.length === 1) return ctx.sample(points[0]!.motion, time, pose);
+
+ const mix = ctx.borrowMix();
+ let sampled = 0;
+ try {
+ mixCapacity(mix, points.length);
+ const { x, y } = blend2DAt(ctx, blend);
+ blend2DWeights(blend, x, y, mix);
+
+ // The blend's own length is its points' lengths under those weights,
+ // and each point is then read at its own share of it — the 1D blend's
+ // phase rule, which stops the shorter clips racing.
+ let whole = 0;
+ for (let i = 0; i < points.length; i++) {
+ if (mix[i]!.weight <= 0) continue;
+ const span = ctx.duration(points[i]!.motion);
+ if (span <= 0) { whole = 0; break; }
+ whole += mix[i]!.weight * span;
+ }
+
+ // Compacting into the prefix is safe because the entry being written
+ // is never past the one being read.
+ for (let i = 0; i < points.length; i++) {
+ const weight = mix[i]!.weight;
+ if (weight <= 0) continue;
+ const motion = points[i]!.motion;
+ const at = whole > 0 ? time * (ctx.duration(motion) / whole) : time;
+ const scratch = ctx.borrowPose();
+ scratch.reset();
+ if (!ctx.sample(motion, at, scratch)) { ctx.releasePose(scratch); continue; }
+ mix[sampled]!.pose = scratch;
+ mix[sampled]!.weight = weight;
+ sampled++;
+ }
+
+ if (sampled === 0) return false;
+ if (sampled === 1) {
+ // Its weight is whatever the points that could not be sampled
+ // left it; as the only thing there is to show it arrives whole.
+ mix[0]!.weight = 1;
+ }
+ mixPoses(mix, pose, ctx.world, sampled);
+ return true;
+ } finally {
+ for (let i = 0; i < sampled; i++) ctx.releasePose(mix[i]!.pose);
+ ctx.releaseMix(mix);
+ }
+ },
+ duration(ctx, blend) {
+ const points = blend.points;
+ if (points.length === 0) return 0;
+ const mix = ctx.borrowMix();
+ try {
+ mixCapacity(mix, points.length);
+ const { x, y } = blend2DAt(ctx, blend);
+ blend2DWeights(blend, x, y, mix);
+ let whole = 0;
+ for (let i = 0; i < points.length; i++) {
+ if (mix[i]!.weight <= 0) continue;
+ const span = ctx.duration(points[i]!.motion);
+ // A point that does not state its length cannot be averaged with
+ // one that does, so the dominant point answers alone.
+ if (span <= 0) return ctx.duration(dominantOf(ctx, blend) ?? points[0]!.motion);
+ whole += mix[i]!.weight * span;
+ }
+ return whole;
+ } finally {
+ ctx.releaseMix(mix);
+ }
+ },
+ loops(ctx, blend) {
+ const dominant = dominantOf(ctx, blend);
+ return dominant ? ctx.loops(dominant) : false;
+ },
+ isFinished(ctx, blend) {
+ const dominant = dominantOf(ctx, blend);
+ return dominant ? ctx.finished(dominant) : false;
+ },
+ events(ctx, blend, span, out) {
+ const dominant = dominantOf(ctx, blend);
+ if (dominant) ctx.events(dominant, span, out);
+ },
+ rootMotion(ctx, blend, span, out) {
+ const dominant = dominantOf(ctx, blend);
+ return dominant !== null && ctx.rootDelta(dominant, span, out);
+ },
+};
diff --git a/sdk/src/animation/poseMix.ts b/sdk/src/animation/poseMix.ts
index 5a926265b..66c3ddda4 100644
--- a/sdk/src/animation/poseMix.ts
+++ b/sdk/src/animation/poseMix.ts
@@ -131,16 +131,19 @@ function mixScalarField(
/**
* Blend `sources` into `out`, then write it. Weights need not sum to one: each
- * field divides by the weight that actually reached it.
- *
- * `out` is seeded from the world like any pose, so a component some motion
- * touches only partly keeps its other fields.
+ * field divides by the weight that actually reached it. `out` is seeded from the
+ * world like any pose, so a component some motion touches only partly keeps its
+ * other fields; `count` reads a prefix, so a varying blend need not allocate.
*/
-export function mixPoses(sources: readonly WeightedPose[], out: Pose, world: PoseWorld): void {
+export function mixPoses(
+ sources: readonly WeightedPose[], out: Pose, world: PoseWorld,
+ count: number = sources.length,
+): void {
out.reset();
const byComponent = new Map<string, Contribution[]>();
- for (const { pose, weight } of sources) {
+ for (let i = 0; i < count; i++) {
+ const { pose, weight } = sources[i]!;
if (weight <= 0) continue;
for (const track of pose.tracks) {
if (track.touched.size === 0) continue;
diff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
index cbd309fba..ac4027903 100644
--- a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
@@ -13,7 +13,7 @@ import type {
} from '../AssetLoader';
import type { RegistryEra } from '../registryAssets';
import type { AnimatorControllerDef, AnimatorState } from '../../animation/Animator';
-import { isBlend1D, type AnimatorMotion } from '../../animation/motion';
+import { isBlend1D, isBlend2D, type AnimatorMotion } from '../../animation/motion';
import { resolveDocumentRef } from '../documentRef';
/**
@@ -37,6 +37,8 @@ function* flatten(motion: AnimatorMotion): Generator<AnimatorMotion> {
yield motion;
if (isBlend1D(motion)) {
for (const stop of motion.thresholds) yield* flatten(stop.motion);
+ } else if (isBlend2D(motion)) {
+ for (const point of motion.points) yield* flatten(point.motion);
}
}
@@ -68,7 +70,7 @@ async function acquireMotionAssets(
): Promise<void> {
const wanted = new Map<string, string>();
for (const motion of motionsOf(def.states)) {
- if (isBlend1D(motion)) continue;
+ if (isBlend1D(motion) || isBlend2D(motion)) continue;
const type = MOTION_ASSET_TYPES[motion.kind];
if (!type || !motion.clip) continue;
motion.clip = resolveDocumentRef(path, motion.clip);
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 100e1d430..027c5107a 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -422,14 +422,20 @@ export {
motionOf,
selectBlendStop,
blend1DPair,
+ blend2DWeights,
+ dominantBlendPoint,
MotionRegistry,
blend1DMotionDriver,
+ blend2DMotionDriver,
+ isBlend2D,
spriteMotionDriver,
SPRITE_MOTION,
SPINE_MOTION,
type AnimatorMotion,
type AnimatorClipMotion,
type AnimatorBlend1DMotion,
+ type AnimatorBlend2DMotion,
+ type AnimatorBlendPoint,
type AnimatorBlendStop,
type MotionContext,
type MotionDriver,
diff --git a/sdk/tests/animatorBlendTree.test.ts b/sdk/tests/animatorBlendTree.test.ts
index d960a238d..6d7d5ecfa 100644
--- a/sdk/tests/animatorBlendTree.test.ts
+++ b/sdk/tests/animatorBlendTree.test.ts
@@ -1,13 +1,16 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * The claim: a 1D blend over sampleable motions MIXES its neighbouring stops
- * rather than picking one, at a shared phase rather than a shared second.
+ * The claim: a blend over sampleable motions MIXES the stops around the
+ * parameter rather than picking one, at a shared phase rather than a shared
+ * second — over a line and over a plane, by the same operation.
*/
import { describe, it, expect } from 'vitest';
import {
Animator, AnimatorControllerAPI, blend1DPair, selectBlendStop,
- type AnimatorData, type AnimatorControllerDef, type AnimatorBlend1DMotion,
+ blend2DWeights, dominantBlendPoint,
+ type AnimatorData, type AnimatorControllerDef,
+ type AnimatorBlend1DMotion, type AnimatorBlend2DMotion, type AnimatorMotion,
} from '../src/animation';
import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';
import { TimelineAPI } from '../src/timeline/TimelineControl';
@@ -85,7 +88,7 @@ const clip = (name: string) => ({ kind: TIMELINE_MOTION, clip: name });
/** One state playing `motion`, driven by the float parameters named. */
function controllerOf(
- motion: AnimatorBlend1DMotion,
+ motion: AnimatorMotion,
assets: Record<string, TimelineAsset>,
params: string[],
): AnimatorControllerAPI {
@@ -271,3 +274,146 @@ describe('a blend nested inside a blend', () => {
expect(liftOf(world)).toBeCloseTo(125, 4);
});
});
+
+// ---------------------------------------------------------------------------
+// Over a plane
+// ---------------------------------------------------------------------------
+
+const at = (x: number, y: number, name: string) => ({ position: { x, y }, motion: clip(name) });
+
+/** Weights for `blend` at (x, y), as a plain array. */
+function weightsAt(blend: AnimatorBlend2DMotion, x: number, y: number): number[] {
+ const out = blend.points.map(() => ({ weight: 0 }));
+ blend2DWeights(blend, x, y, out);
+ return out.map(o => o.weight);
+}
+
+describe('how a 2D blend divides its plane', () => {
+ /** North/south/east/west around the origin — the shape a locomotion grid is. */
+ const compass: AnimatorBlend2DMotion = {
+ kind: 'blend2d', parameterX: 'right', parameterY: 'forward',
+ points: [at(1, 0, 'east'), at(0, 1, 'north'), at(-1, 0, 'west'), at(0, -1, 'south')],
+ };
+
+ it('gives a point standing on a clip that clip alone', () => {
+ expect(weightsAt(compass, 1, 0)).toEqual([1, 0, 0, 0]);
+ expect(weightsAt(compass, 0, -1)).toEqual([0, 0, 0, 1]);
+ });
+
+ it('shares a diagonal between the two clips that reach it', () => {
+ // What no pair of 1D blends can say: half east and half north is ONE
+ // motion, where two lines would pick a direction and a speed apart.
+ const [east, north, west, south] = weightsAt(compass, 0.5, 0.5);
+ expect(east).toBeCloseTo(0.5, 6);
+ expect(north).toBeCloseTo(0.5, 6);
+ expect(west).toBe(0);
+ expect(south).toBe(0);
+ });
+
+ it('always divides the whole of it, never more or less', () => {
+ for (const [x, y] of [[0, 0], [0.3, -0.2], [-0.9, 0.4], [2, 2], [-5, 0]] as const) {
+ const sum = weightsAt(compass, x, y).reduce((a, b) => a + b, 0);
+ expect(sum).toBeCloseTo(1, 6);
+ }
+ });
+
+ it('holds a sample outside the hull by the clip nearest it', () => {
+ const line: AnimatorBlend2DMotion = {
+ kind: 'blend2d', parameterX: 'x', parameterY: 'y',
+ points: [at(0, 0, 'idle'), at(2, 0, 'run')],
+ };
+ expect(weightsAt(line, 3, 0)).toEqual([0, 1]);
+ expect(weightsAt(line, -4, 0)).toEqual([1, 0]);
+ });
+
+ it('names the heaviest point as the one a switched motion gets', () => {
+ expect(dominantBlendPoint(compass, 0.9, 0.1)?.motion).toBe(compass.points[0]!.motion);
+ expect(dominantBlendPoint(compass, -0.1, -0.9)?.motion).toBe(compass.points[3]!.motion);
+ });
+});
+
+describe('a 2D blend through the animator', () => {
+ const held = {
+ 'east.estimeline': hold(100, 10), 'north.estimeline': hold(200, 10),
+ 'west.estimeline': hold(0, 10), 'south.estimeline': hold(300, 10),
+ };
+ const compass: AnimatorBlend2DMotion = {
+ kind: 'blend2d', parameterX: 'right', parameterY: 'forward',
+ points: [
+ at(1, 0, 'east.estimeline'), at(0, 1, 'north.estimeline'),
+ at(-1, 0, 'west.estimeline'), at(0, -1, 'south.estimeline'),
+ ],
+ };
+
+ it('mixes the two clips a diagonal reaches', () => {
+ const world = seedWorld();
+ const ctrl = controllerOf(compass, held, ['right', 'forward']);
+ attach(world);
+
+ ctrl.setFloat(E, 'right', 0.5);
+ ctrl.setFloat(E, 'forward', 0.5);
+ ctrl.update(world, 0.016);
+
+ // Half of east (100) and half of north (200). Either one alone — which is
+ // what selecting would give — is 100 or 200.
+ expect(liftOf(world)).toBeCloseTo(150, 4);
+ });
+
+ it('plays one clip whole where the parameters stand on it', () => {
+ const world = seedWorld();
+ const ctrl = controllerOf(compass, held, ['right', 'forward']);
+ attach(world);
+
+ ctrl.setFloat(E, 'forward', -1);
+ ctrl.update(world, 0.016);
+
+ expect(liftOf(world)).toBeCloseTo(300, 4);
+ });
+
+ it('samples every contributing point at the same phase', () => {
+ const world = seedWorld();
+ const ramps: AnimatorBlend2DMotion = {
+ kind: 'blend2d', parameterX: 'x', parameterY: 'y',
+ points: [at(0, 0, 'slow.estimeline'), at(2, 0, 'fast.estimeline')],
+ };
+ const ctrl = controllerOf(
+ ramps, { 'slow.estimeline': ramp(2), 'fast.estimeline': ramp(1) }, ['x', 'y'],
+ );
+ attach(world);
+ ctrl.setFloat(E, 'x', 1);
+ ctrl.update(world, 0);
+ ctrl.update(world, 0.75);
+
+ expect(liftOf(world)).toBeCloseTo(50, 3);
+ });
+
+ it('keeps its own weights while a nested blend resolves', () => {
+ // Each point of the plane is a line of its own. Both borrow the same kind
+ // of scratch, so an inner blend that got the outer one's list would mix
+ // the outer weights into its own answer.
+ const world = seedWorld();
+ const lean = (a: string, b: string): AnimatorBlend1DMotion => ({
+ kind: 'blend1d', parameter: 'lean',
+ thresholds: [{ value: 0, motion: clip(a) }, { value: 1, motion: clip(b) }],
+ });
+ const outer: AnimatorBlend2DMotion = {
+ kind: 'blend2d', parameterX: 'gait', parameterY: 'y',
+ points: [
+ { position: { x: 0, y: 0 }, motion: lean('a.estimeline', 'b.estimeline') },
+ { position: { x: 1, y: 0 }, motion: lean('c.estimeline', 'd.estimeline') },
+ ],
+ };
+ const ctrl = controllerOf(outer, {
+ 'a.estimeline': hold(0, 10), 'b.estimeline': hold(100, 10),
+ 'c.estimeline': hold(200, 10), 'd.estimeline': hold(300, 10),
+ }, ['gait', 'lean', 'y']);
+ attach(world);
+
+ ctrl.setFloat(E, 'gait', 0.25);
+ ctrl.setFloat(E, 'lean', 0.75);
+ ctrl.update(world, 0.016);
+
+ // Inner low is 75, inner high 275; three quarters of the way to the first.
+ expect(liftOf(world)).toBeCloseTo(125, 4);
+ });
+});