threedog 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +4 -4
- package/core/assets/Animator.js +66 -12
- package/core/assets/ik.js +144 -18
- package/core/assets/maskLayer.js +377 -0
- package/core/assets/rootMotion.js +148 -0
- package/core/audio/Audio.js +100 -4
- package/core/base/errorCodes.js +6 -369
- package/core/base/errorCodesModules.js +378 -0
- package/core/engine/Engine.js +8 -5
- package/core/engine/Loading.js +8 -4
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +15 -4
- package/core/engine/lifecycle.js +1 -0
- package/core/engine/loop.js +23 -3
- package/core/engine/moduleSlots.js +3 -7
- package/core/engine/modules.js +30 -58
- package/core/engine/startup.js +3 -3
- package/core/input/Input.js +7 -3
- package/core/input/inputContext.js +3 -2
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/DebugOverrides.js +1 -1
- package/core/inspect/Describe.js +7 -2
- package/core/inspect/describeRender.js +4 -1
- package/core/inspect/describeText.js +2 -2
- package/core/inspect/metadata.generated.js +380 -74
- package/core/inspect/pictureMenu.js +2 -0
- package/core/inspect/pictureWriters.js +4 -3
- package/core/ops/Ops.js +9 -3
- package/core/ops/actor.js +10 -0
- package/core/ops/control.js +17 -6
- package/core/ops/holds.js +1 -1
- package/core/ops/opsAtomic.js +6 -1
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/owned.js +37 -11
- package/core/ops/sharedPoint.js +5 -1
- package/core/ops/stacks.js +30 -7
- package/core/saves/Saves.js +0 -2
- package/core/saves/saveApply.js +7 -7
- package/core/saves/session.js +6 -3
- package/core/saves/stateReplace.js +71 -41
- package/core/scene/Rays.js +74 -26
- package/core/scene/canvasBox.js +9 -0
- package/core/scene/gameLights.js +19 -11
- package/core/scene/sceneDelta.js +8 -4
- package/core/scene/sceneMethods.js +2 -1
- package/core/stream/chunkStream.js +21 -0
- package/core/stream/dirtyWatch.js +37 -0
- package/core/time/skip.js +9 -6
- package/core/time/time.js +72 -18
- package/docs/AI.md +22 -21
- package/docs/API.md +5 -4
- package/docs/CODEMAP.md +16 -10
- package/docs/COMMANDS.md +5 -5
- package/docs/CONVENTIONS.md +9 -25
- package/docs/api/ambience.md +1 -0
- package/docs/api/assets.md +10 -3
- package/docs/api/audio.md +5 -3
- package/docs/api/decals.md +16 -0
- package/docs/api/engine.md +1 -0
- package/docs/api/tools.md +3 -1
- package/docs/api/water.md +3 -0
- package/docs/recipes/09-materials-lights-models.md +15 -1
- package/docs/recipes/13-animation.md +51 -10
- package/docs/recipes/16-dev-bridge.md +4 -4
- package/docs/recipes/31-audio.md +15 -9
- package/docs/recipes/34-environment-lighting.md +11 -1
- package/docs/recipes/44-water-weather-hooks.md +1 -0
- package/examples/action/.threedog/content-index.json +1 -0
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/plain-picture/.threedog/content-index.json +1 -0
- package/examples/rc2d/.threedog/content-index.json +1 -0
- package/examples/styletest/.threedog/content-index.json +1 -0
- package/examples/techniques/outlines-and-rim/main.js +1 -1
- package/examples/techniques/procedural-surface/main.js +1 -1
- package/examples/techniques/stylized-shading/main.js +1 -1
- package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
- package/examples/world/.threedog/content-index.json +1 -0
- package/index.d.ts +6 -2
- package/index.js +3 -2
- package/llms.txt +11 -10
- package/modules/ambience/Ambience.js +97 -15
- package/modules/camera/common.js +18 -12
- package/modules/characters/Character.js +30 -3
- package/modules/characters/NPC.js +2 -5
- package/modules/characters/astar.js +45 -14
- package/modules/characters/movers/rapier.js +53 -41
- package/modules/characters/movers/simple.js +37 -24
- package/modules/characters/npcView.js +2 -2
- package/modules/characters/pathAsync.js +3 -3
- package/modules/collision/contract.js +2 -2
- package/modules/content/index.js +3 -0
- package/modules/content/models.js +11 -4
- package/modules/content/templates.js +11 -11
- package/modules/debug/DebugPanel.js +1 -0
- package/modules/decals/Decals.js +393 -0
- package/modules/decals/index.js +1 -0
- package/modules/gameplay/Container.js +2 -0
- package/modules/gameplay/Containers.js +17 -3
- package/modules/gameplay/Dialogue.js +1 -1
- package/modules/gameplay/Interactions.js +7 -6
- package/modules/gameplay/Inventory.js +5 -1
- package/modules/gameplay/Quests.js +4 -3
- package/modules/gameplay/inventoryOps.js +2 -2
- package/modules/gameplay/pickups.js +32 -12
- package/modules/gameplay/questSave.js +2 -2
- package/modules/grid/index.js +8 -2
- package/modules/hud/index.js +1 -1
- package/modules/level/heightfield.js +1 -0
- package/modules/level/index.js +3 -2
- package/modules/level/nodes.js +2 -1
- package/modules/lights/index.js +27 -4
- package/modules/lights/slots.js +33 -16
- package/modules/nav/contract.js +4 -4
- package/modules/nav/index.js +6 -2
- package/modules/net/Client.js +24 -11
- package/modules/net/Host.js +73 -20
- package/modules/net/index.js +33 -21
- package/modules/net/sync.js +38 -8
- package/modules/net/transports.js +7 -3
- package/modules/particles/Particles.js +11 -4
- package/modules/particles/contract.js +6 -6
- package/modules/particles/effect.js +0 -1
- package/modules/rigid/RigidBodies.js +69 -57
- package/modules/rigid/Vehicles.js +8 -7
- package/modules/rigid/ragdoll.js +4 -6
- package/modules/rigid/rapierCompat.js +90 -0
- package/modules/rigid/sync.js +2 -5
- package/modules/settings/Settings.js +10 -4
- package/modules/sky/Sky.js +10 -2
- package/modules/sky/environment.js +29 -13
- package/modules/sky/frame.js +2 -2
- package/modules/sky/shader.js +5 -2
- package/modules/sky/skyModule.js +2 -2
- package/modules/swarm/Swarm.js +3 -2
- package/modules/swarm/grid.js +12 -7
- package/modules/terrain/ChunkManager.js +16 -26
- package/modules/triggers/index.js +5 -6
- package/modules/vegetation/draw.js +62 -26
- package/modules/vegetation/groundChunks.js +8 -22
- package/modules/water/Water.js +152 -24
- package/modules/water/surface.js +43 -20
- package/modules/weather/weatherDraw.js +4 -1
- package/modules/world/World.js +21 -2
- package/modules/world/index.js +5 -0
- package/modules/world/persist.js +1 -0
- package/modules/world/records.js +3 -1
- package/modules/world/sim.js +3 -2
- package/modules/world/simFar.js +4 -2
- package/modules/world/state.js +7 -1
- package/package.json +2 -2
- package/presets.js +30 -0
- package/render/PostFX.js +24 -17
- package/render/backend.js +72 -31
- package/render/cascades.js +25 -14
- package/render/cascades.tsl.js +32 -21
- package/render/fogLook.js +2 -1
- package/render/fx/detail.tsl.js +3 -0
- package/render/fx/library.tsl.js +1 -1
- package/render/fx/particles.tsl.js +4 -18
- package/render/fx/pcss.tsl.js +2 -2
- package/render/fx/postWebGPU.tsl.js +47 -25
- package/render/fx/sky.tsl.js +6 -18
- package/render/fx/uniforms.tsl.js +16 -0
- package/render/fx/water.tsl.js +24 -5
- package/render/fxNumbers.js +2 -0
- package/render/impostor.tsl.js +10 -6
- package/render/lights.js +6 -6
- package/render/occlusion.js +17 -6
- package/render/patches.js +40 -28
- package/render/postWebGL.js +6 -4
- package/render/reflectionProbes.js +302 -0
- package/render/shaderErrors.js +18 -8
- package/render/shadowCache.tsl.js +10 -5
- package/render/shadows.js +70 -49
- package/render/threeCompat.js +166 -0
- package/types/core.d.ts +33 -3
- package/types/gameplay.d.ts +80 -0
- package/types/generated/core/audio/Audio.d.ts +18 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +7 -3
- package/types/generated/core/saves/session.d.ts +4 -1
- package/types/generated/modules/ambience/Ambience.d.ts +6 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
- package/types/generated/modules/grid/index.d.ts +27 -3
- package/types/generated/modules/net/index.d.ts +8 -3
- package/types/generated/modules/sky/Sky.d.ts +1 -0
- package/types/generated/modules/water/Water.d.ts +15 -0
- package/types/generated/modules/world/index.d.ts +5 -0
- package/types/generated/render/patches.d.ts +5 -0
- package/types/physics.d.ts +66 -9
- package/types/tsl.d.ts +2 -0
- package/types/world.d.ts +2 -0
- package/ui/Parts.js +3 -2
- package/docs/MIGRATING-0.7.md +0 -39
- package/docs/MIGRATING-0.8.md +0 -171
- package/modules/rigid/refresh.js +0 -10
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,42 @@
|
|
|
2
2
|
|
|
3
3
|
What changed in each version and how a game upgrades.
|
|
4
4
|
|
|
5
|
+
## Unreleased
|
|
6
|
+
|
|
7
|
+
## 2.3.0 (2026-11-26)
|
|
8
|
+
|
|
9
|
+
Upgrading from 2.2: nothing to change.
|
|
10
|
+
|
|
11
|
+
- Added: commercial 3D character animation suite: bone-mask layered blending (`anim.addLayer({ mask: 'upper' | 'lower' | bones, states })`), 8-directional 2D blend spaces (`blend2d` on `AnimatorState` with automatic local `moveX`/`moveZ` on `Character` and `presets.animation`), two-bone limb/hand IK (`anim.addLimb({ limb, bones, target, pole, alignRotation })`), slope ankle alignment on `anim.addFeet({ alignSlope, maxTilt, footOffset })` and spine-weighted `anim.addAim({ weights })`
|
|
12
|
+
- Added: conforming surface decals module (`decals()` -> `engine.decals`: `define`, `add`, `remove`, `count`, `material` plus `presets.decals`) projecting onto curved meshes, moving objects and heightfield terrain with ring-buffer eviction and lifetime fade-out
|
|
13
|
+
- Added: local PMREM reflection probes (`engine.addReflectionProbe({ bounds, position, resolution, include })` -> `{ texture, box, position, bake(), addTarget(), remove() }`) with nested-zone selection, dynamic indoor/outdoor target tracking, `describe().render.reflectionProbes`, picture menu entry and `debug.view('reflectionProbes')`
|
|
14
|
+
- Added: interactive water ripples (`engine.water.ripple(position, { strength, speed, duration })`, `water({ ripples })`, `waterRipple` in `threedog/tsl`) with automatic character wading wakes and raindrop rings across both WebGL and WebGPU
|
|
15
|
+
- Changed: upgraded starter `picture/` template and placeholder lighting defaults (3-cascade CSM on terrain worlds, warm ground-bounce hemisphere fill, smooth PBR specular water with depth color and crest foam, atmospheric sun corona and gently drifting sky clouds, refined surface roughness and GTAO)
|
|
16
|
+
- Added: deterministic skeletal root motion (`rootMotion` on `assets.animate` / state definitions and `anim.rootDelta(state, fromT, toT, opts)`) paired with exact `{ dx, dz, dy }` displacement steps on `control.take`
|
|
17
|
+
- Added: bus low-pass filter handles via `audio.filter(cutoff, { fade })` (exposed on `audio.info` as `filters`), declarative acoustic zone `filter` rules on `ambience` (`ambience.stop`), and `writeMcpConfigs` multi-IDE MCP scaffolding (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) plus bilingual `threedog how` search with inline API signatures
|
|
18
|
+
- Added: `cloneMaterial(material)` exported from `threedog` to clone three.js materials while preserving engine shader patches and custom hooks
|
|
19
|
+
- Added: `load(data, ctx)` / `afterLoad(engine, ctx)` replacement context now exposes bound helpers (`ctx.loadLevel`, `ctx.loadContent`, `ctx.loadSave`, `ctx.loadSession`, `ctx.newGame`, `ctx.quit`) alongside legacy `{ turn }` forwarding; `StateReplace` detects missing `{ turn }` synchronously in dev
|
|
20
|
+
- Changed: unified `ctx.feeds('interactions', ...)` across NPCs, templates, pickups and vehicles (removing per-frame polling); extracted `rapierCompat.js` and `threeCompat.js`; consolidated `patches.js` material state; added reference counting to `world.pauseSimulation()`; hardened `net` reconnect cleanup, schema-aware actor-id mapping and positive-number validation
|
|
21
|
+
- Fixed: `ops.undo` now returns `{ ok: true, revision }` on success (matching `ops.run` / `ops.can`) and bumps `ops.revision` before stamping a failed result
|
|
22
|
+
- Fixed: `session.load(slot, { turn })` now accepts `{ turn }` like `session.newGame`, `session.quit` and `saves.load`
|
|
23
|
+
- Fixed: failed / disabled / blocked non-critical modules with `isReady()` no longer stall `start()` or `loading.view().done`; `stacks` load preserves active non-saved (`system` / `settings` / `debug`) entries; `stacks.changed()` / `showValue` handle functions and circular objects; same-frame taps no longer leak across input context switches; `engine.camera` setter guards 0×0 canvases; `engine.skip` stops immediately on `dispose()`; `owned.at` records `time.tick`; `runState` tolerates `null` freeze values; `input.rebind` validates key names
|
|
24
|
+
|
|
25
|
+
## 2.2.2 (2026-11-19)
|
|
26
|
+
|
|
27
|
+
Upgrading from 2.2.1: nothing to change.
|
|
28
|
+
|
|
29
|
+
- Fixed: `engine.step()` follows a changed viewport (canvas, camera and the UI root) even when no frame was drawn since, so a frozen or stepped page reads the new size on its next step; `engine.renderOnce()` resets `renderer.info`, so draw-call and triangle counts no longer add up across calls
|
|
30
|
+
- Changed (tools): an unknown option on a dev-bridge command says the working form (`errors latest 3`, `state key=value`, `step 2`, `hold <action> <seconds>`, `describe <path>`); `step` on a title screen says how to leave it (`state play=1`, or `--page "/?play"`); `snap` waits for loading to finish, as `shot` does, before it captures
|
|
31
|
+
- Changed (tools): `check` reminds when a game calls three's `bumpMap(` (rule R40): for a height computed in the shader use `detailBump` from `threedog/tsl`; `bumpMap` needs a texture
|
|
32
|
+
- Docs: recipe 16 §2a shows how to hold an action across `threedog snap`, and to step once after changing the viewport on a headless page
|
|
33
|
+
|
|
34
|
+
## 2.2.1 (2026-11-19)
|
|
35
|
+
|
|
36
|
+
Upgrading from 2.2.0: install `@threedog/tools@2.2.1` (the other packages only move with it). Nothing else changes.
|
|
37
|
+
|
|
38
|
+
- Fixed (tools): the published 2.2.0 tools package left out its `expect/` folder, so `threedog check`, `shot`, `test` and `expect` crashed on start after `npm install`. A test now packs every package and fails when shipped code imports a file the package leaves out
|
|
39
|
+
- Fixed (tools): two kinds of plain JS that TypeScript cannot follow were `✗` errors and failed `check`; they are now `!` reminders: a member read on a value whose type inference lost (`never`, as three's TSL declarations give for some `vec2(…).add(uniform(…))`), and an array literal passed where a fixed pair is declared (`repeat = [1, 1]` into a `[number, number]` option)
|
|
40
|
+
|
|
5
41
|
## 2.2.0 (2026-11-19)
|
|
6
42
|
|
|
7
43
|
Upgrading from 2.1: a game changes code only if it uses one of these. `engine.settings.open()` / `close()` / `toggle()` / `isOpen()` become `engine.ui.open('settings')` / `ui.close('settings')` / `ui.isOpen('settings')`, and an input binding on context `win-settings` moves to `ui-settings`. `engine.ui.open` / `close` with a name that is not a full-screen part now throws (fix the name). `engine.mod(point, { id })` on a point that is not per record throws (drop the id, or define the point `{ per: 'optional' }`). `engine.post.add` throws `post-effect` on an unknown key or a wrong type in the definition. Your own CSS that layered over the title screen by z-index: the title is now at 22 (was 80), and the layers are the `--threedog-z-*` variables. Tools: `--no-build` needs one earlier build of the same kind on this machine, and a `threedog test` spec's timeout starts when the engine is up (nothing to change: specs only get more time).
|
package/README.md
CHANGED
|
@@ -5,14 +5,14 @@ A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, a
|
|
|
5
5
|
## Start here
|
|
6
6
|
One way to start a game, in an empty folder (the same for a person and for an AI agent):
|
|
7
7
|
```sh
|
|
8
|
-
npm install threedog
|
|
9
|
-
npm install -D @threedog/tools
|
|
8
|
+
npm install threedog three@~0.187.0
|
|
9
|
+
npm install -D @threedog/tools # the threedog commands: init, shot, check, how, dev, play, test
|
|
10
10
|
npx playwright install chromium # once per machine: the headless browser behind shot, play and test
|
|
11
|
-
npx threedog init # writes the game (main.js, picture/, content/) and
|
|
11
|
+
npx threedog init # writes the game (main.js, picture/, content/) and AGENTS.md / CLAUDE.md; never overwrites a file
|
|
12
12
|
npm install
|
|
13
13
|
npx threedog play # runs the game and reports it (--stop ends it); npm run dev opens it for a person
|
|
14
14
|
```
|
|
15
|
-
Then read the new `CLAUDE.md
|
|
15
|
+
Then read the new `AGENTS.md` (or `CLAUDE.md`): it lists what the engine already has, the loop (`threedog play`, `threedog shot`, `threedog check`), the picture recipes (60 judge the picture, 62 picture code) and `@threedog/post-effects` (bloom, AO, color grading). `npx threedog how "<task words>"` finds everything else.
|
|
16
16
|
|
|
17
17
|
`init` flags: `--open-world` (generated ground, sky, follow camera and a player; it adds `@threedog/terrain-noise`), `--pixel`, `--scene-only`, `--webgl` (WebGL and GLSL instead of WebGPU and TSL). The default is a blank scene with a camera and a neutral, correctly lit starting picture in `picture/` (gray surfaces, white sun, soft shadows, AO, light bloom). It also writes `.mcp.json`, so Claude Code opened in the folder starts the threedog MCP server by itself.
|
|
18
18
|
`npx threedog` comes with this package and runs the commands of `@threedog/tools`; without that package installed it prints the line to install it. To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. This README describes threedog 1.x (from 0.x read `docs/MIGRATING-1.0.md`).
|
package/core/assets/Animator.js
CHANGED
|
@@ -19,12 +19,14 @@ import * as THREE from 'three';
|
|
|
19
19
|
import { warnOnce, warnMissing, missingText } from '../base/validate.js';
|
|
20
20
|
import { readParams, keysSchema } from '../base/params.js';
|
|
21
21
|
import { isOptions } from '../base/util.js';
|
|
22
|
-
import { addAim, addFeet, ikRestore, ikRun, ikClear } from './ik.js';
|
|
22
|
+
import { addAim, addFeet, addLimb, ikRestore, ikRun, ikClear } from './ik.js';
|
|
23
|
+
import { createMaskLayer, computeBlend2D } from './maskLayer.js';
|
|
24
|
+
import { initRootMotion, pinRootBone, rootDelta as sampleRootDelta } from './rootMotion.js';
|
|
23
25
|
const GO_KEYS = ['fade'];
|
|
24
26
|
|
|
25
27
|
// Config keys: a typo (loops: false, state: {...}) would silently play the wrong thing, so both levels are checked like any other options
|
|
26
|
-
const CONFIG_KEYS = ['fade', 'states', 'transitions', 'params'];
|
|
27
|
-
const STATE_KEYS = ['clip', 'blend', 'param', 'sync', 'loop', 'then', 'lock', 'timing'];
|
|
28
|
+
const CONFIG_KEYS = ['fade', 'states', 'transitions', 'params', 'rootMotion'];
|
|
29
|
+
const STATE_KEYS = ['clip', 'blend', 'blend2d', 'param', 'params', 'sync', 'loop', 'then', 'lock', 'timing', 'rootMotion'];
|
|
28
30
|
|
|
29
31
|
/**
|
|
30
32
|
* Find a clip by exact name, else by the part after the last '|' ('Idle' finds 'CharacterArmature|Idle').
|
|
@@ -43,7 +45,7 @@ export class Animator {
|
|
|
43
45
|
constructor(engine, root, config = {}, mappedIn = null) {
|
|
44
46
|
// config is the code's options merged over the manifest mapping, so name both places a typo can be in
|
|
45
47
|
readParams(mappedIn ? `assets.animate() / ${mappedIn.label}` : 'assets.animate()', keysSchema(CONFIG_KEYS), config);
|
|
46
|
-
const { fade = 0.25, states = {}, transitions = {}, params = {} } = config;
|
|
48
|
+
const { fade = 0.25, states = {}, transitions = {}, params = {}, rootMotion } = config;
|
|
47
49
|
this.engine = engine;
|
|
48
50
|
this._mappedIn = mappedIn;
|
|
49
51
|
this.root = root;
|
|
@@ -51,6 +53,9 @@ export class Animator {
|
|
|
51
53
|
this.states = states;
|
|
52
54
|
this.transitions = transitions;
|
|
53
55
|
this.params = { speed: 0, ...params };
|
|
56
|
+
/** Root motion default for states (false / omitted = off; true = auto root/hips bone; string = bone name; { bone?, y? }) */
|
|
57
|
+
this.rootMotion = rootMotion;
|
|
58
|
+
/** @internal root-motion bone/track cache (rootMotion.js) */ this._rm = null;
|
|
54
59
|
this.mixer = new THREE.AnimationMixer(root);
|
|
55
60
|
this.clips = root.animations;
|
|
56
61
|
this.actions = new Map(); // clip name (as written in the state) -> three.js AnimationAction
|
|
@@ -64,6 +69,7 @@ export class Animator {
|
|
|
64
69
|
this._hook = null;
|
|
65
70
|
/** @internal the time channel's scale for this model, () => number; a Character sets it (useModel.js). null: engine time as it is */
|
|
66
71
|
this._rate = null;
|
|
72
|
+
this._maskLayers = []; // masked animation layers (maskLayer.js), blended after base mixer and before IK
|
|
67
73
|
this._ik = []; // IK layers (ik.js), run after the mixer in the order added
|
|
68
74
|
this._ikPose = new Map(); // bone IK writes -> { q, p, n }: its pose before IK, put back before the next mixer update
|
|
69
75
|
/** @internal ground height for addFeet, (x, z, y) => y; a Character hands over its own (platforms, only while grounded) */
|
|
@@ -72,6 +78,7 @@ export class Animator {
|
|
|
72
78
|
this._standing = () => true;
|
|
73
79
|
if (this.hasClips) {
|
|
74
80
|
this._check();
|
|
81
|
+
initRootMotion(this);
|
|
75
82
|
this.mixer.addEventListener('finished', ev => this._finished(ev.action));
|
|
76
83
|
this._needHook();
|
|
77
84
|
}
|
|
@@ -93,7 +100,8 @@ export class Animator {
|
|
|
93
100
|
_problems() {
|
|
94
101
|
const names = [...new Set(this.clips.map(c => short(c.name)))], out = [];
|
|
95
102
|
for (const [st, def] of Object.entries(this.states)) {
|
|
96
|
-
|
|
103
|
+
const clips = def.blend2d ? def.blend2d.map(b => b.clip) : def.blend ? def.blend.map(b => b.clip) : [def.clip];
|
|
104
|
+
for (const clip of clips) {
|
|
97
105
|
if (!findClip(this.clips, clip)) out.push(`assets.animate(): state "${st}" maps to a missing clip. ${missingText('clip', clip, names)}. Fix the clip name in ${this._where(st)}, or remove the state`);
|
|
98
106
|
}
|
|
99
107
|
if (def.then && !this.states[def.then]) out.push(`assets.animate(): ${this._where(st)}.then. ${missingText('animState', def.then, Object.keys(this.states))}`);
|
|
@@ -148,6 +156,18 @@ export class Animator {
|
|
|
148
156
|
* @returns {{ set(opts: { reach?: number, far?: number, speed?: number, weight?: number, fade?: number, ground?: Function }): any, remove(): void, describe(): { kind: string, bones: string[], weight: number } }}
|
|
149
157
|
*/
|
|
150
158
|
addFeet(opts) { return addFeet(this, opts); }
|
|
159
|
+
/**
|
|
160
|
+
* Two-bone limb IK (hands reaching for weapons/doors/ledges, or custom legs): bends [upper, mid, end] toward `target` with optional `pole` and `alignRotation`.
|
|
161
|
+
* Pass `limb: 'leftArm' | 'rightArm' | 'leftLeg' | 'rightLeg'` for auto-detection or `bones: ['UpperArm.R', 'LowerArm.R', 'Hand.R']`.
|
|
162
|
+
* @example const grip = anim.addLimb({ limb: 'leftArm', target: foregrip, alignRotation: true });
|
|
163
|
+
*/
|
|
164
|
+
addLimb(opts) { return addLimb(this, opts); }
|
|
165
|
+
/**
|
|
166
|
+
* Bone-mask animation layer (e.g. `mask: 'upper'` to swing a sword or aim a rifle while the legs keep running/strafing).
|
|
167
|
+
* Returns `{ name, state, go(state | null), action(name), sync(state | null, t), set({ weight, fade }), describe(), remove() }`.
|
|
168
|
+
* @example const upper = anim.addLayer({ mask: 'upper', states: { slash: { clip: 'Sword_Slash', loop: false } } });
|
|
169
|
+
*/
|
|
170
|
+
addLayer(opts) { return createMaskLayer(this, findClip, opts); }
|
|
151
171
|
|
|
152
172
|
/** Set a parameter for blend trees (e.g. speed). */
|
|
153
173
|
set(param, v) { this.params[param] = v; return this; }
|
|
@@ -170,7 +190,8 @@ export class Animator {
|
|
|
170
190
|
if (!this.hasClips) return null; // static model: nothing to play, nothing to warn about
|
|
171
191
|
const def = this.states[state];
|
|
172
192
|
if (!def) { warnMissing('animState', state, Object.keys(this.states)); return null; }
|
|
173
|
-
const
|
|
193
|
+
const clipList = def.blend2d ? def.blend2d.map(b => b.clip) : def.blend ? def.blend.map(b => b.clip) : [def.clip];
|
|
194
|
+
const actions = clipList.map(clip => ({ a: this._action(clip), clip }));
|
|
174
195
|
if (actions.some(x => !x.a)) return null; // missing clip: already reported by _check
|
|
175
196
|
const f = this._fadeFor(this.state, state, fade), rate = f > 0 ? 1 / f : 1e9; // not Infinity: 0 * Infinity (dt 0 behind a full still) is NaN
|
|
176
197
|
for (const l of this._layers) { l.target = 0; l.rate = rate; }
|
|
@@ -260,10 +281,24 @@ export class Animator {
|
|
|
260
281
|
if (next) this.go(next);
|
|
261
282
|
}
|
|
262
283
|
|
|
284
|
+
/**
|
|
285
|
+
* Deterministic root displacement over gameplay interval [fromT, toT], sampled directly from the root / hips position VectorKeyframeTrack
|
|
286
|
+
* (independent of render frames and mixer.update). Handles one-shot clamping, looping wrap-around, and state timing.
|
|
287
|
+
* Default returns world-space { x, y, z } rotated by opts?.yaw ?? this.root.rotation.y; pass { local: true } for bone-local delta or { out } to reuse an object.
|
|
288
|
+
* @param {string} state
|
|
289
|
+
* @param {number} fromT
|
|
290
|
+
* @param {number} toT
|
|
291
|
+
* @param {{ yaw?: number, local?: boolean, y?: boolean, out?: { x: number, y: number, z: number } }} [opts]
|
|
292
|
+
* @returns {{ x: number, y: number, z: number }}
|
|
293
|
+
* @example const d = anim.rootDelta('roll', prevT, t, { yaw: ch.facing });
|
|
294
|
+
*/
|
|
295
|
+
rootDelta(state, fromT, toT, opts) { return sampleRootDelta(this, findClip, state, fromT, toT, opts); }
|
|
296
|
+
|
|
263
297
|
/** @internal Per frame: advance fades, split blend-tree weights by parameter, sync stride, then advance the mixer (the engine calls it). */
|
|
264
298
|
update(dt) {
|
|
265
299
|
if (this._held) { this.afterPose?.(dt); return; } // physics owns the bones (a ragdoll): the mixer writes nothing, attachments still follow the pose
|
|
266
300
|
if (this._ik.length) ikRestore(this);
|
|
301
|
+
for (let i = this._maskLayers.length - 1; i >= 0; i--) this._maskLayers[i].restore();
|
|
267
302
|
let j = 0; // fade, stop faded-out layers and compact in place (no arrays per frame)
|
|
268
303
|
for (const l of this._layers) {
|
|
269
304
|
if (l.w < l.target) l.w = Math.min(l.target, l.w + dt * l.rate);
|
|
@@ -274,6 +309,8 @@ export class Animator {
|
|
|
274
309
|
this._layers.length = j;
|
|
275
310
|
this._weights();
|
|
276
311
|
this.mixer.update(dt);
|
|
312
|
+
if (this._rm || this.rootMotion) pinRootBone(this);
|
|
313
|
+
for (const ml of this._maskLayers) ml.step(dt);
|
|
277
314
|
if (this._ik.length) ikRun(this, dt); // IK is the pose's last layer, before anything is attached to it
|
|
278
315
|
this.afterPose?.(dt); // Character.onPose callbacks (the pose is final here)
|
|
279
316
|
}
|
|
@@ -283,14 +320,25 @@ export class Animator {
|
|
|
283
320
|
let total = 0;
|
|
284
321
|
for (const l of this._layers) { total += l.w; for (const x of l.actions) x.a.setEffectiveWeight(0); }
|
|
285
322
|
for (const l of this._layers) {
|
|
286
|
-
const lw = total > 0 ? l.w / total : 0
|
|
287
|
-
|
|
288
|
-
|
|
323
|
+
const lw = total > 0 ? l.w / total : 0;
|
|
324
|
+
const bw = l.def.blend2d ? computeBlend2D(l.def, this.params) : l.def.blend ? this._blend(l.def) : ONE;
|
|
325
|
+
let dur = 0, moveShare = 0;
|
|
326
|
+
for (let i = 0; i < l.actions.length; i++) {
|
|
327
|
+
const pt = l.def.blend2d?.[i];
|
|
328
|
+
if (pt && pt.at[0] === 0 && pt.at[1] === 0) continue;
|
|
329
|
+
dur += bw[i] * l.actions[i].a.getClip().duration;
|
|
330
|
+
moveShare += bw[i];
|
|
331
|
+
}
|
|
332
|
+
const meanDur = moveShare > 1e-4 ? dur / moveShare : 0;
|
|
289
333
|
for (let i = 0; i < l.actions.length; i++) {
|
|
290
334
|
const { a } = l.actions[i];
|
|
291
335
|
a.setEffectiveWeight(a.weight + lw * bw[i]); // added: two layers on one clip each give their share
|
|
292
|
-
|
|
293
|
-
|
|
336
|
+
const pt = l.def.blend2d?.[i];
|
|
337
|
+
const isIdleCenter = pt && pt.at[0] === 0 && pt.at[1] === 0;
|
|
338
|
+
// blended actions share one beat (walk, strafe and run footfalls land together)
|
|
339
|
+
if ((l.def.blend || l.def.blend2d) && l.def.sync !== false && meanDur > 0 && !isIdleCenter) {
|
|
340
|
+
a.setEffectiveTimeScale(a.getClip().duration / meanDur);
|
|
341
|
+
}
|
|
294
342
|
}
|
|
295
343
|
}
|
|
296
344
|
}
|
|
@@ -312,10 +360,16 @@ export class Animator {
|
|
|
312
360
|
const total = this._layers.reduce((s, x) => s + x.w, 0) || 1; // shown as shares, like the mixer weights (they sum to 1)
|
|
313
361
|
return { state: this.state, clip: l?.actions[0].clip ?? null, time: a ? r3(a.time) : 0, progress: dur ? r3(a.time / dur) : 0,
|
|
314
362
|
driven: !!l?.driven, ...(l?.driven && { t: r3(this._t) }), weights: Object.fromEntries(this._layers.map(x => [x.name, r3(x.w / total)])),
|
|
363
|
+
...(this._maskLayers.length && { layers: this._maskLayers.map(m => m.handle.describe()) }),
|
|
315
364
|
...(this._ik.length && { ik: this._ik.map(x => ({ kind: x.kind, bones: x.names, weight: r3(x.w) })) }) };
|
|
316
365
|
}
|
|
317
366
|
/** Call when no longer needed to stop per-frame updates. */
|
|
318
|
-
dispose() {
|
|
367
|
+
dispose() {
|
|
368
|
+
this._dropHook();
|
|
369
|
+
for (const m of [...this._maskLayers]) m.handle.remove();
|
|
370
|
+
ikClear(this);
|
|
371
|
+
this.mixer.stopAllAction();
|
|
372
|
+
}
|
|
319
373
|
}
|
|
320
374
|
|
|
321
375
|
export const handRolled = [{ kind: 'animation', docRef: 'recipes/13-animation.md §5', seen: 'an AnimationMixer of its own', use: 'engine.assets.animate(model, { states }): states, crossfades, sync with game time and pause', quiet: /\bassets\.animate\b/, code: /\bnew\s+(?:THREE\.)?AnimationMixer\s*\(|\bmixer\.update\s*\(/i }];
|
package/core/assets/ik.js
CHANGED
|
@@ -12,8 +12,9 @@ import { readParams, keysSchema } from '../base/params.js';
|
|
|
12
12
|
import { codedError } from '../base/errorHints.js';
|
|
13
13
|
import { missingText } from '../base/validate.js';
|
|
14
14
|
|
|
15
|
-
const AIM_KEYS = ['bones', 'target', 'limit', 'speed', 'weight', 'fade', 'forward'];
|
|
16
|
-
const FEET_KEYS = ['legs', 'hips', 'reach', 'far', 'speed', 'weight', 'fade', 'ground'];
|
|
15
|
+
const AIM_KEYS = ['bones', 'target', 'limit', 'speed', 'weight', 'fade', 'forward', 'weights'];
|
|
16
|
+
const FEET_KEYS = ['legs', 'hips', 'reach', 'far', 'speed', 'weight', 'fade', 'ground', 'alignSlope', 'maxTilt', 'footOffset'];
|
|
17
|
+
const LIMB_KEYS = ['bones', 'limb', 'target', 'pole', 'alignRotation', 'weight', 'fade', 'speed'];
|
|
17
18
|
const UP = new THREE.Vector3(0, 1, 0), Z = new THREE.Vector3(0, 0, 1), DEG = Math.PI / 180, EPS = 1e-6;
|
|
18
19
|
const _a = new THREE.Vector3(), _b = new THREE.Vector3(), _c = new THREE.Vector3(), _t = new THREE.Vector3(), _d = new THREE.Vector3(), _e = new THREE.Vector3();
|
|
19
20
|
const _ax0 = new THREE.Vector3(), _ax1 = new THREE.Vector3(), _p = new THREE.Vector3();
|
|
@@ -114,10 +115,18 @@ function aimLayer(anim, opts) {
|
|
|
114
115
|
if (!names.length) throw codedError('engine-misuse', `${where}: bones is the bone that turns ('Head') or a chain from the body out (['Neck', 'Head']), got ${JSON.stringify(o.bones)}`);
|
|
115
116
|
const bones = names.map(n => boneOf(anim.root, n, where)), tip = bones[bones.length - 1];
|
|
116
117
|
if (o.forward !== undefined && !(Array.isArray(o.forward) && o.forward.length === 3 && o.forward.every(Number.isFinite))) throw codedError('engine-misuse', `${where}: forward is the last bone's own axis it looks along, [x, y, z]; leave it out to read it from the bind pose`);
|
|
118
|
+
let boneShares = null;
|
|
119
|
+
if (o.weights !== undefined) {
|
|
120
|
+
if (!Array.isArray(o.weights) || o.weights.length !== bones.length || o.weights.some(w => !(Number.isFinite(w) && w >= 0))) {
|
|
121
|
+
throw codedError('engine-misuse', `${where}: weights must be an array of ${bones.length} non-negative numbers matching bones`);
|
|
122
|
+
}
|
|
123
|
+
const wSum = o.weights.reduce((s, x) => s + x, 0) || 1;
|
|
124
|
+
boneShares = o.weights.map(x => x / wSum);
|
|
125
|
+
}
|
|
117
126
|
const l = { kind: 'aim', names, bones, writes: bones, w: 0, target: null, limit: 70, speed: 360, weight: 1, fade: 0.25, cur: null,
|
|
118
127
|
fwd: o.forward ? new THREE.Vector3().fromArray(o.forward).normalize() : bindForward(anim.root, tip) };
|
|
119
128
|
l.set = p => {
|
|
120
|
-
const s = readParams('aim.set()', keysSchema(AIM_KEYS.filter(k => k !== 'bones' && k !== 'forward')), p);
|
|
129
|
+
const s = readParams('aim.set()', keysSchema(AIM_KEYS.filter(k => k !== 'bones' && k !== 'forward' && k !== 'weights')), p);
|
|
121
130
|
if (p && 'target' in p) { checkTarget('aim.set()', s.target); l.target = s.target; } // the raw options: set({ weight }) keeps the target
|
|
122
131
|
for (const k of ['limit', 'speed', 'weight', 'fade']) if (s[k] !== undefined) { nonNeg('aim.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
|
|
123
132
|
};
|
|
@@ -132,11 +141,13 @@ function aimLayer(anim, opts) {
|
|
|
132
141
|
if (T) turnToward(l.cur, turnToward(_b.copy(D0), T.sub(tip.getWorldPosition(_d)).normalize(), l.limit * DEG), l.speed * DEG * dt);
|
|
133
142
|
l.cur.copy(turnToward(_t.copy(D0), l.cur, l.limit * DEG)); // the body turned since: still inside the limit
|
|
134
143
|
const F = turnToward(_d.copy(D0), l.cur, angle(D0, l.cur) * l.w); // the weight blends from the animation
|
|
135
|
-
|
|
144
|
+
let remShare = 1;
|
|
136
145
|
for (let i = 0; i < bones.length; i++) {
|
|
137
146
|
const b = bones[i], now = _e.copy(l.fwd).applyQuaternion(wq(tip, _q)).normalize();
|
|
138
147
|
_q1.setFromUnitVectors(now, F);
|
|
139
|
-
|
|
148
|
+
const frac = boneShares ? (remShare > 1e-6 ? Math.min(1, boneShares[i] / remShare) : 1) : 1 / (bones.length - i);
|
|
149
|
+
if (boneShares) remShare -= boneShares[i];
|
|
150
|
+
_q2.identity().slerp(_q1, frac);
|
|
140
151
|
setWq(b, _q2.multiply(wq(b, _q3)));
|
|
141
152
|
b.updateWorldMatrix(false, true);
|
|
142
153
|
}
|
|
@@ -173,38 +184,58 @@ function findLegs(root, legs, where) {
|
|
|
173
184
|
|
|
174
185
|
function feetLayer(anim, opts) {
|
|
175
186
|
const where = 'anim.addFeet()', o = readParams(where, keysSchema(FEET_KEYS), opts);
|
|
176
|
-
const legs = findLegs(anim.root, o.legs, where).map(([upper, lower, foot]) => ({
|
|
187
|
+
const legs = findLegs(anim.root, o.legs, where).map(([upper, lower, foot]) => ({
|
|
188
|
+
upper, lower, foot, off: 0, cl: new THREE.Vector3(), fp: new THREE.Vector3(), fq: new THREE.Quaternion(), nrm: new THREE.Vector3(0, 1, 0),
|
|
189
|
+
}));
|
|
177
190
|
// the hips lower the whole body when one foot must reach down: the leg tops' common parent unless named
|
|
178
191
|
const hips = o.hips ? boneOf(anim.root, o.hips, where) : legs.every(l => l.upper.parent === legs[0].upper.parent) ? legs[0].upper.parent : null;
|
|
179
192
|
const writes = legs.flatMap(g => [g.upper, g.lower, g.foot]).concat(hips && hips !== anim.root ? [hips] : []);
|
|
180
193
|
const l = { kind: 'feet', names: legs.map(g => g.foot.name), writes, legs, hips: writes.includes(hips) ? hips : null, w: 0, drop: 0,
|
|
181
|
-
reach: 0.5, far: 30, speed: 12, weight: 1, fade: 0.25, ground: o.ground ?? null };
|
|
194
|
+
reach: 0.5, far: 30, speed: 12, weight: 1, fade: 0.25, alignSlope: true, maxTilt: 35, footOffset: 0, ground: o.ground ?? null };
|
|
182
195
|
l.set = p => {
|
|
183
196
|
const s = readParams('feet.set()', keysSchema(FEET_KEYS.filter(k => k !== 'legs' && k !== 'hips')), p);
|
|
184
|
-
for (const k of ['reach', 'far', 'speed', 'weight', 'fade']) if (s[k] !== undefined) { nonNeg('feet.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
|
|
197
|
+
for (const k of ['reach', 'far', 'speed', 'weight', 'fade', 'maxTilt']) if (s[k] !== undefined) { nonNeg('feet.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
|
|
198
|
+
if (s.footOffset !== undefined) {
|
|
199
|
+
if (!Number.isFinite(s.footOffset)) throw codedError('engine-misuse', 'feet.set(): footOffset must be a finite number');
|
|
200
|
+
l.footOffset = s.footOffset;
|
|
201
|
+
}
|
|
202
|
+
if (s.alignSlope !== undefined) l.alignSlope = !!s.alignSlope;
|
|
185
203
|
if (s.ground !== undefined) {
|
|
186
204
|
if (typeof s.ground !== 'function') throw codedError('engine-misuse', `${where}: ground is (x, z, y) => height; leave it out to use the model's own ground (engine.surface, a Character's supports)`);
|
|
187
205
|
l.ground = s.ground;
|
|
188
206
|
}
|
|
189
207
|
};
|
|
190
|
-
l.set({ reach: o.reach, far: o.far, speed: o.speed, weight: o.weight, fade: o.fade, ground: o.ground });
|
|
208
|
+
l.set({ reach: o.reach, far: o.far, speed: o.speed, weight: o.weight, fade: o.fade, ground: o.ground, alignSlope: o.alignSlope, maxTilt: o.maxTilt, footOffset: o.footOffset });
|
|
191
209
|
// preallocated: this runs per character per frame (joint positions handed to twoBone must not be its own scratch vectors)
|
|
192
|
-
const pole = new THREE.Vector3(), rU = new THREE.Quaternion(), rM = new THREE.Quaternion(), ja = new THREE.Vector3(), jb = new THREE.Vector3(), jc = new THREE.Vector3(), jt = new THREE.Vector3();
|
|
210
|
+
const pole = new THREE.Vector3(), rU = new THREE.Quaternion(), rM = new THREE.Quaternion(), ja = new THREE.Vector3(), jb = new THREE.Vector3(), jc = new THREE.Vector3(), jt = new THREE.Vector3(), wantNrm = new THREE.Vector3();
|
|
193
211
|
l.run = dt => {
|
|
194
212
|
const root = anim.root, cam = anim.engine.camera, base = root.getWorldPosition(_b).y;
|
|
195
213
|
// off at once, before any ground query: hidden, far from the camera (nobody sees the feet), or not standing (a Character jumping or swimming);
|
|
196
214
|
// fading over the cached corrections would still bend legs in the air
|
|
197
|
-
if (!root.visible || (cam && cam.position.distanceTo(_b) > l.far) || !anim._standing()) {
|
|
215
|
+
if (!root.visible || (cam && cam.position.distanceTo(_b) > l.far) || !anim._standing()) {
|
|
216
|
+
l.w = 0; l.drop = 0; for (const g of legs) { g.off = 0; g.nrm.set(0, 1, 0); } return;
|
|
217
|
+
}
|
|
198
218
|
fadeWeight(l, l.weight, dt);
|
|
199
|
-
if (l.w <= 0) { l.drop = 0; for (const g of legs) g.off = 0; return; }
|
|
219
|
+
if (l.w <= 0) { l.drop = 0; for (const g of legs) { g.off = 0; g.nrm.set(0, 1, 0); } return; }
|
|
200
220
|
const ground = l.ground ?? anim._ground, k = dt > 0 ? 1 - Math.exp(-l.speed * dt) : 0;
|
|
201
221
|
let low = 0;
|
|
202
222
|
for (const g of legs) {
|
|
203
223
|
g.foot.getWorldPosition(g.fp); wq(g.foot, g.fq);
|
|
204
224
|
g.cl.copy(g.fp); g.lower.worldToLocal(g.cl); // the ankle rides with the lower leg, also when the foot bone hangs elsewhere
|
|
205
|
-
const
|
|
206
|
-
|
|
225
|
+
const h0 = ground(g.fp.x, g.fp.z, base);
|
|
226
|
+
const off = (Number.isFinite(h0) ? h0 + l.footOffset : base) - base;
|
|
227
|
+
const inReach = Number.isFinite(off) && Math.abs(off) <= l.reach;
|
|
228
|
+
g.off += ((inReach ? off : 0) - g.off) * k; // smoothed: an edge under the foot does not pop
|
|
207
229
|
low = Math.min(low, g.off);
|
|
230
|
+
if (l.alignSlope && inReach) {
|
|
231
|
+
const hx1 = ground(g.fp.x + 0.08, g.fp.z, base), hx0 = ground(g.fp.x - 0.08, g.fp.z, base);
|
|
232
|
+
const hz1 = ground(g.fp.x, g.fp.z + 0.08, base), hz0 = ground(g.fp.x, g.fp.z - 0.08, base);
|
|
233
|
+
const sx = Number.isFinite(hx1) && Number.isFinite(hx0) ? (hx1 - hx0) / 0.16 : 0;
|
|
234
|
+
const sz = Number.isFinite(hz1) && Number.isFinite(hz0) ? (hz1 - hz0) / 0.16 : 0;
|
|
235
|
+
// Reject vertical step/ledge drops so feet stay flat on stair treads instead of rolling over the riser
|
|
236
|
+
if (Math.hypot(sx, sz) <= 1.15) wantNrm.set(-sx, 1, -sz).normalize(); else wantNrm.set(0, 1, 0);
|
|
237
|
+
} else wantNrm.set(0, 1, 0);
|
|
238
|
+
g.nrm.lerp(wantNrm, k).normalize();
|
|
208
239
|
}
|
|
209
240
|
l.drop += (low - l.drop) * k;
|
|
210
241
|
if (l.hips && l.drop < 0) {
|
|
@@ -217,10 +248,104 @@ function feetLayer(anim, opts) {
|
|
|
217
248
|
twoBone(g.upper.getWorldPosition(ja), g.lower.getWorldPosition(jb), jc.copy(g.cl).applyMatrix4(g.lower.matrixWorld), jt, pole, rU, rM);
|
|
218
249
|
setWq(g.lower, rM.multiply(wq(g.lower, _q))); g.lower.updateWorldMatrix(false, false);
|
|
219
250
|
setWq(g.upper, rU.multiply(wq(g.upper, _q))); g.upper.updateWorldMatrix(false, true);
|
|
220
|
-
// the foot
|
|
251
|
+
// the foot sits on the new ankle, tilted onto sloped terrain within maxTilt
|
|
221
252
|
g.lower.localToWorld(_t.copy(g.cl));
|
|
222
|
-
g.foot.position.copy(g.foot.parent ? g.foot.parent.worldToLocal(_t) : _t);
|
|
253
|
+
g.foot.position.copy(g.foot.parent ? g.foot.parent.worldToLocal(_t) : _t);
|
|
254
|
+
if (l.alignSlope && g.nrm.y < 0.99999) {
|
|
255
|
+
turnToward(_d.copy(UP), g.nrm, l.maxTilt * DEG);
|
|
256
|
+
_q1.setFromUnitVectors(UP, _d);
|
|
257
|
+
_q2.identity().slerp(_q1, l.w).multiply(g.fq);
|
|
258
|
+
} else _q2.copy(g.fq);
|
|
259
|
+
setWq(g.foot, _q2); g.foot.updateWorldMatrix(false, true);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
return l;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const HAND = /hand|wrist/i, NOT_HAND = /finger|thumb|index|middle|ring|pinky|end|ik|target|pole/i, FOREARM = /lower.?arm|forearm|elbow/i;
|
|
266
|
+
|
|
267
|
+
function findLimbChain(root, bonesOpt, limbOpt, where) {
|
|
268
|
+
if (bonesOpt) {
|
|
269
|
+
if (!Array.isArray(bonesOpt) || bonesOpt.length !== 3) {
|
|
270
|
+
throw codedError('engine-misuse', `${where}: bones must be [upper, mid, end] bone names, e.g. ['UpperArm.R', 'LowerArm.R', 'Hand.R']`);
|
|
271
|
+
}
|
|
272
|
+
return { chain: bonesOpt.map(b => (b?.isObject3D ? b : boneOf(root, b, where))), isArm: !/leg|foot/i.test(String(bonesOpt[2]?.name ?? bonesOpt[2])), side: sideOf(String(bonesOpt[2]?.name ?? bonesOpt[2])) };
|
|
273
|
+
}
|
|
274
|
+
const presets = { leftArm: ['L', true], rightArm: ['R', true], leftLeg: ['L', false], rightLeg: ['R', false] };
|
|
275
|
+
const entry = presets[limbOpt];
|
|
276
|
+
if (!entry) throw codedError('engine-misuse', `${where}: pass bones: [upper, mid, end] or limb: 'leftArm' | 'rightArm' | 'leftLeg' | 'rightLeg'`);
|
|
277
|
+
const [side, isArm] = entry;
|
|
278
|
+
const bones = []; root.traverse(o => { if (o.isBone) bones.push(o); });
|
|
279
|
+
const endRe = isArm ? HAND : FOOT, skipRe = isArm ? NOT_HAND : NOT_FOOT, midRe = isArm ? FOREARM : KNEE;
|
|
280
|
+
const end = bones.find(b => endRe.test(b.name) && !skipRe.test(b.name) && sideOf(b.name) === side);
|
|
281
|
+
let mid = end?.parent, upper = mid?.parent;
|
|
282
|
+
if (end && (!mid?.isBone || BODY.test(mid.name) || !upper?.isBone)) {
|
|
283
|
+
mid = bones.find(b => midRe.test(b.name) && sideOf(b.name) === side);
|
|
284
|
+
upper = mid?.parent;
|
|
285
|
+
}
|
|
286
|
+
if (!end || !mid?.isBone || !upper?.isBone) {
|
|
287
|
+
throw codedError('engine-misuse', `${where}: could not auto-detect ${limbOpt} from skeleton (${bones.map(b => b.name).join(', ') || 'no bones'}); pass bones: ['<upper>', '<mid>', '<end>']`);
|
|
288
|
+
}
|
|
289
|
+
return { chain: [upper, mid, end], isArm, side };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function limbLayer(anim, opts) {
|
|
293
|
+
const where = 'anim.addLimb()', o = readParams(where, keysSchema(LIMB_KEYS), opts);
|
|
294
|
+
const { chain: [upper, mid, end], isArm, side } = findLimbChain(anim.root, o.bones, o.limb, where);
|
|
295
|
+
const writes = [upper, mid, end];
|
|
296
|
+
const l = { kind: 'limb', names: writes.map(b => b.name), writes, upper, mid, end, w: 0,
|
|
297
|
+
target: null, pole: null, alignRotation: false, weight: 1, fade: 0.2, speed: 0 };
|
|
298
|
+
l.set = p => {
|
|
299
|
+
const s = readParams('limb.set()', keysSchema(LIMB_KEYS.filter(k => k !== 'bones' && k !== 'limb')), p);
|
|
300
|
+
if (p && 'target' in p) { checkTarget('limb.set()', s.target); l.target = s.target; }
|
|
301
|
+
if (p && 'pole' in p) { checkTarget('limb.set()', s.pole); l.pole = s.pole; }
|
|
302
|
+
if (s.alignRotation !== undefined) l.alignRotation = s.alignRotation;
|
|
303
|
+
for (const k of ['weight', 'fade', 'speed']) if (s[k] !== undefined) { nonNeg('limb.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
|
|
304
|
+
};
|
|
305
|
+
l.set({ target: o.target, pole: o.pole, alignRotation: o.alignRotation, weight: o.weight, fade: o.fade, speed: o.speed });
|
|
306
|
+
const pole = new THREE.Vector3(), rU = new THREE.Quaternion(), rM = new THREE.Quaternion();
|
|
307
|
+
const ja = new THREE.Vector3(), jb = new THREE.Vector3(), jc = new THREE.Vector3(), jt = new THREE.Vector3();
|
|
308
|
+
const cl = new THREE.Vector3(), eq = new THREE.Quaternion(), curT = new THREE.Vector3();
|
|
309
|
+
let hasCur = false;
|
|
310
|
+
l.run = dt => {
|
|
311
|
+
const T = targetAt(l.target, _c);
|
|
312
|
+
fadeWeight(l, T ? l.weight : 0, dt);
|
|
313
|
+
if (l.w <= 0) { hasCur = false; return; }
|
|
314
|
+
if (T) {
|
|
315
|
+
if (!hasCur || l.speed <= 0) { curT.copy(T); hasCur = true; }
|
|
316
|
+
else curT.lerp(T, dt > 0 ? 1 - Math.exp(-l.speed * dt) : 1);
|
|
317
|
+
}
|
|
318
|
+
if (!hasCur) return;
|
|
319
|
+
end.getWorldPosition(jc); wq(end, eq);
|
|
320
|
+
cl.copy(jc); mid.worldToLocal(cl);
|
|
321
|
+
upper.getWorldPosition(ja); mid.getWorldPosition(jb);
|
|
322
|
+
const P = targetAt(l.pole, pole);
|
|
323
|
+
if (P) pole.sub(ja).normalize();
|
|
324
|
+
else {
|
|
325
|
+
// Arms bend elbows back-and-out; legs bend knees forward
|
|
326
|
+
pole.set(isArm ? (side === 'L' ? -0.35 : 0.35) : 0, 0, isArm ? -1 : 1).normalize().applyQuaternion(wq(anim.root, _q));
|
|
327
|
+
}
|
|
328
|
+
jt.copy(curT);
|
|
329
|
+
twoBone(ja, jb, jc, jt, pole, rU, rM);
|
|
330
|
+
_q1.identity().slerp(rM, l.w);
|
|
331
|
+
_q2.identity().slerp(rU, l.w);
|
|
332
|
+
setWq(mid, _q1.multiply(wq(mid, _q))); mid.updateWorldMatrix(false, false);
|
|
333
|
+
setWq(upper, _q2.multiply(wq(upper, _q))); upper.updateWorldMatrix(false, true);
|
|
334
|
+
if (end.parent !== mid) {
|
|
335
|
+
mid.localToWorld(_t.copy(cl));
|
|
336
|
+
end.position.copy(end.parent ? end.parent.worldToLocal(_t) : _t);
|
|
337
|
+
}
|
|
338
|
+
if (l.alignRotation) {
|
|
339
|
+
let goalQ = null;
|
|
340
|
+
if (l.alignRotation === true && l.target?.isObject3D) goalQ = wq(l.target, _q1);
|
|
341
|
+
else if (l.alignRotation?.isQuaternion) goalQ = _q1.copy(l.alignRotation);
|
|
342
|
+
else if (Array.isArray(l.alignRotation) && l.alignRotation.length === 4) goalQ = _q1.fromArray(l.alignRotation);
|
|
343
|
+
if (goalQ) { _q2.copy(eq).slerp(goalQ, l.w); setWq(end, _q2); }
|
|
344
|
+
else if (end.parent !== mid) setWq(end, eq);
|
|
345
|
+
} else if (end.parent !== mid) {
|
|
346
|
+
setWq(end, eq);
|
|
223
347
|
}
|
|
348
|
+
end.updateWorldMatrix(false, true);
|
|
224
349
|
};
|
|
225
350
|
return l;
|
|
226
351
|
}
|
|
@@ -240,15 +365,16 @@ function addLayer(anim, l) {
|
|
|
240
365
|
if (!anim._held) ikRestore(anim);
|
|
241
366
|
for (const b of l.writes) { const s = anim._ikPose.get(b); if (--s.n <= 0) anim._ikPose.delete(b); }
|
|
242
367
|
if (!anim._held && anim._ik.length) solve(anim, 0);
|
|
243
|
-
if (!anim._ik.length && !anim.hasClips) anim._dropHook(); // a clip-less model needed the frame hook only for IK
|
|
368
|
+
if (!anim._ik.length && !anim._maskLayers?.length && !anim.hasClips) anim._dropHook(); // a clip-less model needed the frame hook only for IK
|
|
244
369
|
},
|
|
245
370
|
describe() { return { kind: l.kind, bones: l.names, weight: Math.round(l.w * 1000) / 1000 }; },
|
|
246
371
|
};
|
|
247
372
|
}
|
|
248
373
|
|
|
249
|
-
/** @internal anim.addAim / anim.addFeet */
|
|
374
|
+
/** @internal anim.addAim / anim.addFeet / anim.addLimb */
|
|
250
375
|
export const addAim = (anim, opts) => addLayer(anim, aimLayer(anim, opts));
|
|
251
376
|
export const addFeet = (anim, opts) => addLayer(anim, feetLayer(anim, opts));
|
|
377
|
+
export const addLimb = (anim, opts) => addLayer(anim, limbLayer(anim, opts));
|
|
252
378
|
/** @internal Before the mixer: the pose before last frame's IK (a bone no clip keys keeps its own pose, not last frame's turn) */
|
|
253
379
|
export function ikRestore(anim) { for (const [b, s] of anim._ikPose) { b.quaternion.copy(s.q); b.position.copy(s.p); } }
|
|
254
380
|
/** @internal After the mixer: remember this pose, then run each layer in the order added */
|