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): a character holds an object by anchors on it, the arms bent to them in one order that cannot loop
yhh1eff204fe250
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e38669fbb..f6a7dfdda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Holding an object in both hands.** A `GripProfile` on an object says where each palm sits on it, by anchor entities, and how its fingers are held; a `GripHolder` on a character takes hold of it, bends the supporting arm (and with the object placed by the game, the leading one) to the anchors and blends the fingers over the clip by `slerp(clip, grip, weight)`. It runs in one fixed order that cannot loop, eases every joint when what is held changes, puts the palm on the anchor for any arm length within reach, and gives the same bones for the same inputs. `captureFingerPose` keeps a hand's fingers as JSON.- **A tiled terrain exports and imports its heightmap, over every tile or only the loaded ones.** The terrain sculpt panel exports the heights as one image the size of the whole area, and imports one (16-bit grey, or the red and green the export writes) over the tiles, as do the **Terrain: Export Heightmap** and **Terrain: Import Selected Heightmap** commands. **Loaded tiles** reads no tile that is not in memory: an export takes the rest from the overview, and an import writes only the tiles in memory and the overview; **All tiles** reads and writes every one. An import is refused while the terrain has changes not saved.- **Tiled terrain can be sculpted and painted, and a save writes only what changed.** A brush on tiled ground runs on the samples copied out of the tiles under it and writes them back to every tile that holds them, so a seam stays one height and the result is the same as on one heightfield, sample for sample. Only tiles in memory are edited: a dab over one not read yet is skipped and the tile is read. A changed tile is kept in memory past the budget until it is saved, the overview follows each stroke so distant ground shows it, and undo covers the tiles and the overview. **Save Ground** writes the changed tiles and the overview only: six dabs on a 4097 by 4097 terrain wrote 2 of its 64 tiles.- **A terrain can be kept as tiles that are read where they are looked at.** A Terrain's `tiles` names a `.esterrain`: the ground cut into tiles of 513 samples a side and a low-detail overview. Distant ground is drawn from the overview, which is always in memory; full-detail tiles are read near where the view or a moving body is, and the least recently used are let go past 256 MiB. Measured in the editor on a 4096-unit area: an 8193 by 8193 field held as one image is 256 MiB, as tiles it opened holding 36 MiB and 45 MiB close to the ground. **Split into Tiles** in the terrain sculpt panel converts a terrain. The tile images are referenced only by the `.esterrain`, so they are no longer preloaded and uploaded as textures the way a `heightmap` is. The editor now also waits for ground still being built before it counts itself idle.diff --git a/desktop b/desktopindex b1b1632b5..ad3d34c9f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit b1b1632b5c4664352aa485a4b95c9db30c28acd2+Subproject commit ad3d34c9f3735a8593d411226f4e52a1b9cab28ediff --git a/docs/astro/src/content/docs/animation/grip-pose.mdx b/docs/astro/src/content/docs/animation/grip-pose.mdxindex 7266d405b..7b0a81334 100644--- a/docs/astro/src/content/docs/animation/grip-pose.mdx+++ b/docs/astro/src/content/docs/animation/grip-pose.mdx@@ -75,6 +75,51 @@ The hand is found by name: a joint called something like `RightHand` or `hand_r`A rig with fewer fingers does without the rest, and says which in the log. `gripPoseStatus(app, entity)` answers what was found on each hand.+## Holding an object++Three parts, each answering one question:++| Part | Answers |+|---|---|+| `GripProfile`, on the object | Where on it each palm sits: an anchor entity for the leading hand and one for the supporting hand, and the fingers' pose for each. |+| The arm | How the shoulder, elbow and wrist get the palm there: two-bone IK, the elbow keeping the side the clip bends it to, the wrist turned to the anchor. |+| The fingers | How each finger is held: a pose captured from a hand, blended over the clip as `slerp(clip, grip, weight)`, or a grip pose by name. |++An anchor is any entity under the object, placed with the ordinary move and rotate gizmos. Its origin is the palm's centre (halfway from the hand joint to the middle knuckle), its +Z the way the fingers point, and its +Y the way the palm faces.++```ts+import { GripHolder, GripPlacement, GripProfile } from 'esengine';++world.insert(rifle, GripProfile, { mainAnchor: gripAnchor, supportAnchor: foregripAnchor, mainPose: 'pistol', supportPose: 'support' });+world.insert(hero, GripHolder, { held: rifle, placement: GripPlacement.Object });+```++| `GripHolder` field | What it does |+|---|---|+| `held` | The object held: an entity with a `GripProfile`. None lets go. |+| `mainHand` | `Right` or `Left`: the hand that leads. |+| `placement` | `Hand`: the object rides the leading hand wherever the clip puts it. `Object`: the game places the object (aiming) and the leading arm is brought to it. |+| `weight`, `supportWeight` | How much of the hold applies over the clip, and of the supporting hand's under that. |+| `blendSeconds` | How long taking hold, letting go and changing what is held take. Every joint eases from where it was, from still and to rest, so no hand jumps. |+| `rightHand`, `leftHand` | The hand joints by path, where their names do not find them. |++It runs after the animator, in one order every frame, so nothing can drive itself round a loop: the clip's pose; then the object, on the leading hand or where the game put it; then the supporting anchor, read off the object as it now stands; then that arm; then the fingers of both. The object never reads the supporting hand. Each frame solves from the clip's pose, never from its own last answer, and nothing reads a clock but the game's: the same inputs and steps give the same bones, bit for bit.++### Finger poses++`captureFingerPose(world, handJoint)` takes the turn of every named joint under a hand as it stands, as plain JSON; `registerFingerPose(name, pose)` keeps it for a `GripProfile` to name. Pose the hand with a `GripPose`, a clip or by hand, capture it, and save the JSON with the game. A captured pose names its rig's bones, so it belongs to that rig; a grip pose by name fits any.++### On another body++Anchors are where a palm goes, not where a hand joint goes, and the arm is solved each frame from the body it is on, so a body with longer or shorter arms still puts its palm on the anchor. Past its reach, the arm points straight at the anchor and the wrist still turns to it: the palm stops short, the same way every time.++### Limits of holding++- **The fingers do not fit the object.** A pose is set, not found on the surface: they can sink into a thick grip or stop short of a thin one. Fitting them to it is not built.+- **No editor for anchors or poses yet.** Anchors are moved with the ordinary gizmos; a finger pose is captured from code.+- **Only the supporting arm is bent with `Hand` placement,** and only the leading one is first with `Object`; a shoulder or the spine does not lean to help an arm reach.+- **One object a holder.**+## Limits- **It does not touch what is held.** A pose is a shape, not a fit: fingers can sink into a wide grip or stop short of a narrow one. Use `curl` for the object, or a pose of its own.diff --git a/docs/astro/src/content/docs/zh-cn/animation/grip-pose.mdx b/docs/astro/src/content/docs/zh-cn/animation/grip-pose.mdxindex 786ab2568..627fe1370 100644--- a/docs/astro/src/content/docs/zh-cn/animation/grip-pose.mdx+++ b/docs/astro/src/content/docs/zh-cn/animation/grip-pose.mdx@@ -75,6 +75,51 @@ registerGripPose('claw', {手指较少的骨架会跳过缺失的手指,并在日志里说明。`gripPoseStatus(app, entity)` 可以查询每只手找到了什么。+## 握持物体++分成三个部分,各回答一个问题:++| 部分 | 负责 |+|---|---|+| `GripProfile`(在物体上) | 每只手的掌心放在物体的什么位置:主手、副手各一个锚点实体,以及各自的手指姿势。 |+| 手臂 | 肩、肘、腕怎样把掌心送到那里:two-bone IK,手肘保持动画原本弯向的一侧,手腕转到锚点的朝向。 |+| 手指 | 每根手指怎么握:截取下来的手指姿势按 `slerp(clip, grip, weight)` 叠加在动画上,或者用一个 GripPose 名字。 |++锚点就是物体下的普通子实体,用现有的移动、旋转 gizmo 摆放。它的原点是掌心中心(手部关节到中指根的中点),+Z 是手指指向,+Y 是掌心朝向。++```ts+import { GripHolder, GripPlacement, GripProfile } from 'esengine';++world.insert(rifle, GripProfile, { mainAnchor: gripAnchor, supportAnchor: foregripAnchor, mainPose: 'pistol', supportPose: 'support' });+world.insert(hero, GripHolder, { held: rifle, placement: GripPlacement.Object });+```++| `GripHolder` 字段 | 作用 |+|---|---|+| `held` | 握着的物体:一个带 `GripProfile` 的实体。为空时松手。 |+| `mainHand` | `Right` 或 `Left`:主手。 |+| `placement` | `Hand`:物体跟着动画里的主手走。`Object`:物体由游戏放置(比如瞄准),主手手臂被带到物体上。 |+| `weight`、`supportWeight` | 握持在动画之上应用多少,以及副手在此之下应用多少。 |+| `blendSeconds` | 握住、松开、换物体分别花多久。每个关节都从原来的位置平滑过渡,起步和停止都平稳,手不会跳。 |+| `rightHand`、`leftHand` | 名字找不到手时,手部关节的路径。 |++它在动画系统之后运行,每帧按固定顺序单向计算,所以不会形成循环:动画姿态;然后物体(跟着主手,或者在游戏放的位置);然后从物体当前位置读出副手锚点;然后副手手臂;最后两只手的手指。物体从不读取副手。每帧都从动画姿态开始求解,从不在自己上一帧的结果上继续;除了游戏时钟不读任何时钟。所以同样的输入和步进得到逐位相同的骨骼。++### 手指姿势++`captureFingerPose(world, handJoint)` 把手下面每个有名字的关节当前的旋转截取成普通 JSON;`registerFingerPose(name, pose)` 保存它,供 `GripProfile` 引用。用 GripPose、动画片段或手动摆好手型后截取下来,把 JSON 和游戏一起保存。截取的姿势用的是骨骼名字,所以属于那套骨架;GripPose 名字则适用于任何骨架。++### 换一个体型++锚点表示掌心的位置,不是手部关节的位置,手臂每帧按所在的身体求解,所以手臂更长或更短的身体仍然能把掌心放到锚点上。够不着时,手臂伸直指向锚点,手腕仍然转到锚点朝向:掌心停在锚点前方,每次结果都一样。++### 握持的限制++- **手指不贴合物体。** 姿势是设定好的,不是在表面上找到的:握把太粗时手指会陷进去,太细时碰不到。贴合还没有做。+- **还没有锚点和姿势的编辑器。** 锚点用普通 gizmo 移动,手指姿势要用代码截取。+- **`Hand` 模式只弯副手手臂,`Object` 模式先弯主手;** 肩膀和脊柱不会为了够到而倾斜。+- **一个持有者只能握一个物体。**+## 限制- **不接触被握的物体。** 姿势只是手型,不做贴合:握把太粗时手指可能陷进去,太细时可能碰不到。可以调 `curl`,或者给这个物体单独做一个姿势。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex b7ee47ec4..be8d97da3 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 178,- "experimental": 2992,+ "experimental": 3005,"deprecated": 3},- "total": 3285,+ "total": 3298,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex b519b38ed..0b947262a 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -207,6 +207,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {// ── Animation ──────────────────────────────────────────────────────────────Animator: { category: 'animation', summary: 'Runs an animator controller — states, transitions and blend trees — over the entity.', doc: 'animation/overview', anchor: 'animator-state-machine', anchorZh: '动画状态机' },AnimatorRootMotion: { category: 'animation', summary: 'Publishes how far the active animation asks the character to move, for gameplay to hand to a character controller — a request, never a result.', doc: 'animation/overview', anchor: 'root-motion', anchorZh: '根运动' },+ GripProfile: { category: 'animation', summary: 'Where on an object each palm sits, and how its fingers are held there.', doc: 'animation/grip-pose', anchor: 'holding-an-object' },+ GripHolder: { category: 'animation', summary: 'Holds an object in its GripProfile\'s grip: the arms bent to its anchors, the fingers posed, in one order that cannot loop.', doc: 'animation/grip-pose', anchor: 'holding-an-object' },GripPose: { category: 'animation', summary: 'Holds a rig\'s hands in a named pose, a pistol grip, a handle, a cup, that fits any rig with fingers.', doc: 'animation/grip-pose' },SpringBone: { category: 'animation', summary: 'Makes every bone below this root a spring: the chain trails the animated pose by inertia, falls with gravity and is pulled back toward it (hair, tails, cords).', doc: 'animation/spring-bones', anchor: 'the-component', anchorZh: '组件' },SpringBoneCollider: { category: 'animation', summary: 'A sphere or capsule that the spring-bone chains naming it are kept out of.', doc: 'animation/spring-bones', anchor: 'the-component', anchorZh: '组件' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 7b95e87de..233707188 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -2740,6 +2740,81 @@"rippleTexture"]},+ {+ "name": "GripHolder",+ "source": "ts",+ "fields": [+ {+ "key": "held",+ "type": "Entity",+ "default": "none",+ "doc": "What is held: an entity with a GripProfile."+ },+ {+ "key": "mainHand",+ "type": "enum",+ "default": "Right",+ "doc": "The hand that leads.",+ "values": [+ "Right",+ "Left"+ ]+ },+ {+ "key": "placement",+ "type": "enum",+ "default": "Hand",+ "doc": "Hand: the object rides the leading hand as the clip moves it. Object: the game places it (aiming) and the leading arm is brought to it.",+ "values": [+ "Hand",+ "Object"+ ]+ },+ {+ "key": "weight",+ "type": "number",+ "default": "1",+ "doc": "How much of the hold applies over the clip.",+ "range": "0–1, step 0.01"+ },+ {+ "key": "supportWeight",+ "type": "number",+ "default": "1",+ "doc": "How much of the supporting hand's hold applies, under the weight.",+ "range": "0–1, step 0.01"+ },+ {+ "key": "blendSeconds",+ "type": "number",+ "default": "0.2",+ "doc": "About how long taking hold, letting go, or changing what is held takes.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "rightHand",+ "type": "string",+ "default": "empty",+ "doc": "The right hand joint, by path from this entity. Empty finds it by name.",+ "advanced": true+ },+ {+ "key": "leftHand",+ "type": "string",+ "default": "empty",+ "doc": "The left hand joint, by path from this entity. Empty finds it by name.",+ "advanced": true+ }+ ],+ "animatable": [+ "held",+ "mainHand",+ "placement",+ "weight",+ "supportWeight",+ "blendSeconds"+ ]+ },{"name": "GripPose","source": "ts",@@ -2814,6 +2889,40 @@"blendSeconds"]},+ {+ "name": "GripProfile",+ "source": "ts",+ "fields": [+ {+ "key": "mainAnchor",+ "type": "Entity",+ "default": "none",+ "doc": "Where the leading palm sits: an entity under this one. Its +Z is the way the fingers point, +Y the way the palm faces."+ },+ {+ "key": "supportAnchor",+ "type": "Entity",+ "default": "none",+ "doc": "Where the supporting palm sits. Empty holds this in one hand."+ },+ {+ "key": "mainPose",+ "type": "string",+ "default": "\"handle\"",+ "doc": "The leading hand's fingers: a captured finger pose, or a grip pose (pistol, handle, support, ...)."+ },+ {+ "key": "supportPose",+ "type": "string",+ "default": "\"support\"",+ "doc": "The supporting hand's fingers."+ }+ ],+ "animatable": [+ "mainAnchor",+ "supportAnchor"+ ]+ },{"name": "GroupOpacity","source": "cpp",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 09b9068c5..358311a5b 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: 115 public · 166 beta · 2118 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2130 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4437,6 +4437,11 @@ type: "filter"{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }```+## FingerPoseDef — interface @experimental+```+joints: Record<string, Quat>+```+## FixedJoint2D — const @experimental```ComponentDef<FixedJoint2DData>@@ -5036,6 +5041,11 @@ curl: numberspread: number | undefined```+## GripHand — const @experimental+```+{ readonly Right: 0; readonly Left: 1; }+```+## GripHandStatus — interface @experimental```hand: number | null@@ -5045,6 +5055,28 @@ pose: stringweight: number```+## GripHolder — const @experimental+```+ComponentDef<GripHolderData>+```++## GripHolderData — interface @experimental+```+blendSeconds: number+held: number+leftHand: string+mainHand: number+placement: number+rightHand: string+supportWeight: number+weight: number+```++## GripPlacement — const @experimental+```+{ readonly Hand: 0; readonly Object: 1; }+```+## GripPose — const @experimental```ComponentDef<GripPoseData>@@ -5073,6 +5105,19 @@ thumb: GripThumbtrigger: GripFinger | undefined```+## GripProfile — const @experimental+```+ComponentDef<GripProfileData>+```++## GripProfileData — interface @experimental+```+mainAnchor: number+mainPose: string+supportAnchor: number+supportPose: string+```+## GripThumb — interface @experimental```gap: number | undefined@@ -14648,6 +14693,11 @@ MotionDriver<AnimatorBlend2DMotion><T>(entities: readonly T[], parentOf: (entity: T) => T | null): T[]```+## captureFingerPose — function @experimental+```+(world: World, hand: Entity): FingerPoseDef+```+## captureFrame — function @experimental```(module: CaptureEngine, nextFrame: NextFrame, maxFrames?: number): Promise<FrameCaptureData | null>@@ -15583,6 +15633,11 @@ EventBindingPlugin(world: World, name: string): Entity | null```+## fingerPose — function @experimental+```+(name: string): FingerPoseDef | undefined+```+## fingerprint — function @experimental```(report: DiagnosticReport): string@@ -15868,6 +15923,11 @@ Plugin(preserveDrawingBuffer?: boolean): WebGLContextAttributes```+## gripHolderStatus — function @experimental+```+(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity; } | null+```+## gripPose — function @experimental```(name: string): GripPoseDef | undefined@@ -17013,6 +17073,11 @@ PrefabsPlugin(def: EffectDef): void```+## registerFingerPose — function @experimental+```+(name: string, pose: FingerPoseDef): void+```+## registerGripPose — function @experimental```(name: string, pose: GripPoseDef): void@@ -17703,6 +17768,11 @@ ServicesPlugin(spec: SkySpec): SkyRadiance```+## slerpQuat — function @experimental+```+(a: Quat, b: Quat, t: number): Quat+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver, ground?: GroundContext): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex cf0e1a1dc..b7a04d3fe 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: 115 public · 171 beta · 2137 experimental · 3 deprecated+Symbols: 115 public · 171 beta · 2150 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4445,6 +4445,11 @@ type: "filter"{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }```+## FingerPoseDef — interface @experimental+```+joints: Record<string, Quat>+```+## FixedJoint2D — const @experimental```ComponentDef<FixedJoint2DData>@@ -5044,6 +5049,11 @@ curl: numberspread: number | undefined```+## GripHand — const @experimental+```+{ readonly Right: 0; readonly Left: 1; }+```+## GripHandStatus — interface @experimental```hand: number | null@@ -5053,6 +5063,28 @@ pose: stringweight: number```+## GripHolder — const @experimental+```+ComponentDef<GripHolderData>+```++## GripHolderData — interface @experimental+```+blendSeconds: number+held: number+leftHand: string+mainHand: number+placement: number+rightHand: string+supportWeight: number+weight: number+```++## GripPlacement — const @experimental+```+{ readonly Hand: 0; readonly Object: 1; }+```+## GripPose — const @experimental```ComponentDef<GripPoseData>@@ -5081,6 +5113,19 @@ thumb: GripThumbtrigger: GripFinger | undefined```+## GripProfile — const @experimental+```+ComponentDef<GripProfileData>+```++## GripProfileData — interface @experimental+```+mainAnchor: number+mainPose: string+supportAnchor: number+supportPose: string+```+## GripThumb — interface @experimental```gap: number | undefined@@ -14884,6 +14929,11 @@ MotionDriver<AnimatorBlend2DMotion><T>(entities: readonly T[], parentOf: (entity: T) => T | null): T[]```+## captureFingerPose — function @experimental+```+(world: World, hand: Entity): FingerPoseDef+```+## captureFrame — function @experimental```(module: CaptureEngine, nextFrame: NextFrame, maxFrames?: number): Promise<FrameCaptureData | null>@@ -15844,6 +15894,11 @@ EventBindingPlugin(world: World, name: string): Entity | null```+## fingerPose — function @experimental+```+(name: string): FingerPoseDef | undefined+```+## fingerprint — function @experimental```(report: DiagnosticReport): string@@ -16129,6 +16184,11 @@ Plugin(preserveDrawingBuffer?: boolean): WebGLContextAttributes```+## gripHolderStatus — function @experimental+```+(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity; } | null+```+## gripPose — function @experimental```(name: string): GripPoseDef | undefined@@ -17284,6 +17344,11 @@ PrefabsPlugin(def: EffectDef): void```+## registerFingerPose — function @experimental+```+(name: string, pose: FingerPoseDef): void+```+## registerGripPose — function @experimental```(name: string, pose: GripPoseDef): void@@ -17974,6 +18039,11 @@ ServicesPlugin(spec: SkySpec): SkyRadiance```+## slerpQuat — function @experimental+```+(a: Quat, b: Quat, t: number): Quat+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver, ground?: GroundContext): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 1d699662f..e7f125f39 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: 115 public · 168 beta · 2117 experimental · 3 deprecated+Symbols: 115 public · 168 beta · 2129 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4432,6 +4432,11 @@ type: "filter"{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }```+## FingerPoseDef — interface @experimental+```+joints: Record<string, Quat>+```+## FixedJoint2D — const @experimental```ComponentDef<FixedJoint2DData>@@ -5031,6 +5036,11 @@ curl: numberspread: number | undefined```+## GripHand — const @experimental+```+{ readonly Right: 0; readonly Left: 1; }+```+## GripHandStatus — interface @experimental```hand: number | null@@ -5040,6 +5050,28 @@ pose: stringweight: number```+## GripHolder — const @experimental+```+ComponentDef<GripHolderData>+```++## GripHolderData — interface @experimental+```+blendSeconds: number+held: number+leftHand: string+mainHand: number+placement: number+rightHand: string+supportWeight: number+weight: number+```++## GripPlacement — const @experimental+```+{ readonly Hand: 0; readonly Object: 1; }+```+## GripPose — const @experimental```ComponentDef<GripPoseData>@@ -5068,6 +5100,19 @@ thumb: GripThumbtrigger: GripFinger | undefined```+## GripProfile — const @experimental+```+ComponentDef<GripProfileData>+```++## GripProfileData — interface @experimental+```+mainAnchor: number+mainPose: string+supportAnchor: number+supportPose: string+```+## GripThumb — interface @experimental```gap: number | undefined@@ -14643,6 +14688,11 @@ MotionDriver<AnimatorBlend2DMotion><T>(entities: readonly T[], parentOf: (entity: T) => T | null): T[]```+## captureFingerPose — function @experimental+```+(world: World, hand: Entity): FingerPoseDef+```+## captureFrame — function @experimental```(module: CaptureEngine, nextFrame: NextFrame, maxFrames?: number): Promise<FrameCaptureData | null>@@ -15578,6 +15628,11 @@ EventBindingPlugin(world: World, name: string): Entity | null```+## fingerPose — function @experimental+```+(name: string): FingerPoseDef | undefined+```+## fingerprint — function @experimental```(report: DiagnosticReport): string@@ -15863,6 +15918,11 @@ Plugin(preserveDrawingBuffer?: boolean): WebGLContextAttributes```+## gripHolderStatus — function @experimental+```+(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity; } | null+```+## gripPose — function @experimental```(name: string): GripPoseDef | undefined@@ -17018,6 +17078,11 @@ PrefabsPlugin(def: EffectDef): void```+## registerFingerPose — function @experimental+```+(name: string, pose: FingerPoseDef): void+```+## registerGripPose — function @experimental```(name: string, pose: GripPoseDef): void@@ -17708,6 +17773,11 @@ ServicesPlugin(spec: SkySpec): SkyRadiance```+## slerpQuat — function @experimental+```+(a: Quat, b: Quat, t: number): Quat+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver, ground?: GroundContext): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 33ac9e1ab..16887b716 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: 115 public · 166 beta · 2139 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2151 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4432,6 +4432,11 @@ type: "filter"{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }```+## FingerPoseDef — interface @experimental+```+joints: Record<string, Quat>+```+## FixedJoint2D — const @experimental```ComponentDef<FixedJoint2DData>@@ -5031,6 +5036,11 @@ curl: numberspread: number | undefined```+## GripHand — const @experimental+```+{ readonly Right: 0; readonly Left: 1; }+```+## GripHandStatus — interface @experimental```hand: number | null@@ -5040,6 +5050,28 @@ pose: stringweight: number```+## GripHolder — const @experimental+```+ComponentDef<GripHolderData>+```++## GripHolderData — interface @experimental+```+blendSeconds: number+held: number+leftHand: string+mainHand: number+placement: number+rightHand: string+supportWeight: number+weight: number+```++## GripPlacement — const @experimental+```+{ readonly Hand: 0; readonly Object: 1; }+```+## GripPose — const @experimental```ComponentDef<GripPoseData>@@ -5068,6 +5100,19 @@ thumb: GripThumbtrigger: GripFinger | undefined```+## GripProfile — const @experimental+```+ComponentDef<GripProfileData>+```++## GripProfileData — interface @experimental+```+mainAnchor: number+mainPose: string+supportAnchor: number+supportPose: string+```+## GripThumb — interface @experimental```gap: number | undefined@@ -14945,6 +14990,11 @@ MotionDriver<AnimatorBlend2DMotion><T>(entities: readonly T[], parentOf: (entity: T) => T | null): T[]```+## captureFingerPose — function @experimental+```+(world: World, hand: Entity): FingerPoseDef+```+## captureFrame — function @experimental```(module: CaptureEngine, nextFrame: NextFrame, maxFrames?: number): Promise<FrameCaptureData | null>@@ -15885,6 +15935,11 @@ EventBindingPlugin(world: World, name: string): Entity | null```+## fingerPose — function @experimental+```+(name: string): FingerPoseDef | undefined+```+## fingerprint — function @experimental```(report: DiagnosticReport): string@@ -16170,6 +16225,11 @@ Plugin(preserveDrawingBuffer?: boolean): WebGLContextAttributes```+## gripHolderStatus — function @experimental+```+(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity; } | null+```+## gripPose — function @experimental```(name: string): GripPoseDef | undefined@@ -17325,6 +17385,11 @@ PrefabsPlugin(def: EffectDef): void```+## registerFingerPose — function @experimental+```+(name: string, pose: FingerPoseDef): void+```+## registerGripPose — function @experimental```(name: string, pose: GripPoseDef): void@@ -18015,6 +18080,11 @@ ServicesPlugin(spec: SkySpec): SkyRadiance```+## slerpQuat — function @experimental+```+(a: Quat, b: Quat, t: number): Quat+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver, ground?: GroundContext): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 9f161c22f..221d030bb 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: 115 public · 166 beta · 2130 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2142 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4432,6 +4432,11 @@ type: "filter"{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }```+## FingerPoseDef — interface @experimental+```+joints: Record<string, Quat>+```+## FixedJoint2D — const @experimental```ComponentDef<FixedJoint2DData>@@ -5031,6 +5036,11 @@ curl: numberspread: number | undefined```+## GripHand — const @experimental+```+{ readonly Right: 0; readonly Left: 1; }+```+## GripHandStatus — interface @experimental```hand: number | null@@ -5040,6 +5050,28 @@ pose: stringweight: number```+## GripHolder — const @experimental+```+ComponentDef<GripHolderData>+```++## GripHolderData — interface @experimental+```+blendSeconds: number+held: number+leftHand: string+mainHand: number+placement: number+rightHand: string+supportWeight: number+weight: number+```++## GripPlacement — const @experimental+```+{ readonly Hand: 0; readonly Object: 1; }+```+## GripPose — const @experimental```ComponentDef<GripPoseData>@@ -5068,6 +5100,19 @@ thumb: GripThumbtrigger: GripFinger | undefined```+## GripProfile — const @experimental+```+ComponentDef<GripProfileData>+```++## GripProfileData — interface @experimental+```+mainAnchor: number+mainPose: string+supportAnchor: number+supportPose: string+```+## GripThumb — interface @experimental```gap: number | undefined@@ -14676,6 +14721,11 @@ MotionDriver<AnimatorBlend2DMotion><T>(entities: readonly T[], parentOf: (entity: T) => T | null): T[]```+## captureFingerPose — function @experimental+```+(world: World, hand: Entity): FingerPoseDef+```+## captureFrame — function @experimental```(module: CaptureEngine, nextFrame: NextFrame, maxFrames?: number): Promise<FrameCaptureData | null>@@ -15611,6 +15661,11 @@ EventBindingPlugin(world: World, name: string): Entity | null```+## fingerPose — function @experimental+```+(name: string): FingerPoseDef | undefined+```+## fingerprint — function @experimental```(report: DiagnosticReport): string@@ -15896,6 +15951,11 @@ Plugin(preserveDrawingBuffer?: boolean): WebGLContextAttributes```+## gripHolderStatus — function @experimental+```+(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity; } | null+```+## gripPose — function @experimental```(name: string): GripPoseDef | undefined@@ -17051,6 +17111,11 @@ PrefabsPlugin(def: EffectDef): void```+## registerFingerPose — function @experimental+```+(name: string, pose: FingerPoseDef): void+```+## registerGripPose — function @experimental```(name: string, pose: GripPoseDef): void@@ -17741,6 +17806,11 @@ ServicesPlugin(spec: SkySpec): SkyRadiance```+## slerpQuat — function @experimental+```+(a: Quat, b: Quat, t: number): Quat+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver, ground?: GroundContext): voiddiff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.tsindex b47468f3e..4d0d0b805 100644--- a/sdk/src/animation/AnimationPlugin.ts+++ b/sdk/src/animation/AnimationPlugin.ts@@ -30,6 +30,7 @@ import { installSwayPush } from '../render/swayPush';import { installFootsteps } from '../render/footsteps';import { SystemLabel } from '../ecs/systemLabels';import { installGripPose } from './gripPose';+import { installGripHold } from './gripHold';export class AnimationPlugin implements Plugin {name = 'animation';@@ -109,6 +110,8 @@ export class AnimationPlugin implements Plugin {{ name: 'SpriteAnimatorSystem' }), { runAfter: [SystemLabel.Tween, SystemLabel.Animator], runIf: playModeOnly });+ // The hold first: it hands the fingers it does not pose itself to the grip pose after it.+ installGripHold(app);installGripPose(app);}diff --git a/sdk/src/animation/gripHold.ts b/sdk/src/animation/gripHold.tsnew file mode 100644index 000000000..d7343cb32--- /dev/null+++ b/sdk/src/animation/gripHold.ts@@ -0,0 +1,433 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file gripHold.ts+ * @brief A character holding an object: where the palms go on it, the arms that take them there, and the fingers once there.+ *+ * @details Three parts, each answering one thing. The object's `GripProfile` says where on it a palm sits, for the hand that leads and the one+ * that supports. The arm is bent to take the palm there. The fingers are a pose blended over what the clip does.+ *+ * The order is fixed and runs one way, so no hand can move what moves it: the clip's pose, then where the object is (on the leading hand,+ * or where the game put it), then the supporting hand's anchor read off the object, then that arm, then the fingers of both. The+ * object never reads the supporting hand. Everything comes from this frame's pose and the game's clock: the same inputs and steps give+ * the same bones.+ */+import type { App } from '../app/app';+import { defineComponent, Children, Name, Parent, Transform, type ComponentDef, type TransformData } from '../ecs/component';+import { defineSystem, GetWorld, Schedule } from '../ecs/system';+import { Res, Time, type TimeData } from '../ecs/resource';+import type { World } from '../ecs/world';+import { resolveChildEntity } from '../ecs/childPath';+import { playModeOnly } from '../ecs/env';+import { SystemLabel } from '../ecs/systemLabels';+import { log } from '../util/logger';+import { q } from '../math/quat';+import type { Entity } from '../types';+import { findHand, gripPose, GripPose, palmFrameOf, type GripPoseData } from './gripPose';++interface Vec3 { x: number; y: number; z: number }+interface Quat { w: number; x: number; y: number; z: number }++/** Where a palm sits on a held object, and how its fingers are held there. @experimental */+export interface GripProfileData {+ /** An entity under the object whose place and turn are the leading palm's: its origin the palm's centre, +Z the way the fingers point, +Y the way the palm faces. */+ mainAnchor: Entity;+ /** The same for the supporting hand. None holds the object in one hand. */+ supportAnchor: Entity;+ /** The fingers of each: a pose captured from a hand (registerFingerPose), or a GripPose by name. */+ mainPose: string;+ supportPose: string;+}++/**+ * How an object is held. Goes on the object; its anchors are entities under it.+ *+ * @experimental+ */+export const GripProfile: ComponentDef<GripProfileData> = /* @__PURE__ */ defineComponent<GripProfileData>('GripProfile', {+ mainAnchor: 0 as Entity, supportAnchor: 0 as Entity, mainPose: 'handle', supportPose: 'support',+}, {+ entityFields: ['mainAnchor', 'supportAnchor'],+ fields: {+ mainAnchor: { tooltip: 'Where the leading palm sits: an entity under this one. Its +Z is the way the fingers point, +Y the way the palm faces.' },+ supportAnchor: { tooltip: 'Where the supporting palm sits. Empty holds this in one hand.' },+ mainPose: { tooltip: 'The leading hand\'s fingers: a captured finger pose, or a grip pose (pistol, handle, support, ...).' },+ supportPose: { tooltip: 'The supporting hand\'s fingers.' },+ },+});++/** Which hand leads. @experimental */+export const GripHand = { Right: 0, Left: 1 } as const;+/** What places the held object: the leading hand as the clip moves it, or the game (aiming), with the leading arm brought to it. @experimental */+export const GripPlacement = { Hand: 0, Object: 1 } as const;++/** The fields of the `GripHolder` component. @experimental */+export interface GripHolderData {+ /** What it holds: an entity with a GripProfile. None holds nothing. */+ held: Entity;+ mainHand: number;+ placement: number;+ /** How much of the hold applies over the clip, 0 to 1; and of the supporting hand's, under that. */+ weight: number;+ supportWeight: number;+ /** About how long taking hold, letting go, or changing what is held takes, in seconds. */+ blendSeconds: number;+ /** The hand joints, by path from this entity. Empty finds them by name. */+ rightHand: string;+ leftHand: string;+}++/**+ * Holds an object in its GripProfile's grip. Goes on the rig's root.+ *+ * @experimental+ */+export const GripHolder: ComponentDef<GripHolderData> = /* @__PURE__ */ defineComponent<GripHolderData>('GripHolder', {+ held: 0 as Entity, mainHand: GripHand.Right, placement: GripPlacement.Hand, weight: 1, supportWeight: 1, blendSeconds: 0.2, rightHand: '', leftHand: '',+}, {+ entityFields: ['held'],+ fields: {+ held: { tooltip: 'What is held: an entity with a GripProfile.' },+ mainHand: { enum: [{ label: 'Right', value: GripHand.Right }, { label: 'Left', value: GripHand.Left }], tooltip: 'The hand that leads.' },+ placement: { enum: [{ label: 'Hand', value: GripPlacement.Hand }, { label: 'Object', value: GripPlacement.Object }], tooltip: 'Hand: the object rides the leading hand as the clip moves it. Object: the game places it (aiming) and the leading arm is brought to it.' },+ weight: { min: 0, max: 1, step: 0.01, tooltip: 'How much of the hold applies over the clip.' },+ supportWeight: { min: 0, max: 1, step: 0.01, tooltip: 'How much of the supporting hand\'s hold applies, under the weight.' },+ blendSeconds: { min: 0, step: 0.01, unit: 's', tooltip: 'About how long taking hold, letting go, or changing what is held takes.' },+ rightHand: { advanced: true, tooltip: 'The right hand joint, by path from this entity. Empty finds it by name.' },+ leftHand: { advanced: true, tooltip: 'The left hand joint, by path from this entity. Empty finds it by name.' },+ },+});++/** A pose of the fingers as one rig holds them: each joint's own turn, by its name. @experimental */+export interface FingerPoseDef {+ joints: Record<string, Quat>;+}++const fingerPoses = new Map<string, FingerPoseDef>();++/** Keeps a finger pose by name, for a GripProfile to name. Replaces one of that name. @experimental */+export function registerFingerPose(name: string, pose: FingerPoseDef): void {+ fingerPoses.set(name, { joints: Object.fromEntries(Object.entries(pose.joints).map(([k, v]) => [k, q.normalize({ ...v })])) });+}++/** The finger pose of that name, or undefined. @experimental */+export function fingerPose(name: string): FingerPoseDef | undefined {+ return fingerPoses.get(name);+}++/** The turn of every named joint below `hand`, as it stands now: what a pose made by hand, or by a GripPose, is kept as. Plain JSON. @experimental */+export function captureFingerPose(world: World, hand: Entity): FingerPoseDef {+ const joints: Record<string, Quat> = {};+ const walk = (at: Entity): void => {+ for (const child of (world.tryGet(at, Children) as { entities?: Entity[] } | null)?.entities ?? []) {+ const name = (world.tryGet(child, Name) as { value?: string } | null)?.value;+ if (name && world.has(child, Transform)) {+ const r = (world.get(child, Transform) as TransformData).rotation;+ joints[name] = { w: r.w, x: r.x, y: r.y, z: r.z };+ }+ walk(child);+ }+ };+ walk(hand);+ return { joints };+}++/** A place, a turn and an even scale. */+interface Pose3 { p: Vec3; r: Quat; s: number }++const add = (a: Vec3, b: Vec3): Vec3 => ({ x: a.x + b.x, y: a.y + b.y, z: a.z + b.z });+const sub = (a: Vec3, b: Vec3): Vec3 => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });+const scale = (a: Vec3, k: number): Vec3 => ({ x: a.x * k, y: a.y * k, z: a.z * k });+const len = (a: Vec3): number => Math.hypot(a.x, a.y, a.z);+const dot = (a: Vec3, b: Vec3): number => a.x * b.x + a.y * b.y + a.z * b.z;+const norm = (a: Vec3): Vec3 => { const l = len(a); return l < 1e-12 ? { x: 0, y: 0, z: 0 } : scale(a, 1 / l); };+const then = (a: Pose3, b: Pose3): Pose3 => ({ p: add(a.p, q.rotate(a.r, scale(b.p, a.s))), r: q.normalize(q.mul(a.r, b.r)), s: a.s * b.s });+const inverse = (a: Pose3): Pose3 => { const r = q.conjugate(a.r), s = 1 / a.s; return { p: scale(q.rotate(r, a.p), -s), r, s }; };++/** Spherical interpolation, the shorter way: what a weight between a clip and a grip means. */+export function slerpQuat(a: Quat, b: Quat, t: number): Quat {+ let d = a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z;+ const sign = d < 0 ? -1 : 1;+ d = Math.abs(d);+ if (d > 0.9995) {+ const k = 1 - t;+ return q.normalize({ w: a.w * k + b.w * t * sign, x: a.x * k + b.x * t * sign, y: a.y * k + b.y * t * sign, z: a.z * k + b.z * t * sign });+ }+ const theta = Math.acos(d), sinT = Math.sin(theta);+ const wa = Math.sin((1 - t) * theta) / sinT, wb = (Math.sin(t * theta) / sinT) * sign;+ return { w: a.w * wa + b.w * wb, x: a.x * wa + b.x * wb, y: a.y * wa + b.y * wb, z: a.z * wa + b.z * wb };+}++/** An entity's place in the world as it stands, from the composed transform. */+function worldOf(world: World, e: Entity): Pose3 {+ const t = world.get(e, Transform) as TransformData;+ return { p: { ...t.worldPosition }, r: q.normalize(t.worldRotation), s: t.worldScale.x };+}++function localOf(world: World, e: Entity): Pose3 {+ const t = world.get(e, Transform) as TransformData;+ return { p: { ...t.position }, r: q.normalize(t.rotation), s: t.scale.x };+}++function parentOf(world: World, e: Entity): Entity | null {+ const p = world.tryGet(e, Parent) as { entity?: Entity } | null;+ return p && typeof p.entity === 'number' && world.valid(p.entity) ? p.entity : null;+}++/** An anchor's place on its object: its locals composed up to the object, so it follows the object wherever this frame puts it. */+function anchorOn(world: World, object: Entity, anchor: Entity): Pose3 | null {+ let at: Entity | null = anchor;+ let pose: Pose3 = { p: { x: 0, y: 0, z: 0 }, r: { w: 1, x: 0, y: 0, z: 0 }, s: 1 };+ for (let guard = 0; at !== null && guard < 32; guard++) {+ if (at === object) return pose;+ pose = then(localOf(world, at), pose);+ at = parentOf(world, at);+ }+ return null;+}++/** One hand's arm and palm, found once. */+interface Arm {+ hand: Entity;+ forearm: Entity;+ upper: Entity;+ /** The palm, from the hand joint. */+ palm: Pose3;+ /** The finger joints by name, for a captured pose. */+ fingers: Map<string, Entity>;+}++function armOf(world: World, root: Entity, side: 'right' | 'left', path: string): Arm | null {+ const hand = path ? resolveChildEntity(world, root, path) : findHand(world, root, side);+ if (hand === null) return null;+ const forearm = parentOf(world, hand), upper = forearm === null ? null : parentOf(world, forearm);+ const frame = palmFrameOf(world, hand, side);+ if (forearm === null || upper === null || !frame) return null;+ const fingers = new Map<string, Entity>();+ const walk = (at: Entity): void => {+ for (const child of (world.tryGet(at, Children) as { entities?: Entity[] } | null)?.entities ?? []) {+ const name = (world.tryGet(child, Name) as { value?: string } | null)?.value;+ if (name) fingers.set(name, child);+ walk(child);+ }+ };+ walk(hand);+ return { hand, forearm, upper, palm: { p: frame.center, r: frame.turn, s: 1 }, fingers };+}++/** The joints a hold writes, and what it last wrote to each, to blend from when what is held changes and to tell a clip's writes from its own. */+interface HolderState {+ arms: { right: Arm | null; left: Arm | null };+ paths: string;+ held: Entity;+ /** How much of the hold applies now, and how fast it is moving: eased toward the weight. */+ amount: number;+ speed: number;+ /** On a change of what is held: each joint's turn as it was, eased away from. */+ from: Map<Entity, Quat>;+ change: number;+ changeSpeed: number;+ written: Map<Entity, Quat>;+ /** Each joint's turn as something else last left it: the clip's, which a hold goes over. */+ base: Map<Entity, Quat>;+}++/** Eases `value` toward `wanted`, critically damped: from still, and to rest without passing it. */+function ease(value: number, speed: number, wanted: number, blend: number, dt: number): [number, number] {+ if (blend <= 0) return [wanted, 0];+ const omega = 6 / blend;+ const gap = value - wanted;+ const carry = (speed + omega * gap) * dt;+ const fade = Math.exp(-omega * dt);+ const nextSpeed = (speed - omega * carry) * fade;+ const next = wanted + (gap + carry) * fade;+ return Math.abs(next - wanted) < 1e-4 && Math.abs(nextSpeed) < 1e-3 ? [wanted, 0] : [next, nextSpeed];+}++/**+ * The upper arm and forearm turned so the hand joint lands on `goal`, the elbow keeping the side it is bent toward; then the hand turned to `handTurn`.+ * World turns in, each joint's own turn out. The arm cannot be longer than it is: past its reach it points straight at the goal.+ */+function bendArm(world: World, arm: Arm, goal: Vec3, handTurn: Quat): Map<Entity, Quat> {+ const upper = worldOf(world, arm.upper), fore = worldOf(world, arm.forearm), hand = worldOf(world, arm.hand);+ const shoulder = parentOf(world, arm.upper);+ const shoulderTurn = shoulder === null ? { w: 1, x: 0, y: 0, z: 0 } : worldOf(world, shoulder).r;+ const a = len(sub(fore.p, upper.p)), b = len(sub(hand.p, fore.p));+ const reach = sub(goal, upper.p);+ const out = new Map<Entity, Quat>();+ if (a < 1e-9 || b < 1e-9 || len(reach) < 1e-9) return out;+ const c = Math.min(Math.max(len(reach), Math.abs(a - b) + 1e-6), a + b - 1e-6);+ const along = norm(reach);+ // The side the elbow is bent to now; a straight arm takes any side off the line.+ let side = sub(sub(fore.p, upper.p), scale(along, dot(sub(fore.p, upper.p), along)));+ if (len(side) < 1e-9) side = { x: -along.y, y: along.x, z: 0 };+ if (len(side) < 1e-9) side = { x: 0, y: -along.z, z: along.y };+ side = norm(side);+ const cos = Math.min(1, Math.max(-1, (a * a + c * c - b * b) / (2 * a * c)));+ const elbow = add(upper.p, add(scale(along, a * cos), scale(side, a * Math.sqrt(Math.max(0, 1 - cos * cos)))));+ const tip = add(upper.p, scale(along, c));+ const upperTurn = q.normalize(q.mul(q.rotationTo(sub(fore.p, upper.p), sub(elbow, upper.p)), upper.r));+ const carried = q.normalize(q.mul(upperTurn, q.conjugate(upper.r)));+ const foreTurn = q.normalize(q.mul(q.rotationTo(q.rotate(carried, sub(hand.p, fore.p)), sub(tip, elbow)), q.mul(carried, fore.r)));+ out.set(arm.upper, q.normalize(q.mul(q.conjugate(shoulderTurn), upperTurn)));+ out.set(arm.forearm, q.normalize(q.mul(q.conjugate(upperTurn), foreTurn)));+ out.set(arm.hand, q.normalize(q.mul(q.conjugate(foreTurn), handTurn)));+ return out;+}++/** Where the hand joint and its turn must be for its palm to sit on `anchor`, a pose in the world. */+function handFor(arm: Arm, anchor: Pose3, handScale: number): { at: Vec3; turn: Quat } {+ const turn = q.normalize(q.mul(anchor.r, q.conjugate(arm.palm.r)));+ return { at: sub(anchor.p, q.rotate(turn, scale(arm.palm.p, handScale))), turn };+}++/** The fingers' own turns for a pose: a captured one by joint name. Null where it names no captured pose. */+function capturedFingers(arm: Arm, poseName: string): Map<Entity, Quat> | null {+ const pose = fingerPoses.get(poseName);+ if (!pose) return null;+ const out = new Map<Entity, Quat>();+ for (const [name, rotation] of Object.entries(pose.joints)) {+ const joint = arm.fingers.get(name);+ if (joint !== undefined) out.set(joint, rotation);+ }+ return out;+}++const rigs = new WeakMap<App, Map<Entity, HolderState>>();++/** Runs every holder. Called by the animation plugin, before the grip poses it hands fingers to. */+export function installGripHold(app: App): void {+ const known = new Map<Entity, HolderState>();+ rigs.set(app, known);+ // system-access: what a hold writes (arm joints, fingers, the held object) is found by walking the rig and the object.+ app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time), GetWorld()], (time: TimeData, world: World) => {+ for (const [rig] of known) if (!world.valid(rig) || !world.has(rig, GripHolder)) known.delete(rig);+ const holders = [...world.getEntitiesWithComponents([GripHolder])];+ if (holders.length === 0) return;+ world.ensureTransformsComposed();+ // What a hold wrote last frame goes back to the clip's pose first, so every solve starts from this frame's clip and never from its own last answer.+ let restored = false;+ for (const state of known.values()) {+ for (const [joint, written] of state.written) {+ if (!world.valid(joint) || !world.has(joint, Transform)) continue;+ const now = (world.get(joint, Transform) as TransformData).rotation;+ const base = state.base.get(joint);+ if (base && same(now, written)) { world.update(joint, Transform, (t: TransformData) => { t.rotation = { ...base }; }); restored = true; }+ }+ }+ if (restored) world.ensureTransformsComposed();+ for (const rig of holders) hold(world, known, rig, world.get(rig, GripHolder) as GripHolderData, time.delta);+ }, { name: 'GripHoldSystem' }), { runAfter: [SystemLabel.Animator], runIf: playModeOnly });+}++function hold(world: World, known: Map<Entity, HolderState>, rig: Entity, data: GripHolderData, dt: number): void {+ const paths = `${data.rightHand}|${data.leftHand}`;+ let state = known.get(rig);+ if (!state || state.paths !== paths) {+ const right = armOf(world, rig, 'right', data.rightHand), left = armOf(world, rig, 'left', data.leftHand);+ if (!right && !left) log.warn('animation', `a GripHolder found no arm with a hand on "${(world.tryGet(rig, Name) as { value?: string } | null)?.value ?? rig}"`);+ state = { arms: { right, left }, paths, held: 0 as Entity, amount: 0, speed: 0, from: new Map(), change: 1, changeSpeed: 0, written: new Map(), base: new Map() };+ known.set(rig, state);+ }+ const held = data.held && world.valid(data.held) && world.has(data.held, GripProfile) ? data.held : 0 as Entity;+ if (held !== state.held) {+ // What is held changed: every joint eases from where it was, so the hands go to the new grip and do not jump.+ state.from = new Map(state.written);+ state.change = state.from.size ? 0 : 1;+ state.changeSpeed = 0;+ state.held = held;+ }+ [state.amount, state.speed] = ease(state.amount, state.speed, held ? Math.min(1, Math.max(0, data.weight)) : 0, data.blendSeconds, dt);+ [state.change, state.changeSpeed] = ease(state.change, state.changeSpeed, 1, data.blendSeconds, dt);+ const main = data.mainHand === GripHand.Left ? state.arms.left : state.arms.right;+ const support = data.mainHand === GripHand.Left ? state.arms.right : state.arms.left;+ const wanted = new Map<Entity, Quat>();+ const fingerNames: { arm: Arm; pose: string; weight: number }[] = [];++ if (held && main) {+ const profile = world.get(held, GripProfile) as GripProfileData;+ const mainAnchor = profile.mainAnchor ? anchorOn(world, held, profile.mainAnchor) : null;+ const supportAnchor = profile.supportAnchor ? anchorOn(world, held, profile.supportAnchor) : null;+ if (mainAnchor) {+ const handWorld = worldOf(world, main.hand);+ let object: Pose3;+ if (data.placement === GripPlacement.Object) {+ // The game has put the object: the leading arm is brought to its anchor.+ object = worldOf(world, held);+ const goal = handFor(main, then(object, mainAnchor), handWorld.s);+ for (const [joint, turn] of bendArm(world, main, goal.at, goal.turn)) wanted.set(joint, turn);+ } else {+ // The object rides the leading hand, wherever the clip has put it.+ object = then(then(handWorld, main.palm), inverse(mainAnchor));+ const parent = parentOf(world, held);+ const local = parent === null ? object : then(inverse(worldOf(world, parent)), object);+ world.update(held, Transform, (t: TransformData) => {+ t.position = { ...local.p };+ t.rotation = { ...local.r };+ });+ }+ fingerNames.push({ arm: main, pose: profile.mainPose, weight: 1 });+ const supportWeight = Math.min(1, Math.max(0, data.supportWeight));+ if (support && supportAnchor && supportWeight > 0) {+ // Read off the object as it now stands; the object never reads this hand.+ const goal = handFor(support, then(object, supportAnchor), worldOf(world, support.hand).s);+ for (const [joint, turn] of bendArm(world, support, goal.at, goal.turn)) {+ wanted.set(joint, turn);+ supportWeights.set(joint, supportWeight);+ }+ fingerNames.push({ arm: support, pose: profile.supportPose, weight: supportWeight });+ }+ }+ }++ // The fingers last: a captured pose by joint, or a grip pose handed to the GripPose that holds the hand.+ const presets: Partial<GripPoseData> = {};+ for (const { arm, pose, weight } of fingerNames) {+ const captured = capturedFingers(arm, pose);+ if (captured) {+ for (const [joint, turn] of captured) { wanted.set(joint, turn); supportWeights.set(joint, weight); }+ } else if (gripPose(pose)) {+ const right = arm === state.arms.right;+ if (right) { presets.rightPose = pose; presets.rightWeight = state.amount * weight; } else { presets.leftPose = pose; presets.leftWeight = state.amount * weight; }+ }+ }+ if (Object.keys(presets).length || world.has(rig, GripPose)) {+ if (!world.has(rig, GripPose)) world.insert(rig, GripPose, { blendSeconds: data.blendSeconds });+ world.update(rig, GripPose, (g: GripPoseData) => {+ if (presets.rightPose !== undefined) { g.rightPose = presets.rightPose; g.rightWeight = presets.rightWeight!; } else if (state!.amount === 0) g.rightWeight = 0;+ if (presets.leftPose !== undefined) { g.leftPose = presets.leftPose; g.leftWeight = presets.leftWeight!; } else if (state!.amount === 0) g.leftWeight = 0;+ });+ }++ // Every joint once: the clip's turn, toward the hold's by how much of it applies, and from the old grip by how far the change has come.+ const touched = new Set<Entity>([...wanted.keys(), ...state.written.keys()]);+ for (const joint of touched) {+ if (!world.valid(joint) || !world.has(joint, Transform)) continue;+ // Already put back to the clip's turn at the top of the frame where nothing else moved it; what a clip wrote since is the new base.+ const clip = (world.get(joint, Transform) as TransformData).rotation;+ state.base.set(joint, { w: clip.w, x: clip.x, y: clip.y, z: clip.z });+ const target = wanted.get(joint);+ const share = state.amount * (supportWeights.get(joint) ?? 1);+ let out = target ? slerpQuat(clip, target, share) : clip;+ const from = state.from.get(joint);+ if (from && state.change < 1) out = slerpQuat(from, out, state.change);+ const value = q.normalize(out);+ world.update(joint, Transform, (t: TransformData) => { t.rotation = { ...value }; });+ const stored = (world.get(joint, Transform) as TransformData).rotation;+ if (target || state.change < 1) state.written.set(joint, { w: stored.w, x: stored.x, y: stored.y, z: stored.z });+ else state.written.delete(joint);+ }+ supportWeights.clear();+ if (state.change >= 1) state.from.clear();+}++/** Per joint, the share of the hold it takes: the supporting hand's weight on its arm and fingers. Reused across holders in one frame. */+const supportWeights = new Map<Entity, number>();++const same = (a: Quat, b: Quat): boolean => Math.abs(a.w - b.w) < 1e-6 && Math.abs(a.x - b.x) < 1e-6 && Math.abs(a.y - b.y) < 1e-6 && Math.abs(a.z - b.z) < 1e-6;++/** What a holder found and is doing. @experimental */+export function gripHolderStatus(app: App, rig: Entity): { right: boolean; left: boolean; amount: number; held: Entity } | null {+ const state = rigs.get(app)?.get(rig);+ return state ? { right: !!state.arms.right, left: !!state.arms.left, amount: state.amount, held: state.held } : null;+}diff --git a/sdk/src/animation/gripPose.ts b/sdk/src/animation/gripPose.tsindex 8b8e25a8b..18b8d6c35 100644--- a/sdk/src/animation/gripPose.ts+++ b/sdk/src/animation/gripPose.ts@@ -404,8 +404,43 @@ const NOT_A_HAND = /thumb|index|middle|ring|pinky|pinkie|little|finger|metacarpaconst IS_RIGHT = /right|(^|[^a-z])r($|[^a-z])/i;const IS_LEFT = /left|(^|[^a-z])l($|[^a-z])/i;-/** The joint named for that hand under `root`, nearest first. */-function findHand(world: World, root: Entity, side: 'right' | 'left'): Entity | null {+/**+ * The palm of a hand joint, in the hand's own frame: its centre (halfway to the middle knuckle), and the turn whose +Z is the way the fingers point+ * and whose +Y is the way the palm faces. Null for a hand whose fingers say neither. @internal+ */+export function palmFrameOf(world: World, hand: Entity, side: 'right' | 'left'): { center: Vec3; turn: Quat } | null {+ const chains: Partial<Record<FingerName, Entity[]>> = {};+ for (const name of FINGERS) chains[name] = fingerChain(world, hand, name);+ const shape = palmOf(world, side, chains);+ const knuckle = (chains.middle?.length ? chains.middle : chains.index?.length ? chains.index : chains.ring) ?? null;+ if (!shape || !knuckle?.length) return null;+ const z = shape.forward, y = norm(sub(shape.palm, scale(z, dot(shape.palm, z))));+ const x = cross(y, z);+ return { center: scale(fromHand(world, [knuckle[0]!]).at[0]!, 0.5), turn: basisTurn(x, y, z) };+}++/** The turn that takes +X, +Y, +Z to three square unit vectors. */+function basisTurn(x: Vec3, y: Vec3, z: Vec3): Quat {+ const trace = x.x + y.y + z.z;+ let w: number, qx: number, qy: number, qz: number;+ if (trace > 0) {+ const s = Math.sqrt(trace + 1) * 2;+ w = s / 4; qx = (y.z - z.y) / s; qy = (z.x - x.z) / s; qz = (x.y - y.x) / s;+ } else if (x.x > y.y && x.x > z.z) {+ const s = Math.sqrt(1 + x.x - y.y - z.z) * 2;+ w = (y.z - z.y) / s; qx = s / 4; qy = (y.x + x.y) / s; qz = (z.x + x.z) / s;+ } else if (y.y > z.z) {+ const s = Math.sqrt(1 + y.y - x.x - z.z) * 2;+ w = (z.x - x.z) / s; qx = (y.x + x.y) / s; qy = s / 4; qz = (z.y + y.z) / s;+ } else {+ const s = Math.sqrt(1 + z.z - x.x - y.y) * 2;+ w = (x.y - y.x) / s; qx = (z.x + x.z) / s; qy = (z.y + y.z) / s; qz = s / 4;+ }+ return q.normalize({ w, x: qx, y: qy, z: qz });+}++/** The joint named for that hand under `root`, nearest first. @internal */+export function findHand(world: World, root: Entity, side: 'right' | 'left'): Entity | null {const wanted = side === 'right' ? IS_RIGHT : IS_LEFT;const queue: Entity[] = [root];for (let i = 0; i < queue.length && i < 512; i++) {diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex 46ac457a4..21340f656 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -85,6 +85,10 @@ export {GripPose, registerGripPose, gripPose, gripPoseNames, gripPoseStatus,type GripPoseData, type GripPoseDef, type GripFinger, type GripThumb, type GripHandStatus,} from './gripPose';+export {+ GripProfile, GripHolder, GripHand, GripPlacement, registerFingerPose, fingerPose, captureFingerPose, gripHolderStatus, slerpQuat,+ type GripProfileData, type GripHolderData, type FingerPoseDef,+} from './gripHold';export {emptyAnimatorController,diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 66b32597f..2d5c8c03e 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -660,6 +660,18 @@ export {type GripFinger,type GripThumb,type GripHandStatus,+ GripProfile,+ GripHolder,+ GripHand,+ GripPlacement,+ registerFingerPose,+ fingerPose,+ captureFingerPose,+ gripHolderStatus,+ slerpQuat,+ type GripProfileData,+ type GripHolderData,+ type FingerPoseDef,} from './animation';// =============================================================================diff --git a/sdk/tests/grip-hold-wasm.test.ts b/sdk/tests/grip-hold-wasm.test.tsnew file mode 100644index 000000000..fd86521c7--- /dev/null+++ b/sdk/tests/grip-hold-wasm.test.ts@@ -0,0 +1,366 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Holding an object, on the real engine, against the four things asked of it: a change of what is held does not make a hand jump; the two hands+ * cannot drive each other round a loop; a different body still puts its palm where the object says; and the same inputs give the same bones.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { AnimationPlugin } from '../src/animation/AnimationPlugin';+import { GripHolder, GripPlacement, GripProfile, captureFingerPose, gripHolderStatus, registerFingerPose, slerpQuat, type GripHolderData } from '../src/animation/gripHold';+import { palmFrameOf } from '../src/animation/gripPose';+import { Name, Parent, Transform, type TransformData } from '../src/ecs/component';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { q } from '../src/math/quat';+import type { Entity } from '../src/types';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++interface V { x: number; y: number; z: number }+interface Q { w: number; x: number; y: number; z: number }+const I: Q = { w: 1, x: 0, y: 0, z: 0 };++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => { while (apps.length) apps.pop()!.quit?.(); setEditorMode(false); setPlayMode(false); });++function scene() {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });+ setPlayMode(true);+ app.addPlugin(new AnimationPlugin());+ const tick = async (n = 1, dt = 1 / 60): Promise<void> => { for (let i = 0; i < n; i++) { await app.tick(dt); await Promise.resolve(); } };+ return { app, world: app.world, tick };+}+type World = App['world'];++const FINGERS: Record<string, { from: V; lengths: number[] }> = {+ Thumb: { from: { x: -0.03, y: 0.02, z: -0.01 }, lengths: [0.035, 0.03, 0.025] },+ Index: { from: { x: -0.025, y: 0.09, z: 0 }, lengths: [0.04, 0.025, 0.02] },+ Middle: { from: { x: -0.005, y: 0.095, z: 0 }, lengths: [0.045, 0.03, 0.02] },+ Ring: { from: { x: 0.015, y: 0.09, z: 0 }, lengths: [0.04, 0.028, 0.02] },+ Pinky: { from: { x: 0.033, y: 0.08, z: 0 }, lengths: [0.03, 0.02, 0.018] },+};++/**+ * A body with two arms reaching forward (+Z) from shoulders 0.2 apart, each ending in a hand whose fingers point along the arm and whose palm faces+ * down. `upper` and `fore` are the arm's two lengths, to try another body with the same object.+ */+function body(world: World, options: { upper?: number; fore?: number } = {}) {+ const upperLen = options.upper ?? 0.3, foreLen = options.fore ?? 0.27;+ const spawn = (name: string, parent: Entity | null, position: V, rotation: Q = I): Entity => {+ const e = world.spawn(name);+ world.insert(e, Name, { value: name });+ world.insert(e, Transform, { position, rotation });+ if (parent !== null) world.setParent(e, parent);+ return e;+ };+ const root = spawn('Hero', null, { x: 0, y: 0, z: 0 });+ const spine = spawn('mixamorig:Spine', root, { x: 0, y: 1.4, z: 0 });+ // Bones along +Y, turned so +Y runs forward: the hand's fingers point ahead, its palm down.+ const forward = q.normalize({ w: Math.SQRT1_2, x: Math.SQRT1_2, y: 0, z: 0 });+ const arms: Record<string, { upper: Entity; fore: Entity; hand: Entity }> = {};+ for (const [side, mirror] of [['Right', -1], ['Left', 1]] as const) {+ const shoulder = spawn(`mixamorig:${side}Shoulder`, spine, { x: 0.2 * mirror, y: 0, z: 0 }, forward);+ // A slight bend down at the elbow, so the arm has a side to bend to.+ const upper = spawn(`mixamorig:${side}Arm`, shoulder, { x: 0, y: 0.05, z: 0 }, q.normalize({ w: 0.999, x: 0.04, y: 0, z: 0 }));+ const fore = spawn(`mixamorig:${side}ForeArm`, upper, { x: 0, y: upperLen, z: 0 }, q.normalize({ w: 0.995, x: -0.1, y: 0, z: 0 }));+ const hand = spawn(`mixamorig:${side}Hand`, fore, { x: 0, y: foreLen, z: 0 });+ for (const [finger, f] of Object.entries(FINGERS)) {+ let parent = hand, at: V = { x: f.from.x * -mirror, y: f.from.y, z: f.from.z };+ let prev: V = { x: 0, y: 0, z: 0 };+ const dir = finger === 'Thumb' ? { x: -0.7 * -mirror, y: 0.7, z: 0 } : { x: 0, y: 1, z: 0 };+ const unit = Math.hypot(dir.x, dir.y, dir.z);+ for (let i = 0; i <= f.lengths.length; i++) {+ parent = spawn(`mixamorig:${side}Hand${finger}${i + 1}`, parent, { x: at.x - prev.x, y: at.y - prev.y, z: at.z - prev.z });+ prev = at;+ if (i < f.lengths.length) at = { x: at.x + dir.x / unit * f.lengths[i]!, y: at.y + dir.y / unit * f.lengths[i]!, z: at.z + dir.z / unit * f.lengths[i]! };+ }+ }+ arms[side] = { upper, fore, hand };+ }+ return { root, arms };+}++/** An object with a leading and a supporting anchor, the second `apart` ahead of the first. */+function gun(world: World, at: V, apart = 0.18, name = 'Gun', across = 0) {+ const e = world.spawn(name);+ world.insert(e, Name, { value: name });+ world.insert(e, Transform, { position: at });+ const anchor = (label: string, p: V, r: Q = I): Entity => {+ const a = world.spawn(label);+ world.insert(a, Name, { value: label });+ world.insert(a, Transform, { position: p, rotation: r });+ world.setParent(a, e);+ return a;+ };+ // Fingers ahead (+Z) and the palm facing down (-Y is the way +Y of the anchor must face here, so turned about Z by half a turn).+ const down = { w: 0, x: 0, y: 0, z: 1 };+ // Off the object's origin, so an anchor read as the object itself is caught.+ const main = anchor('Main', { x: 0.01, y: -0.03, z: -0.02 }, down);+ const support = anchor('Support', { x: across, y: 0.02, z: apart }, down);+ world.insert(e, GripProfile, { mainAnchor: main, supportAnchor: support, mainPose: '', supportPose: '' });+ return { e, main, support };+}++/** A bone's world pose from the locals, so a test does not lean on the engine's own composing. */+function worldPose(world: World, e: Entity): { p: V; r: Q } {+ const chain: Entity[] = [];+ for (let at: Entity | null = e; at !== null;) {+ chain.unshift(at);+ const p = world.tryGet(at, Parent) as { entity?: Entity } | null;+ at = p && typeof p.entity === 'number' ? p.entity : null;+ }+ let p: V = { x: 0, y: 0, z: 0 }, r: Q = I;+ for (const link of chain) {+ const t = world.get(link, Transform) as TransformData;+ const v = q.rotate(r, t.position);+ p = { x: p.x + v.x, y: p.y + v.y, z: p.z + v.z };+ r = q.normalize(q.mul(r, t.rotation));+ }+ return { p, r };+}++function palmOf(world: World, hand: Entity, side: 'right' | 'left') {+ const frame = palmFrameOf(world, hand, side)!;+ const h = worldPose(world, hand);+ const v = q.rotate(h.r, frame.center);+ return { p: { x: h.p.x + v.x, y: h.p.y + v.y, z: h.p.z + v.z }, r: q.normalize(q.mul(h.r, frame.turn)) };+}++const dist = (a: V, b: V): number => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);+/** The angle between two turns, by the sine of the half angle: acos of a dot product near 1 turns float32 rounding into a thousandth of a radian. */+const angle = (a: Q, b: Q): number => { const d = q.mul(q.conjugate(a), b); return 2 * Math.atan2(Math.hypot(d.x, d.y, d.z), Math.abs(d.w)); };+const rotationsOf = (world: World, joints: Entity[]): Q[] => joints.map((j) => ({ ...(world.get(j, Transform) as TransformData).rotation }));+const holder = (world: World, root: Entity, data: Partial<GripHolderData>): void => { world.insert(root, GripHolder, { blendSeconds: 0, ...data }); };++/** Puts the supporting anchor where the left arm can reach, read off the object as it now stands: in front of the chest, the palm down. */+function reachable(world: World, g: { e: Entity; support: Entity }, at: V = { x: 0.02, y: 1.38, z: 0.5 }): void {+ const o = worldPose(world, g.e);+ const back = q.conjugate(o.r);+ const local = q.rotate(back, { x: at.x - o.p.x, y: at.y - o.p.y, z: at.z - o.p.z });+ const down = { w: 0, x: 0, y: 0, z: 1 };+ world.update(g.support, Transform, (t: TransformData) => { t.position = local; t.rotation = q.normalize(q.mul(back, q.mul(o.r, q.mul(q.conjugate(o.r), down)))); });+}+const armJoints = (b: ReturnType<typeof body>): Entity[] => Object.values(b.arms).flatMap((a) => [a.upper, a.fore, a.hand]);++describe.skipIf(!HAS_WASM)('holding an object', () => {+ beforeAll(async () => { if (HAS_WASM) core = await loadWasmModule(); });++ it('puts the leading palm on the object\'s anchor when the game places the object', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });+ await s.tick(2);+ const palm = palmOf(s.world, b.arms.Right!.hand, 'right');+ const anchor = worldPose(s.world, g.main);+ expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);+ expect(angle(palm.r, anchor.r)).toBeLessThan(0.01);+ });++ it('carries the object on the leading hand where the clip has put it, and leaves that hand alone', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ const before = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, supportWeight: 0 });+ await s.tick(2);+ const palm = palmOf(s.world, b.arms.Right!.hand, 'right');+ const anchor = worldPose(s.world, g.main);+ expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);+ expect(angle(palm.r, anchor.r)).toBeLessThan(0.01);+ const after = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);+ after.forEach((r, i) => expect(angle(r, before[i]!)).toBeLessThan(1e-6));+ });++ it('brings the supporting palm to its anchor on the object as it now stands', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });+ await s.tick(1);+ reachable(s.world, g);+ await s.tick(2);+ const palm = palmOf(s.world, b.arms.Left!.hand, 'left');+ const anchor = worldPose(s.world, g.support);+ expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);+ });++ describe('does not make a hand jump when what is held changes', () => {+ it('eases every joint over, each frame a small part of the way', async () => {+ const run = async (blend: number) => {+ const s = scene();+ const b = body(s.world);+ const a = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 }, 0.18, 'A');+ const c = gun(s.world, { x: -0.05, y: 1.1, z: 0.35 }, 0.1, 'B');+ holder(s.world, b.root, { held: a.e, placement: GripPlacement.Object, blendSeconds: blend });+ await s.tick(60);+ const joints = armJoints(b);+ let last = rotationsOf(s.world, joints), biggest = 0, total = 0;+ const start = last;+ s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = c.e; });+ for (let i = 0; i < 60; i++) {+ await s.tick(1);+ const now = rotationsOf(s.world, joints);+ biggest = Math.max(biggest, ...now.map((r, k) => angle(r, last[k]!)));+ last = now;+ }+ total = Math.max(...last.map((r, k) => angle(r, start[k]!)));+ return { biggest, total };+ };+ const eased = await run(0.25), cut = await run(0);+ expect(cut.biggest).toBeCloseTo(cut.total, 3);+ expect(eased.total).toBeCloseTo(cut.total, 3);+ expect(eased.biggest).toBeLessThan(eased.total * 0.15);+ });++ it('takes hold and lets go the same way, back to the clip\'s pose', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });+ const joints = armJoints(b);+ const rest = rotationsOf(s.world, joints);+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, blendSeconds: 0.25 });+ let last = rest, biggest = 0;+ for (let i = 0; i < 60; i++) { await s.tick(1); const now = rotationsOf(s.world, joints); biggest = Math.max(biggest, ...now.map((r, k) => angle(r, last[k]!))); last = now; }+ const held = Math.max(...last.map((r, k) => angle(r, rest[k]!)));+ expect(held).toBeGreaterThan(0.2);+ expect(biggest).toBeLessThan(held * 0.15);+ s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = 0 as Entity; });+ await s.tick(60);+ rotationsOf(s.world, joints).forEach((r, k) => expect(angle(r, rest[k]!)).toBeLessThan(1e-3));+ });+ });++ describe('cannot drive itself round a loop', () => {+ it('moves neither the object nor the leading arm when the supporting anchor moves', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });+ await s.tick(1);+ reachable(s.world, g);+ await s.tick(3);+ const object = worldPose(s.world, g.e), main = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);+ reachable(s.world, g, { x: 0.08, y: 1.33, z: 0.45 });+ await s.tick(3);+ const after = worldPose(s.world, g.e);+ expect(dist(after.p, object.p)).toBe(0);+ rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]).forEach((r, k) => expect(r).toEqual(main[k]));+ expect(dist(palmOf(s.world, b.arms.Left!.hand, 'left').p, worldPose(s.world, g.support).p)).toBeLessThan(1e-3);+ });++ it('stays exactly where it settled, frame after frame, with nothing changing', async () => {+ for (const placement of [GripPlacement.Hand, GripPlacement.Object]) {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, placement === GripPlacement.Hand ? { x: 3, y: 0, z: 0 } : { x: -0.15, y: 1.25, z: 0.45 });+ holder(s.world, b.root, { held: g.e, placement, blendSeconds: 0.2 });+ await s.tick(90);+ const joints = armJoints(b);+ const settled = rotationsOf(s.world, joints), object = worldPose(s.world, g.e);+ await s.tick(300);+ expect(rotationsOf(s.world, joints)).toEqual(settled);+ expect(worldPose(s.world, g.e)).toEqual(object);+ }+ });+ });++ describe('puts the palm where the object says on another body', () => {+ it('for arms shorter and longer than the one it was made with', async () => {+ for (const [upper, fore] of [[0.24, 0.22], [0.3, 0.27], [0.36, 0.32]]) {+ const s = scene();+ const b = body(s.world, { upper, fore });+ const g = gun(s.world, { x: -0.12, y: 1.32, z: 0.3 }, 0.12, 'Gun', 0.22);+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object });+ await s.tick(2);+ for (const [side, hand, anchor] of [['right', b.arms.Right!.hand, g.main], ['left', b.arms.Left!.hand, g.support]] as const) {+ const palm = palmOf(s.world, hand, side);+ const at = worldPose(s.world, anchor);+ expect(dist(palm.p, at.p), `${side} at ${upper}+${fore}`).toBeLessThan(1e-3);+ expect(angle(palm.r, at.r), `${side} at ${upper}+${fore}`).toBeLessThan(0.01);+ }+ }+ });++ it('out of reach, points the arm straight at the anchor and turns the palm to it, every time the same', async () => {+ const s = scene();+ const b = body(s.world, { upper: 0.2, fore: 0.18 });+ const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.9 });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });+ await s.tick(2);+ const shoulder = worldPose(s.world, b.arms.Right!.upper).p, elbow = worldPose(s.world, b.arms.Right!.fore).p, hand = worldPose(s.world, b.arms.Right!.hand).p;+ const anchor = worldPose(s.world, g.main);+ const toward = (from: V, to: V): V => { const d = dist(from, to); return { x: (to.x - from.x) / d, y: (to.y - from.y) / d, z: (to.z - from.z) / d }; };+ const a = toward(shoulder, elbow), c = toward(elbow, hand), goal = toward(shoulder, anchor.p);+ expect(a.x * c.x + a.y * c.y + a.z * c.z).toBeGreaterThan(0.999);+ expect(a.x * goal.x + a.y * goal.y + a.z * goal.z).toBeGreaterThan(0.99);+ expect(angle(palmOf(s.world, b.arms.Right!.hand, 'right').r, anchor.r)).toBeLessThan(0.01);+ });+ });++ it('gives the same bones for the same inputs, to the last bit', async () => {+ const steps = [1 / 60, 1 / 30, 1 / 144, 1 / 60, 1 / 45, 1 / 60, 1 / 90];+ const run = async () => {+ const s = scene();+ const b = body(s.world);+ const a = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 }, 0.18, 'A');+ const c = gun(s.world, { x: -0.05, y: 1.1, z: 0.35 }, 0.1, 'B');+ holder(s.world, b.root, { held: a.e, placement: GripPlacement.Object, blendSeconds: 0.2 });+ for (let i = 0; i < 40; i++) await s.tick(1, steps[i % steps.length]);+ s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = c.e; });+ for (let i = 0; i < 20; i++) await s.tick(1, steps[i % steps.length]);+ return [...rotationsOf(s.world, armJoints(b)), ...Object.values(b.arms).flatMap((arm) => rotationsOf(s.world, [arm.hand]))];+ };+ expect(await run()).toEqual(await run());+ });++ it('blends a captured finger pose over the clip by the weight, as slerp(clip, grip, w)', async () => {+ const s = scene();+ const b = body(s.world);+ const finger = s.world.getEntitiesWithComponents([Name]).find((e) => (s.world.get(e, Name) as { value: string }).value === 'mixamorig:RightHandIndex1')!;+ const grip = q.normalize({ w: 0.8, x: 0.5, y: 0.2, z: 0.1 });+ const clip = (s.world.get(finger, Transform) as TransformData).rotation;+ registerFingerPose('test-curl', { joints: { 'mixamorig:RightHandIndex1': grip } });+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ s.world.update(g.e, GripProfile, (p: { mainPose: string }) => { p.mainPose = 'test-curl'; });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, weight: 0.5, supportWeight: 0 });+ await s.tick(2);+ const want = slerpQuat(clip, grip, 0.5);+ const got = (s.world.get(finger, Transform) as TransformData).rotation;+ expect(angle(got, want)).toBeLessThan(1e-5);+ expect(gripHolderStatus(s.app, b.root)!.amount).toBe(0.5);+ });++ it('captures a hand\'s fingers as plain JSON that puts them back', async () => {+ const s = scene();+ const b = body(s.world);+ const hand = b.arms.Right!.hand;+ const named = (n: string) => s.world.getEntitiesWithComponents([Name]).find((e) => (s.world.get(e, Name) as { value: string }).value === n)!;+ s.world.update(named('mixamorig:RightHandMiddle2'), Transform, (t: TransformData) => { t.rotation = q.normalize({ w: 0.7, x: 0.7, y: 0, z: 0 }); });+ const pose = JSON.parse(JSON.stringify(captureFingerPose(s.world, hand)));+ expect(Object.keys(pose.joints)).toContain('mixamorig:RightHandMiddle2');+ expect(Object.keys(pose.joints).length).toBe(20);+ registerFingerPose('kept', pose);+ s.world.update(named('mixamorig:RightHandMiddle2'), Transform, (t: TransformData) => { t.rotation = I; });+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ s.world.update(g.e, GripProfile, (p: { mainPose: string }) => { p.mainPose = 'kept'; });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, supportWeight: 0 });+ await s.tick(2);+ expect(angle((s.world.get(named('mixamorig:RightHandMiddle2'), Transform) as TransformData).rotation, q.normalize({ w: 0.7, x: 0.7, y: 0, z: 0 }))).toBeLessThan(1e-5);+ });++ it('hands a grip pose by name to the hand\'s GripPose, by the hold\'s weight', async () => {+ const s = scene();+ const b = body(s.world);+ const g = gun(s.world, { x: 3, y: 0, z: 0 });+ s.world.update(g.e, GripProfile, (p: { mainPose: string; supportPose: string }) => { p.mainPose = 'pistol'; p.supportPose = 'support'; });+ holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });+ await s.tick(3);+ const grip = s.world.get(b.root, (await import('../src/animation/gripPose')).GripPose) as { rightPose: string; leftPose: string; rightWeight: number };+ expect(grip.rightPose).toBe('pistol');+ expect(grip.leftPose).toBe('support');+ expect(grip.rightWeight).toBe(1);+ });+});diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 84f67eef1..c845066f4 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -125,6 +125,8 @@ const DISPOSITION = {Planet: ['owed', 'authored by a game today (star-neighbors, a round planet from its own generator); an example that registers a planet provider is owed'],MeshInstances: ['derived', 'the foliage and world generation systems write it, one entity a kind and part of a cell; its places are data a system computes, not something a scene authors'],ParticleCollider: ['owed', 'no example has a GPU emitter bouncing off a shape yet; the particle-gpu scenes are where the first one goes'],+ GripProfile: ['owed', 'no example holds an object in its two hands yet; a character with a rifle is where the first one goes'],+ GripHolder: ['owed', 'no example holds an object in its two hands yet; a character with a rifle is where the first one goes'],GripPose: ['owed', 'no example holds a tool in a named pose yet; a character with something in its hand is where the first one goes'],VoxelTerrain: ['owed', 'no example digs in a volume yet; a small mine is where the first one goes'],RoadDecal: ['owed', 'no example lays a road over a terrain yet; wilds is where the first one goes'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9973bcefd..13fa4f29c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4234,6 +4234,8 @@ export const NOTED = {{"note": "Particles and plain sprites in a Canvas paint by their place in its tree."},"fix(text): stopping lets go of the labels the engine holds, so the next Play cannot draw them on other entities":{"note": "Labels no longer come back as black boxes after a change between Plays."},+ "feat(animation): a character holds an object by anchors on it, the arms bent to them in one order that cannot loop":+ {"note": "Holding an object in both hands."},"feat(animation): a rig's hands held in a named pose that fits any skeleton":{"note": "Hands that hold things."},"fix(animation): a held hand's thumb reaches for the fingers and lies over them, instead of standing out from the palm":