@zephyr3d/scene 0.7.1 → 0.8.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/dist/animation/animation.js +0 -18
- package/dist/animation/animation.js.map +1 -1
- package/dist/animation/animationset.js +2 -2
- package/dist/animation/animationset.js.map +1 -1
- package/dist/animation/ik/ccd_solver.js +372 -0
- package/dist/animation/ik/ccd_solver.js.map +1 -0
- package/dist/animation/ik/fabrik_solver.js +399 -0
- package/dist/animation/ik/fabrik_solver.js.map +1 -0
- package/dist/animation/ik/ik_angle_constraint.js +181 -0
- package/dist/animation/ik/ik_angle_constraint.js.map +1 -0
- package/dist/animation/ik/ik_chain.js +163 -0
- package/dist/animation/ik/ik_chain.js.map +1 -0
- package/dist/animation/ik/ik_chain_builder.js +68 -0
- package/dist/animation/ik/ik_chain_builder.js.map +1 -0
- package/dist/animation/ik/ik_constraint.js +25 -0
- package/dist/animation/ik/ik_constraint.js.map +1 -0
- package/dist/animation/ik/ik_pole_constraint.js +123 -0
- package/dist/animation/ik/ik_pole_constraint.js.map +1 -0
- package/dist/animation/ik/ik_solver.js +48 -0
- package/dist/animation/ik/ik_solver.js.map +1 -0
- package/dist/animation/ik/ik_track.js +96 -0
- package/dist/animation/ik/ik_track.js.map +1 -0
- package/dist/animation/ik/ik_utils.js +270 -0
- package/dist/animation/ik/ik_utils.js.map +1 -0
- package/dist/animation/ik/two_bone_ik_solver.js +332 -0
- package/dist/animation/ik/two_bone_ik_solver.js.map +1 -0
- package/dist/animation/ik_modifier.js +61 -0
- package/dist/animation/ik_modifier.js.map +1 -0
- package/dist/animation/ik_postprocessor.js +71 -0
- package/dist/animation/ik_postprocessor.js.map +1 -0
- package/dist/animation/manual_transform_processor.js +156 -0
- package/dist/animation/manual_transform_processor.js.map +1 -0
- package/dist/animation/skeleton.js +55 -51
- package/dist/animation/skeleton.js.map +1 -1
- package/dist/animation/skeleton_modifier.js +38 -0
- package/dist/animation/skeleton_modifier.js.map +1 -0
- package/dist/animation/skeleton_postprocessor.js +50 -0
- package/dist/animation/skeleton_postprocessor.js.map +1 -0
- package/dist/animation/spring/multi_chain_spring_system.js +503 -0
- package/dist/animation/spring/multi_chain_spring_system.js.map +1 -0
- package/dist/animation/spring/spring_chain.js +103 -0
- package/dist/animation/spring/spring_chain.js.map +1 -0
- package/dist/animation/spring/spring_collider.js +247 -0
- package/dist/animation/spring/spring_collider.js.map +1 -0
- package/dist/animation/spring/spring_constraint.js +21 -0
- package/dist/animation/spring/spring_constraint.js.map +1 -0
- package/dist/animation/spring/spring_particle.js +20 -0
- package/dist/animation/spring/spring_particle.js.map +1 -0
- package/dist/animation/spring/spring_system.js +526 -0
- package/dist/animation/spring/spring_system.js.map +1 -0
- package/dist/animation/spring_modifier.js +45 -0
- package/dist/animation/spring_modifier.js.map +1 -0
- package/dist/animation/spring_postprocessor.js +54 -0
- package/dist/animation/spring_postprocessor.js.map +1 -0
- package/dist/app/screen.js +1 -1
- package/dist/app/screen.js.map +1 -1
- package/dist/asset/model.js +8 -4
- package/dist/asset/model.js.map +1 -1
- package/dist/camera/perspectivecamera.js +3 -3
- package/dist/camera/perspectivecamera.js.map +1 -1
- package/dist/index.d.ts +1385 -4
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -1
- package/dist/material/mixins/lightmodel/blinnphong.js +66 -4
- package/dist/material/mixins/lightmodel/blinnphong.js.map +1 -1
- package/dist/material/shader/helper.js +5 -3
- package/dist/material/shader/helper.js.map +1 -1
- package/dist/scene/mesh.js +15 -23
- package/dist/scene/mesh.js.map +1 -1
- package/dist/utility/serialization/scene/animation.js +21 -20
- package/dist/utility/serialization/scene/animation.js.map +1 -1
- package/dist/utility/serialization/scene/material.js +62 -0
- package/dist/utility/serialization/scene/material.js.map +1 -1
- package/package.json +2 -2
|
@@ -168,24 +168,6 @@ import { Disposable } from '@zephyr3d/base';
|
|
|
168
168
|
track.reset(target);
|
|
169
169
|
return this;
|
|
170
170
|
}
|
|
171
|
-
/** @internal */ resample(frames, callback) {
|
|
172
|
-
for(let frame = 0; frame <= frames; frame++){
|
|
173
|
-
const t = frame / this.timeDuration;
|
|
174
|
-
for (const [k, v] of this.tracks){
|
|
175
|
-
for (const track of v){
|
|
176
|
-
const state = track.calculateState(k, t);
|
|
177
|
-
track.applyState(k, state);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
for (const sk of this.skeletons){
|
|
181
|
-
const skeleton = this._animationSet.model.findSkeletonById(sk);
|
|
182
|
-
if (skeleton) {
|
|
183
|
-
skeleton.computeJoints();
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
callback(frame);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
171
|
}
|
|
190
172
|
|
|
191
173
|
export { AnimationClip };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"animation.js","sources":["../../src/animation/animation.ts"],"sourcesContent":["import { Disposable } from '@zephyr3d/base';\r\nimport type { AnimationSet } from './animationset';\r\nimport type { AnimationTrack } from './animationtrack';\r\n\r\n/**\r\n * Animation clip\r\n *\r\n * Represents a named animation composed of multiple tracks targeting various objects/properties,\r\n * with an overall duration, weight, and optional auto-play behavior. Tracks may target different\r\n * objects and are grouped by a per-target array. Skeletons used by this clip are tracked for\r\n * lifecycle and application during playback.\r\n *\r\n * Typical workflow:\r\n * - Create a clip via `AnimationSet.createAnimation(name)`.\r\n * - Add one or more `AnimationTrack`s via `addTrack(target, track)`.\r\n * - Optionally register skeletons via `addSkeleton(...)`.\r\n * - Start playback through the owning `AnimationSet.playAnimation(name, options)`.\r\n *\r\n * @public\r\n */\r\nexport class AnimationClip extends Disposable {\r\n /** @internal */\r\n protected _name: string;\r\n /** @internal */\r\n protected _animationSet: AnimationSet;\r\n /** @internal */\r\n protected _embedded: boolean;\r\n /** @internal */\r\n protected _duration: number;\r\n /** @internal */\r\n protected _autoPlay: boolean;\r\n /** @internal */\r\n protected _tracks: Map<object, AnimationTrack[]>;\r\n protected _weight: number;\r\n /** @internal */\r\n protected _skeletons: Set<string>;\r\n /**\r\n * Creates an animation instance\r\n * @param name - Name of the animation\r\n * @param model - Parent node if this is a skeleton animation\r\n */\r\n constructor(name: string, animationSet: AnimationSet, embedded = false) {\r\n super();\r\n this._name = name;\r\n this._animationSet = animationSet;\r\n this._embedded = embedded;\r\n this._tracks = new Map();\r\n this._duration = 0;\r\n this._weight = 1;\r\n this._autoPlay = false;\r\n this._skeletons = new Set();\r\n }\r\n /**\r\n * Whether this clip is embedded (owned inline by its container/resource).\r\n */\r\n get embedded() {\r\n return this._embedded;\r\n }\r\n /**\r\n * The `AnimationSet` that owns this clip.\r\n */\r\n get animationSet() {\r\n return this._animationSet;\r\n }\r\n /**\r\n * Global blend weight for the clip.\r\n *\r\n * Used by the animation system when combining multiple active clips.\r\n */\r\n get weight() {\r\n return this._weight;\r\n }\r\n set weight(val: number) {\r\n this._weight = val;\r\n }\r\n /**\r\n * Whether this clip should start playing automatically when loaded/instantiated.\r\n */\r\n get autoPlay() {\r\n return this._autoPlay;\r\n }\r\n set autoPlay(val: boolean) {\r\n this._autoPlay = val;\r\n }\r\n /**\r\n * The unique name of this clip.\r\n */\r\n get name() {\r\n return this._name;\r\n }\r\n /**\r\n * All animation tracks grouped by target object.\r\n *\r\n * Key: target object; Value: list of `AnimationTrack`s affecting that target.\r\n */\r\n get tracks() {\r\n return this._tracks;\r\n }\r\n /**\r\n * All skeletons referenced by this clip.\r\n */\r\n get skeletons() {\r\n return this._skeletons;\r\n }\r\n set skeletons(val: Set<string>) {\r\n this._skeletons = val;\r\n }\r\n /**\r\n * Total time span of the clip in seconds.\r\n *\r\n * Automatically extended when adding tracks with longer duration.\r\n */\r\n get timeDuration() {\r\n return this._duration;\r\n }\r\n set timeDuration(val) {\r\n this._duration = val;\r\n }\r\n /**\r\n * Add a skeleton used by this clip.\r\n *\r\n * @param skeletonId - Persistent ID of Skeleton to register for this clip.\r\n */\r\n addSkeleton(skeletonId: string) {\r\n this._skeletons.add(skeletonId);\r\n }\r\n /**\r\n * Remove a specific track from this clip.\r\n *\r\n * Errors if the track does not belong to this clip. Does nothing if not found.\r\n *\r\n * @param track - The track instance to remove.\r\n * @returns This clip (for chaining).\r\n */\r\n deleteTrack(track: AnimationTrack) {\r\n if (track?.animation !== this) {\r\n console.error('Cannot delete animation track which is not belongs to THIS animation');\r\n }\r\n for (const k of this._tracks.keys()) {\r\n const tracks = this._tracks.get(k)!;\r\n const index = tracks.indexOf(track);\r\n if (index >= 0) {\r\n tracks.splice(index, 1);\r\n }\r\n }\r\n return this;\r\n }\r\n /**\r\n * Add a track to this clip for a specific target object.\r\n *\r\n * Constraints:\r\n * - The track must not already belong to another clip.\r\n * - Only one track with the same blendId may exist per target in a single clip.\r\n *\r\n * Side effects:\r\n * - Assigns this clip to `track.animation`.\r\n * - Extends `timeDuration` to cover the track duration if longer.\r\n * - Calls `track.reset(target)` to initialize the target state if needed.\r\n *\r\n * @param target - Target object controlled by the track.\r\n * @param track - Track to add.\r\n * @returns This clip (for chaining).\r\n */\r\n addTrack(target: object, track: AnimationTrack) {\r\n if (!track) {\r\n return this;\r\n }\r\n if (track.animation) {\r\n if (track.animation === this) {\r\n return this;\r\n } else {\r\n console.error('Track is already in another animation');\r\n return this;\r\n }\r\n }\r\n const blendId = track.getBlendId();\r\n const tracks = this._tracks.get(target);\r\n if (tracks && tracks.findIndex((track) => track.getBlendId() === blendId) >= 0) {\r\n console.error('Tracks with same BlendId could not be added to same animation');\r\n return this;\r\n }\r\n track.animation = this;\r\n let trackInfo = this._tracks.get(target);\r\n if (!trackInfo) {\r\n trackInfo = [];\r\n this._tracks.set(target, trackInfo);\r\n }\r\n trackInfo.push(track);\r\n this._duration = Math.max(this._duration, track.getDuration() ?? 0);\r\n track.reset(target);\r\n return this;\r\n }\r\n /** @internal */\r\n resample(frames: number, callback: (frame: number) => void) {\r\n for (let frame = 0; frame <= frames; frame++) {\r\n const t = frame / this.timeDuration;\r\n for (const [k, v] of this.tracks) {\r\n for (const track of v) {\r\n const state = track.calculateState(k, t);\r\n track.applyState(k, state);\r\n }\r\n }\r\n for (const sk of this.skeletons) {\r\n const skeleton = this._animationSet.model.findSkeletonById(sk);\r\n if (skeleton) {\r\n skeleton.computeJoints();\r\n }\r\n }\r\n callback(frame);\r\n }\r\n }\r\n}\r\n"],"names":["AnimationClip","Disposable","_weight","name","animationSet","embedded","_name","_animationSet","_embedded","_tracks","Map","_duration","_autoPlay","_skeletons","Set","weight","val","autoPlay","tracks","skeletons","timeDuration","addSkeleton","skeletonId","add","deleteTrack","track","animation","console","error","k","keys","get","index","indexOf","splice","addTrack","target","blendId","getBlendId","findIndex","trackInfo","set","push","Math","max","getDuration","reset","resample","frames","callback","frame","t","v","state","calculateState","applyState","sk","skeleton","model","findSkeletonById","computeJoints"],"mappings":";;AAIA;;;;;;;;;;;;;;;IAgBO,MAAMA,aAAsBC,SAAAA,UAAAA,CAAAA;qBAEjC,KAAwB;qBAExB,aAAsC;qBAEtC,SAA6B;qBAE7B,SAA4B;qBAE5B,SAA6B;qBAE7B,OAAiD;IACvCC,OAAgB;qBAE1B,UAAkC;AAClC;;;;AAIC,MACD,YAAYC,IAAY,EAAEC,YAA0B,EAAEC,QAAAA,GAAW,KAAK,CAAE;QACtE,KAAK,EAAA;QACL,IAAI,CAACC,KAAK,GAAGH,IAAAA;QACb,IAAI,CAACI,aAAa,GAAGH,YAAAA;QACrB,IAAI,CAACI,SAAS,GAAGH,QAAAA;QACjB,IAAI,CAACI,OAAO,GAAG,IAAIC,GAAAA,EAAAA;QACnB,IAAI,CAACC,SAAS,GAAG,CAAA;QACjB,IAAI,CAACT,OAAO,GAAG,CAAA;QACf,IAAI,CAACU,SAAS,GAAG,KAAA;QACjB,IAAI,CAACC,UAAU,GAAG,IAAIC,GAAAA,EAAAA;AACxB;AACA;;AAEC,MACD,IAAIT,QAAW,GAAA;QACb,OAAO,IAAI,CAACG,SAAS;AACvB;AACA;;AAEC,MACD,IAAIJ,YAAe,GAAA;QACjB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CAAAA;AACf,QAAA,IAAI,CAACd,SAAS,GAAGgC,IAAAA,CAAKC,GAAG,CAAC,IAAI,CAACjC,SAAS,EAAEc,KAAMoB,CAAAA,WAAW,EAAM,IAAA,CAAA,CAAA;AACjEpB,QAAAA,KAAAA,CAAMqB,KAAK,CAACV,MAAAA,CAAAA;AACZ,QAAA,OAAO,IAAI;AACb;AACA,qBACAW,QAAAA,CAASC,MAAc,EAAEC,QAAiC,EAAE;AAC1D,QAAA,IAAK,IAAIC,KAAAA,GAAQ,CAAGA,EAAAA,KAAAA,IAASF,QAAQE,KAAS,EAAA,CAAA;AAC5C,YAAA,MAAMC,CAAID,GAAAA,KAAAA,GAAQ,IAAI,CAAC9B,YAAY;YACnC,KAAK,MAAM,CAACS,CAAGuB,EAAAA,CAAAA,CAAE,IAAI,IAAI,CAAClC,MAAM,CAAE;gBAChC,KAAK,MAAMO,SAAS2B,CAAG,CAAA;AACrB,oBAAA,MAAMC,KAAQ5B,GAAAA,KAAAA,CAAM6B,cAAc,CAACzB,CAAGsB,EAAAA,CAAAA,CAAAA;oBACtC1B,KAAM8B,CAAAA,UAAU,CAAC1B,CAAGwB,EAAAA,KAAAA,CAAAA;AACtB;AACF;AACA,YAAA,KAAK,MAAMG,EAAAA,IAAM,IAAI,CAACrC,SAAS,CAAE;gBAC/B,MAAMsC,QAAAA,GAAW,IAAI,CAAClD,aAAa,CAACmD,KAAK,CAACC,gBAAgB,CAACH,EAAAA,CAAAA;AAC3D,gBAAA,IAAIC,QAAU,EAAA;AACZA,oBAAAA,QAAAA,CAASG,aAAa,EAAA;AACxB;AACF;YACAX,QAASC,CAAAA,KAAAA,CAAAA;AACX;AACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"animation.js","sources":["../../src/animation/animation.ts"],"sourcesContent":["import { Disposable } from '@zephyr3d/base';\r\nimport type { AnimationSet } from './animationset';\r\nimport type { AnimationTrack } from './animationtrack';\r\n\r\n/**\r\n * Animation clip\r\n *\r\n * Represents a named animation composed of multiple tracks targeting various objects/properties,\r\n * with an overall duration, weight, and optional auto-play behavior. Tracks may target different\r\n * objects and are grouped by a per-target array. Skeletons used by this clip are tracked for\r\n * lifecycle and application during playback.\r\n *\r\n * Typical workflow:\r\n * - Create a clip via `AnimationSet.createAnimation(name)`.\r\n * - Add one or more `AnimationTrack`s via `addTrack(target, track)`.\r\n * - Optionally register skeletons via `addSkeleton(...)`.\r\n * - Start playback through the owning `AnimationSet.playAnimation(name, options)`.\r\n *\r\n * @public\r\n */\r\nexport class AnimationClip extends Disposable {\r\n /** @internal */\r\n protected _name: string;\r\n /** @internal */\r\n protected _animationSet: AnimationSet;\r\n /** @internal */\r\n protected _embedded: boolean;\r\n /** @internal */\r\n protected _duration: number;\r\n /** @internal */\r\n protected _autoPlay: boolean;\r\n /** @internal */\r\n protected _tracks: Map<object, AnimationTrack[]>;\r\n protected _weight: number;\r\n /** @internal */\r\n protected _skeletons: Set<string>;\r\n /**\r\n * Creates an animation instance\r\n * @param name - Name of the animation\r\n * @param model - Parent node if this is a skeleton animation\r\n */\r\n constructor(name: string, animationSet: AnimationSet, embedded = false) {\r\n super();\r\n this._name = name;\r\n this._animationSet = animationSet;\r\n this._embedded = embedded;\r\n this._tracks = new Map();\r\n this._duration = 0;\r\n this._weight = 1;\r\n this._autoPlay = false;\r\n this._skeletons = new Set();\r\n }\r\n /**\r\n * Whether this clip is embedded (owned inline by its container/resource).\r\n */\r\n get embedded() {\r\n return this._embedded;\r\n }\r\n /**\r\n * The `AnimationSet` that owns this clip.\r\n */\r\n get animationSet() {\r\n return this._animationSet;\r\n }\r\n /**\r\n * Global blend weight for the clip.\r\n *\r\n * Used by the animation system when combining multiple active clips.\r\n */\r\n get weight() {\r\n return this._weight;\r\n }\r\n set weight(val: number) {\r\n this._weight = val;\r\n }\r\n /**\r\n * Whether this clip should start playing automatically when loaded/instantiated.\r\n */\r\n get autoPlay() {\r\n return this._autoPlay;\r\n }\r\n set autoPlay(val: boolean) {\r\n this._autoPlay = val;\r\n }\r\n /**\r\n * The unique name of this clip.\r\n */\r\n get name() {\r\n return this._name;\r\n }\r\n /**\r\n * All animation tracks grouped by target object.\r\n *\r\n * Key: target object; Value: list of `AnimationTrack`s affecting that target.\r\n */\r\n get tracks() {\r\n return this._tracks;\r\n }\r\n /**\r\n * All skeletons referenced by this clip.\r\n */\r\n get skeletons() {\r\n return this._skeletons;\r\n }\r\n set skeletons(val: Set<string>) {\r\n this._skeletons = val;\r\n }\r\n /**\r\n * Total time span of the clip in seconds.\r\n *\r\n * Automatically extended when adding tracks with longer duration.\r\n */\r\n get timeDuration() {\r\n return this._duration;\r\n }\r\n set timeDuration(val) {\r\n this._duration = val;\r\n }\r\n /**\r\n * Add a skeleton used by this clip.\r\n *\r\n * @param skeletonId - Persistent ID of Skeleton to register for this clip.\r\n */\r\n addSkeleton(skeletonId: string) {\r\n this._skeletons.add(skeletonId);\r\n }\r\n /**\r\n * Remove a specific track from this clip.\r\n *\r\n * Errors if the track does not belong to this clip. Does nothing if not found.\r\n *\r\n * @param track - The track instance to remove.\r\n * @returns This clip (for chaining).\r\n */\r\n deleteTrack(track: AnimationTrack) {\r\n if (track?.animation !== this) {\r\n console.error('Cannot delete animation track which is not belongs to THIS animation');\r\n }\r\n for (const k of this._tracks.keys()) {\r\n const tracks = this._tracks.get(k)!;\r\n const index = tracks.indexOf(track);\r\n if (index >= 0) {\r\n tracks.splice(index, 1);\r\n }\r\n }\r\n return this;\r\n }\r\n /**\r\n * Add a track to this clip for a specific target object.\r\n *\r\n * Constraints:\r\n * - The track must not already belong to another clip.\r\n * - Only one track with the same blendId may exist per target in a single clip.\r\n *\r\n * Side effects:\r\n * - Assigns this clip to `track.animation`.\r\n * - Extends `timeDuration` to cover the track duration if longer.\r\n * - Calls `track.reset(target)` to initialize the target state if needed.\r\n *\r\n * @param target - Target object controlled by the track.\r\n * @param track - Track to add.\r\n * @returns This clip (for chaining).\r\n */\r\n addTrack(target: object, track: AnimationTrack) {\r\n if (!track) {\r\n return this;\r\n }\r\n if (track.animation) {\r\n if (track.animation === this) {\r\n return this;\r\n } else {\r\n console.error('Track is already in another animation');\r\n return this;\r\n }\r\n }\r\n const blendId = track.getBlendId();\r\n const tracks = this._tracks.get(target);\r\n if (tracks && tracks.findIndex((track) => track.getBlendId() === blendId) >= 0) {\r\n console.error('Tracks with same BlendId could not be added to same animation');\r\n return this;\r\n }\r\n track.animation = this;\r\n let trackInfo = this._tracks.get(target);\r\n if (!trackInfo) {\r\n trackInfo = [];\r\n this._tracks.set(target, trackInfo);\r\n }\r\n trackInfo.push(track);\r\n this._duration = Math.max(this._duration, track.getDuration() ?? 0);\r\n track.reset(target);\r\n return this;\r\n }\r\n /*\r\n resample(frames: number, callback: (frame: number) => void) {\r\n for (let frame = 0; frame <= frames; frame++) {\r\n const t = frame / this.timeDuration;\r\n for (const [k, v] of this.tracks) {\r\n for (const track of v) {\r\n const state = track.calculateState(k, t);\r\n track.applyState(k, state);\r\n }\r\n }\r\n for (const sk of this.skeletons) {\r\n const skeleton = this._animationSet.model.findSkeletonById(sk);\r\n if (skeleton) {\r\n skeleton.computeJoints();\r\n }\r\n }\r\n callback(frame);\r\n }\r\n }\r\n */\r\n}\r\n"],"names":["AnimationClip","Disposable","_weight","name","animationSet","embedded","_name","_animationSet","_embedded","_tracks","Map","_duration","_autoPlay","_skeletons","Set","weight","val","autoPlay","tracks","skeletons","timeDuration","addSkeleton","skeletonId","add","deleteTrack","track","animation","console","error","k","keys","get","index","indexOf","splice","addTrack","target","blendId","getBlendId","findIndex","trackInfo","set","push","Math","max","getDuration","reset"],"mappings":";;AAIA;;;;;;;;;;;;;;;IAgBO,MAAMA,aAAsBC,SAAAA,UAAAA,CAAAA;qBAEjC,KAAwB;qBAExB,aAAsC;qBAEtC,SAA6B;qBAE7B,SAA4B;qBAE5B,SAA6B;qBAE7B,OAAiD;IACvCC,OAAgB;qBAE1B,UAAkC;AAClC;;;;AAIC,MACD,YAAYC,IAAY,EAAEC,YAA0B,EAAEC,QAA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ACd,QAAUA,KAAMa,CAAAA,UAAU,EAAOD,KAAAA,OAAAA,CAAAA,IAAY,CAAG,EAAA;AAC9EV,YAAAA,OAAAA,CAAQC,KAAK,CAAC,+DAAA,CAAA;AACd,YAAA,OAAO,IAAI;AACb;QACAH,KAAMC,CAAAA,SAAS,GAAG,IAAI;AACtB,QAAA,IAAIc,YAAY,IAAI,CAAC/B,OAAO,CAACsB,GAAG,CAACK,MAAAA,CAAAA;AACjC,QAAA,IAAI,CAACI,SAAW,EAAA;AACdA,YAAAA,SAAAA,GAAY,EAAE;AACd,YAAA,IAAI,CAAC/B,OAAO,CAACgC,GAAG,CAACL,MAAQI,EAAAA,SAAAA,CAAAA;AAC3B;AACAA,QAAAA,SAAAA,CAAUE,IAAI,CAACjB,KAAAA,CAAAA;AACf,QAAA,IAAI,CAACd,SAAS,GAAGgC,IAAAA,CAAKC,GAAG,CAAC,IAAI,CAACjC,SAAS,EAAEc,KAAMoB,CAAAA,WAAW,EAAM,IAAA,CAAA,CAAA;AACjEpB,QAAAA,KAAAA,CAAMqB,KAAK,CAACV,MAAAA,CAAAA;AACZ,QAAA,OAAO,IAAI;AACb;AAqBF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"animationset.js","sources":["../../src/animation/animationset.ts"],"sourcesContent":["import { weightedAverage, Disposable } from '@zephyr3d/base';\r\nimport type { DRef, IDisposable } from '@zephyr3d/base';\r\nimport type { SceneNode } from '../scene';\r\nimport { AnimationClip } from './animation';\r\nimport type { AnimationTrack } from './animationtrack';\r\nimport type { Skeleton } from './skeleton';\r\n\r\n/**\r\n * Options for playing an animation.\r\n *\r\n * Controls looping, playback speed (including reverse), and fade-in blending.\r\n * @public\r\n **/\r\nexport type PlayAnimationOptions = {\r\n /**\r\n * Number of loops to play.\r\n *\r\n * - 0: infinite looping (default).\r\n * - n \\> 0: play exactly n loops (each loop is one full duration of the clip).\r\n */\r\n repeat?: number;\r\n /**\r\n * Playback speed multiplier.\r\n *\r\n * - 1: normal speed (default).\r\n * - \\>1: faster; \\<1: slower.\r\n * - Negative values play the clip in reverse. The initial `currentTime` will be set to the end.\r\n */\r\n speedRatio?: number;\r\n /**\r\n * Fade-in duration in seconds.\r\n *\r\n * Interpolates the animation weight from 0 to the clip's configured weight over this time.\r\n * Use together with `stopAnimation(..., { fadeOut })` for smooth cross-fading.\r\n * Default is 0 (no fade-in).\r\n */\r\n fadeIn?: number;\r\n /**\r\n * Weight of the animation clip.\r\n *\r\n * Used during blending when multiple animations affect the same property.\r\n * Default is the clip's configured weight.\r\n */\r\n weight?: number;\r\n};\r\n\r\n/**\r\n * Options for stopping an animation.\r\n *\r\n * Allows a graceful fade-out instead of abrupt stop.\r\n * @public\r\n */\r\nexport type StopAnimationOptions = {\r\n /**\r\n * Fade-out duration in seconds.\r\n *\r\n * Interpolates the current animation weight down to 0 over this time.\r\n * Default is 0 (immediate stop).\r\n */\r\n fadeOut?: number;\r\n};\r\n\r\n/**\r\n * Animation set\r\n *\r\n * Manages a collection of named animation clips for a model and orchestrates:\r\n * - Playback state (time, loops, speed, weights, fade-in/out).\r\n * - Blending across multiple tracks targeting the same property via weighted averages.\r\n * - Skeleton usage and application for clips that drive skeletal animation.\r\n * - Active track registration and cleanup as clips start/stop.\r\n *\r\n * Usage:\r\n * - Create or retrieve `AnimationClip`s by name.\r\n * - Start playback with `playAnimation(name, options)`.\r\n * - Advance animation with `update(deltaSeconds)`.\r\n * - Optionally adjust weight while playing with `setAnimationWeight(name, weight)`.\r\n *\r\n * Lifetime:\r\n * - Disposing the set releases references to the model, clips, and clears active state.\r\n *\r\n * @public\r\n */\r\nexport class AnimationSet extends Disposable implements IDisposable {\r\n /** @internal */\r\n private _model: SceneNode;\r\n /** @internal */\r\n private _animations: Partial<Record<string, AnimationClip>>;\r\n /** @internal */\r\n private _skeletons: DRef<Skeleton>[];\r\n /** @internal */\r\n private readonly _activeTracks: Map<object, Map<unknown, AnimationTrack[]>>;\r\n /** @internal */\r\n private readonly _activeSkeletons: Map<Skeleton, number>;\r\n /** @internal */\r\n private readonly _activeAnimations: Map<\r\n AnimationClip,\r\n {\r\n currentTime: number;\r\n repeat: number;\r\n repeatCounter: number;\r\n weight: number;\r\n speedRatio: number;\r\n firstFrame: boolean;\r\n fadeIn: number;\r\n fadeOut: number;\r\n fadeOutStart: number;\r\n animateTime: number;\r\n }\r\n >;\r\n /**\r\n * Create an AnimationSet controlling the provided model.\r\n *\r\n * @param model - The SceneNode (model root) controlled by this animation set.\r\n */\r\n constructor(model: SceneNode) {\r\n super();\r\n this._model = model;\r\n this._animations = {};\r\n this._activeTracks = new Map();\r\n this._activeSkeletons = new Map();\r\n this._activeAnimations = new Map();\r\n this._skeletons = [];\r\n }\r\n /**\r\n * The model (SceneNode) controlled by this animation set.\r\n */\r\n get model() {\r\n return this._model;\r\n }\r\n /**\r\n * Number of animation clips registered in this set.\r\n */\r\n get numAnimations() {\r\n return Object.getOwnPropertyNames(this._animations).length;\r\n }\r\n /**\r\n * The skeletons used by animations in this set.\r\n */\r\n get skeletons() {\r\n return this._skeletons;\r\n }\r\n /**\r\n * Retrieve an animation clip by name.\r\n *\r\n * @param name - Name of the animation.\r\n * @returns The clip if present; otherwise null.\r\n */\r\n get(name: string) {\r\n return this._animations[name] ?? null;\r\n }\r\n /**\r\n * Create and register a new animation clip.\r\n *\r\n * @param name - Unique name for the animation clip.\r\n * @param embedded - Whether the clip is embedded/owned (implementation-specific). Default false.\r\n * @returns The created clip, or null if the name is empty or not unique.\r\n */\r\n createAnimation(name: string, embedded = false) {\r\n if (!name || this._animations[name]) {\r\n console.error('Animation must have unique name');\r\n return null;\r\n } else {\r\n const animation = new AnimationClip(name, this, embedded);\r\n this._animations[name] = animation;\r\n this._model.scene?.queueUpdateNode(this._model);\r\n return animation;\r\n }\r\n }\r\n /**\r\n * Delete and dispose an animation clip by name.\r\n *\r\n * - If the animation is currently playing, it is first stopped (immediately).\r\n *\r\n * @param name - Name of the animation to remove.\r\n */\r\n deleteAnimation(name: string) {\r\n const animation = this._animations[name];\r\n if (animation) {\r\n this.stopAnimation(name);\r\n delete this._animations[name];\r\n animation.dispose();\r\n }\r\n }\r\n /**\r\n * Get the list of all registered animation names.\r\n *\r\n * @returns An array of clip names.\r\n */\r\n getAnimationNames() {\r\n return Object.keys(this._animations);\r\n }\r\n /**\r\n * Advance and apply active animations.\r\n *\r\n * Responsibilities per call:\r\n * - Update time cursor for each active clip (respecting speedRatio and looping).\r\n * - Enforce repeat limits and apply fade-out termination if configured.\r\n * - For each animated target, blend active tracks (weighted by clip weight × fade-in × fade-out)\r\n * and apply the resulting state to the target.\r\n * - Apply all active skeletons to update skinning transforms.\r\n *\r\n * @param deltaInSeconds - Time step in seconds since last update.\r\n */\r\n update(deltaInSeconds: number) {\r\n this._activeAnimations.forEach((v, k) => {\r\n if (v.fadeOut > 0 && v.fadeOutStart < 0) {\r\n v.fadeOutStart = v.animateTime;\r\n }\r\n // Update animation time\r\n if (v.firstFrame) {\r\n v.firstFrame = false;\r\n } else {\r\n const timeAdvance = deltaInSeconds * v.speedRatio;\r\n v.currentTime += timeAdvance;\r\n v.animateTime += timeAdvance;\r\n if (v.currentTime > k.timeDuration) {\r\n v.repeatCounter++;\r\n v.currentTime = 0;\r\n } else if (v.currentTime < 0) {\r\n v.repeatCounter++;\r\n v.currentTime = k.timeDuration;\r\n }\r\n if (v.repeat !== 0 && v.repeatCounter >= v.repeat) {\r\n this.stopAnimation(k.name);\r\n } else if (v.fadeOut > 0) {\r\n if (v.animateTime - v.fadeOutStart >= v.fadeOut) {\r\n this.stopAnimation(k.name);\r\n }\r\n }\r\n }\r\n });\r\n // Update tracks\r\n this._activeTracks.forEach((v, k) => {\r\n v.forEach((alltracks) => {\r\n // Only deal with tracks which have not been removed\r\n const tracks = alltracks.filter(\r\n (track) => track.animation && this.isPlayingAnimation(track.animation.name)\r\n );\r\n if (tracks.length > 0) {\r\n const weights = tracks.map((track) => {\r\n const info = this._activeAnimations.get(track.animation!)!;\r\n const weight = info.weight;\r\n const fadeIn = info.fadeIn === 0 ? 1 : Math.min(1, info.animateTime / info.fadeIn);\r\n let fadeOut = 1;\r\n if (info.fadeOut !== 0) {\r\n fadeOut = 1 - (info.animateTime - info.fadeOutStart) / info.fadeOut;\r\n }\r\n return weight * fadeIn * fadeOut;\r\n });\r\n const states = tracks.map((track) => {\r\n const info = this._activeAnimations.get(track.animation!)!;\r\n const t = (info.currentTime / track.animation!.timeDuration) * track.getDuration();\r\n return track.calculateState(k, t);\r\n });\r\n const state = weightedAverage(weights, states, (a, b, t) => {\r\n return tracks[0].mixState(a, b, t);\r\n });\r\n tracks[0].applyState(k, state);\r\n }\r\n });\r\n });\r\n // Update skeletons\r\n this._activeSkeletons.forEach((v, k) => {\r\n k.apply();\r\n });\r\n }\r\n /**\r\n * Check whether an animation is currently playing.\r\n *\r\n * @param name - Optional animation name. If omitted, returns true if any animation is playing.\r\n * @returns True if playing; otherwise false.\r\n */\r\n isPlayingAnimation(name?: string) {\r\n if (name) {\r\n const animation = this._animations[name];\r\n return !!animation && this._activeAnimations.has(animation);\r\n }\r\n return this._activeAnimations.size > 0;\r\n }\r\n /**\r\n * Get an animation clip by name.\r\n *\r\n * Alias of `get(name)` returning a nullable type.\r\n *\r\n * @param name - Name of the animation.\r\n * @returns The clip if present; otherwise null.\r\n */\r\n getAnimationClip(name: string) {\r\n return this._animations[name] ?? null;\r\n }\r\n /**\r\n * Set the runtime blend weight for a currently playing animation.\r\n *\r\n * Has no effect if the clip is not active.\r\n *\r\n * @param name - Name of the playing animation.\r\n * @param weight - New weight value used during blending.\r\n */\r\n setAnimationWeight(name: string, weight: number) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n info.weight = weight;\r\n }\r\n }\r\n /**\r\n * Start (or update) playback of an animation clip.\r\n *\r\n * Behavior:\r\n * - If the clip is already playing, updates its fade-in (resets fade-out).\r\n * - Otherwise initializes playback state (repeat counter, speed, weight, initial time).\r\n * - Registers clip tracks and skeletons into the active sets for blending and application.\r\n *\r\n * @param name - Name of the animation to play.\r\n * @param options - Playback options (repeat, speedRatio, fadeIn).\r\n */\r\n playAnimation(name: string, options?: PlayAnimationOptions) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const fadeIn = Math.max(options?.fadeIn ?? 0, 0);\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n info.fadeOut = 0;\r\n info.fadeIn = fadeIn;\r\n } else {\r\n const repeat = options?.repeat ?? 0;\r\n const speedRatio = options?.speedRatio ?? 1;\r\n const weight = options?.weight ?? ani.weight ?? 1;\r\n this._activeAnimations.set(ani, {\r\n repeat,\r\n weight,\r\n speedRatio,\r\n fadeIn,\r\n fadeOut: 0,\r\n repeatCounter: 0,\r\n currentTime: speedRatio < 0 ? ani.timeDuration : 0,\r\n animateTime: 0,\r\n fadeOutStart: 0,\r\n firstFrame: true\r\n });\r\n ani.tracks?.forEach((v, k) => {\r\n let nodeTracks = this._activeTracks.get(k);\r\n if (!nodeTracks) {\r\n nodeTracks = new Map();\r\n this._activeTracks.set(k, nodeTracks);\r\n }\r\n for (const track of v) {\r\n const blendId = track.getBlendId();\r\n let blendedTracks = nodeTracks.get(blendId);\r\n if (!blendedTracks) {\r\n blendedTracks = [];\r\n nodeTracks.set(blendId, blendedTracks);\r\n }\r\n blendedTracks.push(track);\r\n }\r\n });\r\n ani.skeletons?.forEach((v, k) => {\r\n const skeleton = this.model.findSkeletonById(k);\r\n if (skeleton) {\r\n const refcount = this._activeSkeletons.get(skeleton);\r\n if (refcount) {\r\n this._activeSkeletons.set(skeleton, refcount + 1);\r\n } else {\r\n this._activeSkeletons.set(skeleton, 1);\r\n }\r\n skeleton.playing = true;\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Stop playback of an animation clip.\r\n *\r\n * Behavior:\r\n * - If `options.fadeOut > 0`, marks the clip for fade-out; actual removal occurs after fade completes.\r\n * - If `fadeOut` is 0 or omitted, immediately:\r\n * - Removes the clip from active animations.\r\n * - Unregisters its tracks from active track maps.\r\n * - Decrements skeleton reference counts; resets and removes skeletons when refcount reaches 0.\r\n *\r\n * @param name - Name of the animation to stop.\r\n * @param options - Optional fade-out configuration.\r\n */\r\n stopAnimation(name: string, options?: StopAnimationOptions) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n const fadeOut = Math.max(options?.fadeOut ?? 0, 0);\r\n if (fadeOut !== 0) {\r\n info.fadeOut = fadeOut;\r\n info.fadeOutStart = -1;\r\n } else {\r\n this._activeAnimations.delete(ani);\r\n this._activeTracks.forEach((v) => {\r\n v.forEach((tracks, id) => {\r\n v.set(\r\n id,\r\n tracks.filter((track) => track.animation !== ani)\r\n );\r\n });\r\n });\r\n ani.skeletons?.forEach((v, k) => {\r\n const skeleton = this.model.findSkeletonById(k);\r\n if (skeleton) {\r\n const refcount = this._activeSkeletons.get(skeleton)!;\r\n if (refcount === 1) {\r\n skeleton.reset();\r\n this._activeSkeletons.delete(skeleton);\r\n } else {\r\n this._activeSkeletons.set(skeleton, refcount - 1);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n }\r\n /**\r\n * Dispose the animation set and release owned resources.\r\n *\r\n * - Disposes the weak reference to the model.\r\n * - Disposes all registered animation clips.\r\n * - Clears active animations, tracks, and skeleton references.\r\n */\r\n protected onDispose() {\r\n super.onDispose();\r\n for (const k in this._animations) {\r\n this._animations[k]!.dispose();\r\n }\r\n this._animations = {};\r\n this._activeAnimations.clear();\r\n this._activeSkeletons.clear();\r\n this._activeTracks.clear();\r\n }\r\n}\r\n"],"names":["AnimationSet","Disposable","model","_model","_animations","_activeTracks","Map","_activeSkeletons","_activeAnimations","_skeletons","numAnimations","Object","getOwnPropertyNames","length","skeletons","get","name","createAnimation","embedded","console","error","animation","AnimationClip","scene","queueUpdateNode","deleteAnimation","stopAnimation","dispose","getAnimationNames","keys","update","deltaInSeconds","forEach","v","k","fadeOut","fadeOutStart","animateTime","firstFrame","timeAdvance","speedRatio","currentTime","timeDuration","repeatCounter","repeat","alltracks","tracks","filter","track","isPlayingAnimation","weights","map","info","weight","fadeIn","Math","min","states","t","getDuration","calculateState","state","weightedAverage","a","b","mixState","applyState","apply","has","size","getAnimationClip","setAnimationWeight","ani","playAnimation","options","max","set","nodeTracks","blendId","getBlendId","blendedTracks","push","skeleton","findSkeletonById","refcount","playing","delete","id","reset","onDispose","clear"],"mappings":";;;AA8DA;;;;;;;;;;;;;;;;;;;IAoBO,MAAMA,YAAqBC,SAAAA,UAAAA,CAAAA;qBAEhC,MAA0B;qBAE1B,WAA4D;qBAE5D,UAAqC;qBAErC,aAA4E;qBAE5E,gBAAyD;qBAEzD,iBAcE;AACF;;;;MAKA,WAAA,CAAYC,KAAgB,CAAE;QAC5B,KAAK,EAAA;QACL,IAAI,CAACC,MAAM,GAAGD,KAAAA;QACd,IAAI,CAACE,WAAW,GAAG,EAAC;QACpB,IAAI,CAACC,aAAa,GAAG,IAAIC,GAAAA,EAAAA;QACzB,IAAI,CAACC,gBAAgB,GAAG,IAAID,GAAAA,EAAAA;QAC5B,IAAI,CAACE,iBAAiB,GAAG,IAAIF,GAAAA,EAAAA;QAC7B,IAAI,CAACG,UAAU,GAAG,EAAE;AACtB;AACA;;AAEC,MACD,IAAIP,KAAQ,GAAA;QACV,OAAO,IAAI,CAACC,MAAM;AACpB;AACA;;AAEC,MACD,IAAIO,aAAgB,GAAA;AAClB,QAAA,OAAOC,OAAOC,mBAAmB,CAAC,IAAI,CAACR,WAAW,EAAES,MAAM;AAC5D;AACA;;AAEC,MACD,IAAIC,SAAY,GAAA;QACd,OAAO,IAAI,CAACL,UAAU;AACxB;AACA;;;;;MAMAM,GAAAA,CAAIC,IAAY,EAAE;AAChB,QAAA,OAAO,IAAI,CAACZ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,KAAM3B,CAAAA,SAAS,KAAKmD,GAAAA,CAAAA,CAAAA;AAEjD,qBAAA,CAAA;AACF,iBAAA,CAAA;AACAA,gBAAAA,GAAAA,CAAI1D,SAAS,EAAEkB,OAAQ,CAAA,CAACC,CAAGC,EAAAA,CAAAA,GAAAA;AACzB,oBAAA,MAAMgD,WAAW,IAAI,CAAChF,KAAK,CAACiF,gBAAgB,CAACjD,CAAAA,CAAAA;AAC7C,oBAAA,IAAIgD,QAAU,EAAA;AACZ,wBAAA,MAAME,WAAW,IAAI,CAAC7E,gBAAgB,CAACQ,GAAG,CAACmE,QAAAA,CAAAA;AAC3C,wBAAA,IAAIE,aAAa,CAAG,EAAA;AAClBF,4BAAAA,QAAAA,CAASM,KAAK,EAAA;AACd,4BAAA,IAAI,CAACjF,gBAAgB,CAAC+E,MAAM,CAACJ,QAAAA,CAAAA;yBACxB,MAAA;AACL,4BAAA,IAAI,CAAC3E,gBAAgB,CAACqE,GAAG,CAACM,UAAUE,QAAW,GAAA,CAAA,CAAA;AACjD;AACF;AACF,iBAAA,CAAA;AACF;AACF;AACF;AACA;;;;;;AAMC,MACD,SAAsB,GAAA;AACpB,QAAA,KAAK,CAACK,SAAAA,EAAAA;AACN,QAAA,IAAK,MAAMvD,CAAAA,IAAK,IAAI,CAAC9B,WAAW,CAAE;AAChC,YAAA,IAAI,CAACA,WAAW,CAAC8B,CAAAA,CAAE,CAAEP,OAAO,EAAA;AAC9B;QACA,IAAI,CAACvB,WAAW,GAAG,EAAC;QACpB,IAAI,CAACI,iBAAiB,CAACkF,KAAK,EAAA;QAC5B,IAAI,CAACnF,gBAAgB,CAACmF,KAAK,EAAA;QAC3B,IAAI,CAACrF,aAAa,CAACqF,KAAK,EAAA;AAC1B;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"animationset.js","sources":["../../src/animation/animationset.ts"],"sourcesContent":["import { weightedAverage, Disposable } from '@zephyr3d/base';\r\nimport type { DRef, IDisposable } from '@zephyr3d/base';\r\nimport type { SceneNode } from '../scene';\r\nimport { AnimationClip } from './animation';\r\nimport type { AnimationTrack } from './animationtrack';\r\nimport type { Skeleton } from './skeleton';\r\n\r\n/**\r\n * Options for playing an animation.\r\n *\r\n * Controls looping, playback speed (including reverse), and fade-in blending.\r\n * @public\r\n **/\r\nexport type PlayAnimationOptions = {\r\n /**\r\n * Number of loops to play.\r\n *\r\n * - 0: infinite looping (default).\r\n * - n \\> 0: play exactly n loops (each loop is one full duration of the clip).\r\n */\r\n repeat?: number;\r\n /**\r\n * Playback speed multiplier.\r\n *\r\n * - 1: normal speed (default).\r\n * - \\>1: faster; \\<1: slower.\r\n * - Negative values play the clip in reverse. The initial `currentTime` will be set to the end.\r\n */\r\n speedRatio?: number;\r\n /**\r\n * Fade-in duration in seconds.\r\n *\r\n * Interpolates the animation weight from 0 to the clip's configured weight over this time.\r\n * Use together with `stopAnimation(..., { fadeOut })` for smooth cross-fading.\r\n * Default is 0 (no fade-in).\r\n */\r\n fadeIn?: number;\r\n /**\r\n * Weight of the animation clip.\r\n *\r\n * Used during blending when multiple animations affect the same property.\r\n * Default is the clip's configured weight.\r\n */\r\n weight?: number;\r\n};\r\n\r\n/**\r\n * Options for stopping an animation.\r\n *\r\n * Allows a graceful fade-out instead of abrupt stop.\r\n * @public\r\n */\r\nexport type StopAnimationOptions = {\r\n /**\r\n * Fade-out duration in seconds.\r\n *\r\n * Interpolates the current animation weight down to 0 over this time.\r\n * Default is 0 (immediate stop).\r\n */\r\n fadeOut?: number;\r\n};\r\n\r\n/**\r\n * Animation set\r\n *\r\n * Manages a collection of named animation clips for a model and orchestrates:\r\n * - Playback state (time, loops, speed, weights, fade-in/out).\r\n * - Blending across multiple tracks targeting the same property via weighted averages.\r\n * - Skeleton usage and application for clips that drive skeletal animation.\r\n * - Active track registration and cleanup as clips start/stop.\r\n *\r\n * Usage:\r\n * - Create or retrieve `AnimationClip`s by name.\r\n * - Start playback with `playAnimation(name, options)`.\r\n * - Advance animation with `update(deltaSeconds)`.\r\n * - Optionally adjust weight while playing with `setAnimationWeight(name, weight)`.\r\n *\r\n * Lifetime:\r\n * - Disposing the set releases references to the model, clips, and clears active state.\r\n *\r\n * @public\r\n */\r\nexport class AnimationSet extends Disposable implements IDisposable {\r\n /** @internal */\r\n private _model: SceneNode;\r\n /** @internal */\r\n private _animations: Partial<Record<string, AnimationClip>>;\r\n /** @internal */\r\n private _skeletons: DRef<Skeleton>[];\r\n /** @internal */\r\n private readonly _activeTracks: Map<object, Map<unknown, AnimationTrack[]>>;\r\n /** @internal */\r\n private readonly _activeSkeletons: Map<Skeleton, number>;\r\n /** @internal */\r\n private readonly _activeAnimations: Map<\r\n AnimationClip,\r\n {\r\n currentTime: number;\r\n repeat: number;\r\n repeatCounter: number;\r\n weight: number;\r\n speedRatio: number;\r\n firstFrame: boolean;\r\n fadeIn: number;\r\n fadeOut: number;\r\n fadeOutStart: number;\r\n animateTime: number;\r\n }\r\n >;\r\n /**\r\n * Create an AnimationSet controlling the provided model.\r\n *\r\n * @param model - The SceneNode (model root) controlled by this animation set.\r\n */\r\n constructor(model: SceneNode) {\r\n super();\r\n this._model = model;\r\n this._animations = {};\r\n this._activeTracks = new Map();\r\n this._activeSkeletons = new Map();\r\n this._activeAnimations = new Map();\r\n this._skeletons = [];\r\n }\r\n /**\r\n * The model (SceneNode) controlled by this animation set.\r\n */\r\n get model() {\r\n return this._model;\r\n }\r\n /**\r\n * Number of animation clips registered in this set.\r\n */\r\n get numAnimations() {\r\n return Object.getOwnPropertyNames(this._animations).length;\r\n }\r\n /**\r\n * The skeletons used by animations in this set.\r\n */\r\n get skeletons() {\r\n return this._skeletons;\r\n }\r\n /**\r\n * Retrieve an animation clip by name.\r\n *\r\n * @param name - Name of the animation.\r\n * @returns The clip if present; otherwise null.\r\n */\r\n get(name: string) {\r\n return this._animations[name] ?? null;\r\n }\r\n /**\r\n * Create and register a new animation clip.\r\n *\r\n * @param name - Unique name for the animation clip.\r\n * @param embedded - Whether the clip is embedded/owned (implementation-specific). Default false.\r\n * @returns The created clip, or null if the name is empty or not unique.\r\n */\r\n createAnimation(name: string, embedded = false) {\r\n if (!name || this._animations[name]) {\r\n console.error('Animation must have unique name');\r\n return null;\r\n } else {\r\n const animation = new AnimationClip(name, this, embedded);\r\n this._animations[name] = animation;\r\n this._model.scene?.queueUpdateNode(this._model);\r\n return animation;\r\n }\r\n }\r\n /**\r\n * Delete and dispose an animation clip by name.\r\n *\r\n * - If the animation is currently playing, it is first stopped (immediately).\r\n *\r\n * @param name - Name of the animation to remove.\r\n */\r\n deleteAnimation(name: string) {\r\n const animation = this._animations[name];\r\n if (animation) {\r\n this.stopAnimation(name);\r\n delete this._animations[name];\r\n animation.dispose();\r\n }\r\n }\r\n /**\r\n * Get the list of all registered animation names.\r\n *\r\n * @returns An array of clip names.\r\n */\r\n getAnimationNames() {\r\n return Object.keys(this._animations);\r\n }\r\n /**\r\n * Advance and apply active animations.\r\n *\r\n * Responsibilities per call:\r\n * - Update time cursor for each active clip (respecting speedRatio and looping).\r\n * - Enforce repeat limits and apply fade-out termination if configured.\r\n * - For each animated target, blend active tracks (weighted by clip weight × fade-in × fade-out)\r\n * and apply the resulting state to the target.\r\n * - Apply all active skeletons to update skinning transforms.\r\n *\r\n * @param deltaInSeconds - Time step in seconds since last update.\r\n */\r\n update(deltaInSeconds: number) {\r\n this._activeAnimations.forEach((v, k) => {\r\n if (v.fadeOut > 0 && v.fadeOutStart < 0) {\r\n v.fadeOutStart = v.animateTime;\r\n }\r\n // Update animation time\r\n if (v.firstFrame) {\r\n v.firstFrame = false;\r\n } else {\r\n const timeAdvance = deltaInSeconds * v.speedRatio;\r\n v.currentTime += timeAdvance;\r\n v.animateTime += timeAdvance;\r\n if (v.currentTime > k.timeDuration) {\r\n v.repeatCounter++;\r\n v.currentTime = 0;\r\n } else if (v.currentTime < 0) {\r\n v.repeatCounter++;\r\n v.currentTime = k.timeDuration;\r\n }\r\n if (v.repeat !== 0 && v.repeatCounter >= v.repeat) {\r\n this.stopAnimation(k.name);\r\n } else if (v.fadeOut > 0) {\r\n if (v.animateTime - v.fadeOutStart >= v.fadeOut) {\r\n this.stopAnimation(k.name);\r\n }\r\n }\r\n }\r\n });\r\n // Update tracks\r\n this._activeTracks.forEach((v, k) => {\r\n v.forEach((alltracks) => {\r\n // Only deal with tracks which have not been removed\r\n const tracks = alltracks.filter(\r\n (track) => track.animation && this.isPlayingAnimation(track.animation.name)\r\n );\r\n if (tracks.length > 0) {\r\n const weights = tracks.map((track) => {\r\n const info = this._activeAnimations.get(track.animation!)!;\r\n const weight = info.weight;\r\n const fadeIn = info.fadeIn === 0 ? 1 : Math.min(1, info.animateTime / info.fadeIn);\r\n let fadeOut = 1;\r\n if (info.fadeOut !== 0) {\r\n fadeOut = 1 - (info.animateTime - info.fadeOutStart) / info.fadeOut;\r\n }\r\n return weight * fadeIn * fadeOut;\r\n });\r\n const states = tracks.map((track) => {\r\n const info = this._activeAnimations.get(track.animation!)!;\r\n const t = (info.currentTime / track.animation!.timeDuration) * track.getDuration();\r\n return track.calculateState(k, t);\r\n });\r\n const state = weightedAverage(weights, states, (a, b, t) => {\r\n return tracks[0].mixState(a, b, t);\r\n });\r\n tracks[0].applyState(k, state);\r\n }\r\n });\r\n });\r\n // Update skeletons\r\n this._skeletons.forEach((v) => {\r\n v.get()?.apply(deltaInSeconds);\r\n });\r\n }\r\n /**\r\n * Check whether an animation is currently playing.\r\n *\r\n * @param name - Optional animation name. If omitted, returns true if any animation is playing.\r\n * @returns True if playing; otherwise false.\r\n */\r\n isPlayingAnimation(name?: string) {\r\n if (name) {\r\n const animation = this._animations[name];\r\n return !!animation && this._activeAnimations.has(animation);\r\n }\r\n return this._activeAnimations.size > 0;\r\n }\r\n /**\r\n * Get an animation clip by name.\r\n *\r\n * Alias of `get(name)` returning a nullable type.\r\n *\r\n * @param name - Name of the animation.\r\n * @returns The clip if present; otherwise null.\r\n */\r\n getAnimationClip(name: string) {\r\n return this._animations[name] ?? null;\r\n }\r\n /**\r\n * Set the runtime blend weight for a currently playing animation.\r\n *\r\n * Has no effect if the clip is not active.\r\n *\r\n * @param name - Name of the playing animation.\r\n * @param weight - New weight value used during blending.\r\n */\r\n setAnimationWeight(name: string, weight: number) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n info.weight = weight;\r\n }\r\n }\r\n /**\r\n * Start (or update) playback of an animation clip.\r\n *\r\n * Behavior:\r\n * - If the clip is already playing, updates its fade-in (resets fade-out).\r\n * - Otherwise initializes playback state (repeat counter, speed, weight, initial time).\r\n * - Registers clip tracks and skeletons into the active sets for blending and application.\r\n *\r\n * @param name - Name of the animation to play.\r\n * @param options - Playback options (repeat, speedRatio, fadeIn).\r\n */\r\n playAnimation(name: string, options?: PlayAnimationOptions) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const fadeIn = Math.max(options?.fadeIn ?? 0, 0);\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n info.fadeOut = 0;\r\n info.fadeIn = fadeIn;\r\n } else {\r\n const repeat = options?.repeat ?? 0;\r\n const speedRatio = options?.speedRatio ?? 1;\r\n const weight = options?.weight ?? ani.weight ?? 1;\r\n this._activeAnimations.set(ani, {\r\n repeat,\r\n weight,\r\n speedRatio,\r\n fadeIn,\r\n fadeOut: 0,\r\n repeatCounter: 0,\r\n currentTime: speedRatio < 0 ? ani.timeDuration : 0,\r\n animateTime: 0,\r\n fadeOutStart: 0,\r\n firstFrame: true\r\n });\r\n ani.tracks?.forEach((v, k) => {\r\n let nodeTracks = this._activeTracks.get(k);\r\n if (!nodeTracks) {\r\n nodeTracks = new Map();\r\n this._activeTracks.set(k, nodeTracks);\r\n }\r\n for (const track of v) {\r\n const blendId = track.getBlendId();\r\n let blendedTracks = nodeTracks.get(blendId);\r\n if (!blendedTracks) {\r\n blendedTracks = [];\r\n nodeTracks.set(blendId, blendedTracks);\r\n }\r\n blendedTracks.push(track);\r\n }\r\n });\r\n ani.skeletons?.forEach((v, k) => {\r\n const skeleton = this.model.findSkeletonById(k);\r\n if (skeleton) {\r\n const refcount = this._activeSkeletons.get(skeleton);\r\n if (refcount) {\r\n this._activeSkeletons.set(skeleton, refcount + 1);\r\n } else {\r\n this._activeSkeletons.set(skeleton, 1);\r\n }\r\n skeleton.playing = true;\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Stop playback of an animation clip.\r\n *\r\n * Behavior:\r\n * - If `options.fadeOut > 0`, marks the clip for fade-out; actual removal occurs after fade completes.\r\n * - If `fadeOut` is 0 or omitted, immediately:\r\n * - Removes the clip from active animations.\r\n * - Unregisters its tracks from active track maps.\r\n * - Decrements skeleton reference counts; resets and removes skeletons when refcount reaches 0.\r\n *\r\n * @param name - Name of the animation to stop.\r\n * @param options - Optional fade-out configuration.\r\n */\r\n stopAnimation(name: string, options?: StopAnimationOptions) {\r\n const ani = this._animations[name];\r\n if (!ani) {\r\n console.error(`Animation ${name} not exists`);\r\n return;\r\n }\r\n const info = this._activeAnimations.get(ani);\r\n if (info) {\r\n const fadeOut = Math.max(options?.fadeOut ?? 0, 0);\r\n if (fadeOut !== 0) {\r\n info.fadeOut = fadeOut;\r\n info.fadeOutStart = -1;\r\n } else {\r\n this._activeAnimations.delete(ani);\r\n this._activeTracks.forEach((v) => {\r\n v.forEach((tracks, id) => {\r\n v.set(\r\n id,\r\n tracks.filter((track) => track.animation !== ani)\r\n );\r\n });\r\n });\r\n ani.skeletons?.forEach((v, k) => {\r\n const skeleton = this.model.findSkeletonById(k);\r\n if (skeleton) {\r\n const refcount = this._activeSkeletons.get(skeleton)!;\r\n if (refcount === 1) {\r\n skeleton.reset();\r\n this._activeSkeletons.delete(skeleton);\r\n } else {\r\n this._activeSkeletons.set(skeleton, refcount - 1);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n }\r\n /**\r\n * Dispose the animation set and release owned resources.\r\n *\r\n * - Disposes the weak reference to the model.\r\n * - Disposes all registered animation clips.\r\n * - Clears active animations, tracks, and skeleton references.\r\n */\r\n protected onDispose() {\r\n super.onDispose();\r\n for (const k in this._animations) {\r\n this._animations[k]!.dispose();\r\n }\r\n this._animations = {};\r\n this._activeAnimations.clear();\r\n this._activeSkeletons.clear();\r\n this._activeTracks.clear();\r\n }\r\n}\r\n"],"names":["AnimationSet","Disposable","model","_model","_animations","_activeTracks","Map","_activeSkeletons","_activeAnimations","_skeletons","numAnimations","Object","getOwnPropertyNames","length","skeletons","get","name","createAnimation","embedded","console","error","animation","AnimationClip","scene","queueUpdateNode","deleteAnimation","stopAnimation","dispose","getAnimationNames","keys","update","deltaInSeconds","forEach","v","k","fadeOut","fadeOutStart","animateTime","firstFrame","timeAdvance","speedRatio","currentTime","timeDuration","repeatCounter","repeat","alltracks","tracks","filter","track","isPlayingAnimation","weights","map","info","weight","fadeIn","Math","min","states","t","getDuration","calculateState","state","weightedAverage","a","b","mixState","applyState","apply","has","size","getAnimationClip","setAnimationWeight","ani","playAnimation","options","max","set","nodeTracks","blendId","getBlendId","blendedTracks","push","skeleton","findSkeletonById","refcount","playing","delete","id","reset","onDispose","clear"],"mappings":";;;AA8DA;;;;;;;;;;;;;;;;;;;IAoBO,MAAMA,YAAqBC,SAAAA,UAAAA,CAAAA;qBAEhC,MAA0B;qBAE1B,WAA4D;qBAE5D,UAAqC;qBAErC,aAA4E;qBAE5E,gBAAyD;qBAEzD,iBAcE;AACF;;;;MAKA,WAAA,CAAYC,KAAgB,CAAE;QAC5B,KAAK,EAAA;QACL,IAAI,CAACC,MAAM,GAAGD,KAAAA;QACd,IAAI,CAACE,WAAW,GAAG,EAAC;QACpB,IAAI,CAACC,aAAa,GAAG,IAAIC,GAAAA,EAAAA;QACzB,IAAI,CAACC,gBAAgB,GAAG,IAAID,GAAAA,EAAAA;QAC5B,IAAI,CAACE,iBAAiB,GAAG,IAAIF,GAAAA,EAAAA;QAC7B,IAAI,CAACG,UAAU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EP,OAAO,EAAA;AAC9B;QACA,IAAI,CAACvB,WAAW,GAAG,EAAC;QACpB,IAAI,CAACI,iBAAiB,CAACkF,KAAK,EAAA;QAC5B,IAAI,CAACnF,gBAAgB,CAACmF,KAAK,EAAA;QAC3B,IAAI,CAACrF,aAAa,CAACqF,KAAK,EAAA;AAC1B;AACF;;;;"}
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { Vector3, Quaternion } from '@zephyr3d/base';
|
|
2
|
+
import { IKSolver } from './ik_solver.js';
|
|
3
|
+
import { IKUtils } from './ik_utils.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* CCD (Cyclic Coordinate Descent) IK solver.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* CCD is an iterative IK algorithm that works by:
|
|
10
|
+
* 1. Starting from the joint closest to the end effector
|
|
11
|
+
* 2. Rotating each joint to point the end effector toward the target
|
|
12
|
+
* 3. Moving backward through the chain to the root
|
|
13
|
+
* 4. Repeating until convergence or max iterations
|
|
14
|
+
*
|
|
15
|
+
* CCD is generally faster than FABRIK and works well for chains of any length.
|
|
16
|
+
* It's particularly good for tentacles, tails, and other flexible chains.
|
|
17
|
+
*
|
|
18
|
+
* Supports multiple pole vectors to control the bending direction of different joints.
|
|
19
|
+
*
|
|
20
|
+
* @public
|
|
21
|
+
*/ class CCDSolver extends IKSolver {
|
|
22
|
+
/** Map of joint index to pole vector configuration */ _poleVectors;
|
|
23
|
+
/** Twist constraints for each joint (indexed by joint index) */ _twistConstraints;
|
|
24
|
+
/**
|
|
25
|
+
* Create a CCD solver.
|
|
26
|
+
*
|
|
27
|
+
* @param chain - The IK chain to solve
|
|
28
|
+
* @param maxIterations - Maximum number of iterations (default: 10)
|
|
29
|
+
* @param tolerance - Convergence tolerance in world units (default: 0.001)
|
|
30
|
+
*/ constructor(chain, maxIterations = 10, tolerance = 0.001){
|
|
31
|
+
super(chain, maxIterations, tolerance);
|
|
32
|
+
this._poleVectors = new Map();
|
|
33
|
+
this._twistConstraints = new Map();
|
|
34
|
+
// Set default twist constraints for all joints
|
|
35
|
+
for(let i = 0; i < chain.joints.length - 1; i++){
|
|
36
|
+
// Middle joints have more restrictive twist limits
|
|
37
|
+
const isMiddleJoint = i > 0 && i < chain.joints.length - 2;
|
|
38
|
+
this._twistConstraints.set(i, {
|
|
39
|
+
minTwist: isMiddleJoint ? -Math.PI * 0.2 : -Math.PI * 0.3,
|
|
40
|
+
maxTwist: isMiddleJoint ? Math.PI * 0.2 : Math.PI * 0.3,
|
|
41
|
+
smoothFactor: 0.3
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Set twist constraint for a specific joint.
|
|
47
|
+
*
|
|
48
|
+
* @param jointIndex - Index of the joint
|
|
49
|
+
* @param minTwist - Minimum twist angle in radians
|
|
50
|
+
* @param maxTwist - Maximum twist angle in radians
|
|
51
|
+
* @param smoothFactor - Smoothing factor [0-1] (default: 0.3)
|
|
52
|
+
*/ setTwistConstraint(jointIndex, minTwist, maxTwist, smoothFactor = 0.3) {
|
|
53
|
+
if (jointIndex < 0 || jointIndex >= this._chain.joints.length - 1) {
|
|
54
|
+
throw new Error(`Invalid joint index: ${jointIndex}`);
|
|
55
|
+
}
|
|
56
|
+
this._twistConstraints.set(jointIndex, {
|
|
57
|
+
minTwist,
|
|
58
|
+
maxTwist,
|
|
59
|
+
smoothFactor: Math.max(0, Math.min(1, smoothFactor))
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Get twist constraint for a specific joint.
|
|
64
|
+
*
|
|
65
|
+
* @param jointIndex - Index of the joint
|
|
66
|
+
* @returns Twist constraint or undefined if not set
|
|
67
|
+
*/ getTwistConstraint(jointIndex) {
|
|
68
|
+
return this._twistConstraints.get(jointIndex);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Remove twist constraint for a specific joint.
|
|
72
|
+
*
|
|
73
|
+
* @param jointIndex - Index of the joint
|
|
74
|
+
* @returns True if a constraint was removed
|
|
75
|
+
*/ removeTwistConstraint(jointIndex) {
|
|
76
|
+
return this._twistConstraints.delete(jointIndex);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Clear all twist constraints.
|
|
80
|
+
*/ clearTwistConstraints() {
|
|
81
|
+
this._twistConstraints.clear();
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Set pole vector for a specific joint.
|
|
85
|
+
*
|
|
86
|
+
* @param jointIndex - Index of the joint to apply pole vector to
|
|
87
|
+
* @param poleVector - Pole vector position in world space
|
|
88
|
+
* @param weight - Weight of the pole vector constraint (0-1, default: 1)
|
|
89
|
+
*/ setPoleVector(jointIndex, poleVector, weight = 1) {
|
|
90
|
+
if (jointIndex < 0 || jointIndex >= this._chain.joints.length) {
|
|
91
|
+
throw new Error(`Invalid joint index: ${jointIndex}`);
|
|
92
|
+
}
|
|
93
|
+
this._poleVectors.set(jointIndex, {
|
|
94
|
+
position: poleVector.clone(),
|
|
95
|
+
weight: Math.max(0, Math.min(1, weight))
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Remove pole vector for a specific joint.
|
|
100
|
+
*
|
|
101
|
+
* @param jointIndex - Index of the joint to remove pole vector from
|
|
102
|
+
* @returns True if a pole vector was removed, false if none existed
|
|
103
|
+
*/ removePoleVector(jointIndex) {
|
|
104
|
+
return this._poleVectors.delete(jointIndex);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Clear all pole vectors.
|
|
108
|
+
*/ clearPoleVectors() {
|
|
109
|
+
this._poleVectors.clear();
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Get pole vector configuration for a specific joint.
|
|
113
|
+
*
|
|
114
|
+
* @param jointIndex - Index of the joint
|
|
115
|
+
* @returns Pole vector configuration or undefined if not set
|
|
116
|
+
*/ getPoleVector(jointIndex) {
|
|
117
|
+
const config = this._poleVectors.get(jointIndex);
|
|
118
|
+
if (config) {
|
|
119
|
+
return {
|
|
120
|
+
position: config.position.clone(),
|
|
121
|
+
weight: config.weight
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Check if a joint has a pole vector.
|
|
128
|
+
*
|
|
129
|
+
* @param jointIndex - Index of the joint
|
|
130
|
+
* @returns True if the joint has a pole vector
|
|
131
|
+
*/ hasPoleVector(jointIndex) {
|
|
132
|
+
return this._poleVectors.has(jointIndex);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Solve the IK chain to reach the target position using CCD algorithm.
|
|
136
|
+
*
|
|
137
|
+
* @param target - Target position for the end effector
|
|
138
|
+
* @returns True if converged within tolerance, false otherwise
|
|
139
|
+
*/ solve(target) {
|
|
140
|
+
const joints = this._chain.joints;
|
|
141
|
+
// Update joint positions from scene nodes before solving
|
|
142
|
+
this._chain.updateFromNodes();
|
|
143
|
+
// Store original positions
|
|
144
|
+
this._chain.storeOriginalPositions();
|
|
145
|
+
let converged = false;
|
|
146
|
+
for(let iteration = 0; iteration < this._maxIterations; iteration++){
|
|
147
|
+
// Check convergence
|
|
148
|
+
const endEffector = joints[joints.length - 1];
|
|
149
|
+
const distToTarget = Vector3.distance(endEffector.position, target);
|
|
150
|
+
if (distToTarget < this._tolerance) {
|
|
151
|
+
converged = true;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
// Iterate backward through joints (from second-to-last to root)
|
|
155
|
+
// We skip the end effector itself since it doesn't have a child to rotate toward
|
|
156
|
+
for(let i = joints.length - 2; i >= 0; i--){
|
|
157
|
+
const joint = joints[i];
|
|
158
|
+
// Vector from current joint to end effector
|
|
159
|
+
const toEnd = Vector3.sub(endEffector.position, joint.position, new Vector3());
|
|
160
|
+
const toEndDist = toEnd.magnitude;
|
|
161
|
+
// Vector from current joint to target
|
|
162
|
+
const toTarget = Vector3.sub(target, joint.position, new Vector3());
|
|
163
|
+
const toTargetDist = toTarget.magnitude;
|
|
164
|
+
// Skip if either vector is too small
|
|
165
|
+
if (toEndDist < 0.000001 || toTargetDist < 0.000001) {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
// Normalize vectors
|
|
169
|
+
const toEndDir = Vector3.scale(toEnd, 1 / toEndDist, new Vector3());
|
|
170
|
+
const toTargetDir = Vector3.scale(toTarget, 1 / toTargetDist, new Vector3());
|
|
171
|
+
// Calculate rotation needed to align end effector toward target
|
|
172
|
+
let rotation = new Quaternion();
|
|
173
|
+
IKUtils.fromToRotation(toEndDir, toTargetDir, rotation);
|
|
174
|
+
// Apply rotation to all joints from current to end effector
|
|
175
|
+
this._rotateJointsFromIndex(i, rotation, joint.position);
|
|
176
|
+
// Apply constraints after rotating this joint
|
|
177
|
+
this._applyConstraintsForJoint(i);
|
|
178
|
+
}
|
|
179
|
+
// Apply all pole vector constraints after each full iteration
|
|
180
|
+
// This is more stable than applying them during the CCD loop
|
|
181
|
+
this._applyAllPoleVectors();
|
|
182
|
+
}
|
|
183
|
+
return converged;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Rotate all joints from the given index to the end effector around a pivot point.
|
|
187
|
+
*
|
|
188
|
+
* @param startIndex - Index of the joint to start rotating from
|
|
189
|
+
* @param rotation - Rotation to apply
|
|
190
|
+
* @param pivot - Pivot point for rotation (position of the joint being adjusted)
|
|
191
|
+
*/ _rotateJointsFromIndex(startIndex, rotation, pivot) {
|
|
192
|
+
const joints = this._chain.joints;
|
|
193
|
+
// Rotate all joints from startIndex+1 to end effector
|
|
194
|
+
for(let i = startIndex + 1; i < joints.length; i++){
|
|
195
|
+
const joint = joints[i];
|
|
196
|
+
// Translate to pivot
|
|
197
|
+
const offset = Vector3.sub(joint.position, pivot, new Vector3());
|
|
198
|
+
// Rotate around pivot
|
|
199
|
+
const rotated = rotation.transform(offset, new Vector3());
|
|
200
|
+
// Translate back
|
|
201
|
+
joint.position.set(Vector3.add(pivot, rotated, new Vector3()));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Apply all pole vector constraints.
|
|
206
|
+
*
|
|
207
|
+
* @remarks
|
|
208
|
+
* This method applies all configured pole vectors to their respective joints.
|
|
209
|
+
* Pole vectors are applied in reverse order (from end to root) to minimize
|
|
210
|
+
* interference between multiple pole vectors. This ensures that pole vectors
|
|
211
|
+
* closer to the end effector are not affected by pole vectors closer to the root.
|
|
212
|
+
*/ _applyAllPoleVectors() {
|
|
213
|
+
if (this._poleVectors.size === 0) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
// Apply pole vectors in reverse order (from end to root)
|
|
217
|
+
// This prevents earlier pole vectors from affecting later ones
|
|
218
|
+
const sortedIndices = Array.from(this._poleVectors.keys()).sort((a, b)=>b - a);
|
|
219
|
+
for (const jointIndex of sortedIndices){
|
|
220
|
+
const config = this._poleVectors.get(jointIndex);
|
|
221
|
+
if (config && config.weight > 0.001) {
|
|
222
|
+
this._applyPoleVectorTwist(jointIndex, config.position, config.weight);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Apply pole vector twist to a specific joint.
|
|
228
|
+
*
|
|
229
|
+
* @remarks
|
|
230
|
+
* This method is called after the base CCD rotation has been applied.
|
|
231
|
+
* It adds an additional twist rotation around the joint-to-end axis
|
|
232
|
+
* to make the next joint (child) bend toward the pole vector.
|
|
233
|
+
*
|
|
234
|
+
* @param jointIndex - Index of the pole joint
|
|
235
|
+
* @param poleVector - Pole vector position in world space
|
|
236
|
+
* @param weight - Weight of the pole vector constraint (0-1)
|
|
237
|
+
*/ _applyPoleVectorTwist(jointIndex, poleVector, weight) {
|
|
238
|
+
const joints = this._chain.joints;
|
|
239
|
+
// We need at least 3 joints to apply pole vector (parent, pole joint, child)
|
|
240
|
+
if (jointIndex < 1 || jointIndex >= joints.length - 1) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const parentJoint = joints[jointIndex - 1];
|
|
244
|
+
const currentJoint = joints[jointIndex];
|
|
245
|
+
const childJoint = joints[jointIndex + 1];
|
|
246
|
+
const parentPos = parentJoint.position;
|
|
247
|
+
const currentPos = currentJoint.position;
|
|
248
|
+
const childPos = childJoint.position;
|
|
249
|
+
// Calculate the plane defined by parent, child, and pole vector
|
|
250
|
+
// Vector from parent to child (the "line" we're bending around)
|
|
251
|
+
const parentToChild = Vector3.sub(childPos, parentPos, new Vector3());
|
|
252
|
+
const lineLength = parentToChild.magnitude;
|
|
253
|
+
if (lineLength < 0.000001) {
|
|
254
|
+
return; // Parent and child are at same position
|
|
255
|
+
}
|
|
256
|
+
const lineDir = Vector3.scale(parentToChild, 1 / lineLength, new Vector3());
|
|
257
|
+
// Project current joint onto the parent-child line
|
|
258
|
+
const parentToCurrent = Vector3.sub(currentPos, parentPos, new Vector3());
|
|
259
|
+
const projectionLength = Vector3.dot(parentToCurrent, lineDir);
|
|
260
|
+
const projectionPoint = Vector3.scale(lineDir, projectionLength, new Vector3());
|
|
261
|
+
Vector3.add(parentPos, projectionPoint, projectionPoint);
|
|
262
|
+
// Vector from projection point to current joint (perpendicular to line)
|
|
263
|
+
const perpendicular = Vector3.sub(currentPos, projectionPoint, new Vector3());
|
|
264
|
+
const perpLength = perpendicular.magnitude;
|
|
265
|
+
if (perpLength < 0.000001) {
|
|
266
|
+
return; // Current joint is on the line
|
|
267
|
+
}
|
|
268
|
+
// Calculate desired direction toward pole vector
|
|
269
|
+
const parentToPole = Vector3.sub(poleVector, parentPos, new Vector3());
|
|
270
|
+
const poleProjectionLength = Vector3.dot(parentToPole, lineDir);
|
|
271
|
+
const poleProjectionPoint = Vector3.scale(lineDir, poleProjectionLength, new Vector3());
|
|
272
|
+
Vector3.add(parentPos, poleProjectionPoint, poleProjectionPoint);
|
|
273
|
+
// Direction from projection to pole (perpendicular to line)
|
|
274
|
+
const poleDirection = Vector3.sub(poleVector, poleProjectionPoint, new Vector3());
|
|
275
|
+
const poleDirLength = poleDirection.magnitude;
|
|
276
|
+
if (poleDirLength < 0.000001) {
|
|
277
|
+
return; // Pole is on the line
|
|
278
|
+
}
|
|
279
|
+
poleDirection.scaleBy(1 / poleDirLength);
|
|
280
|
+
// Calculate new position for current joint
|
|
281
|
+
// Keep the same distance from the line, but rotate toward pole direction
|
|
282
|
+
const desiredPerpendicular = Vector3.scale(poleDirection, perpLength, new Vector3());
|
|
283
|
+
const newPosition = Vector3.add(projectionPoint, desiredPerpendicular, new Vector3());
|
|
284
|
+
// Apply weight (blend between original and constrained position)
|
|
285
|
+
if (weight < 0.999) {
|
|
286
|
+
const blended = new Vector3();
|
|
287
|
+
blended.x = currentPos.x + (newPosition.x - currentPos.x) * weight;
|
|
288
|
+
blended.y = currentPos.y + (newPosition.y - currentPos.y) * weight;
|
|
289
|
+
blended.z = currentPos.z + (newPosition.z - currentPos.z) * weight;
|
|
290
|
+
currentJoint.position.set(blended);
|
|
291
|
+
} else {
|
|
292
|
+
currentJoint.position.set(newPosition);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Apply constraints for a specific joint.
|
|
297
|
+
*
|
|
298
|
+
* @param jointIndex - Index of the joint to apply constraints to
|
|
299
|
+
*/ _applyConstraintsForJoint(jointIndex) {
|
|
300
|
+
const constraints = this._chain.constraints;
|
|
301
|
+
for (const constraint of constraints){
|
|
302
|
+
if (constraint.jointIndex === jointIndex) {
|
|
303
|
+
constraint.apply(this._chain.joints);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Apply the solved joint positions to scene nodes as rotations.
|
|
309
|
+
*
|
|
310
|
+
* @param weight - Blend weight (0 = original, 1 = full IK, default: 1)
|
|
311
|
+
*/ applyToNodes(weight = 1) {
|
|
312
|
+
const joints = this._chain.joints;
|
|
313
|
+
// Apply rotation for all joints except the end effector
|
|
314
|
+
for(let i = 0; i < joints.length - 1; i++){
|
|
315
|
+
const joint = joints[i];
|
|
316
|
+
const nextJoint = joints[i + 1];
|
|
317
|
+
// Calculate direction from current joint to next joint in world space
|
|
318
|
+
const originalDir = Vector3.sub(nextJoint.originalPosition, joint.originalPosition, new Vector3());
|
|
319
|
+
const newDir = Vector3.sub(nextJoint.position, joint.position, new Vector3());
|
|
320
|
+
const originalDirNorm = Vector3.normalize(originalDir, new Vector3());
|
|
321
|
+
const newDirNorm = Vector3.normalize(newDir, new Vector3());
|
|
322
|
+
// Calculate basic rotation
|
|
323
|
+
const deltaRotation = new Quaternion();
|
|
324
|
+
IKUtils.fromToRotation(originalDirNorm, newDirNorm, deltaRotation);
|
|
325
|
+
// Calculate new world rotation
|
|
326
|
+
let worldRotation = Quaternion.multiply(deltaRotation, joint.originalRotation, new Quaternion());
|
|
327
|
+
// Apply swing-twist constraint to prevent over-rotation
|
|
328
|
+
const swing = new Quaternion();
|
|
329
|
+
const twist = new Quaternion();
|
|
330
|
+
IKUtils.decomposeSwingTwist(worldRotation, newDirNorm, swing, twist);
|
|
331
|
+
// Get twist angle
|
|
332
|
+
let twistAngle = IKUtils.getTwistAngle(twist, newDirNorm);
|
|
333
|
+
// Get twist constraint for this joint
|
|
334
|
+
const constraint = this._twistConstraints.get(i);
|
|
335
|
+
if (constraint) {
|
|
336
|
+
// Clamp and smooth twist
|
|
337
|
+
twistAngle = IKUtils.clampAndSmoothTwist(twistAngle, joint.previousTwist, constraint.minTwist, constraint.maxTwist, constraint.smoothFactor);
|
|
338
|
+
}
|
|
339
|
+
// Store for next frame
|
|
340
|
+
joint.previousTwist = twistAngle;
|
|
341
|
+
// Reconstruct rotation from clamped twist: Q = Twist * Swing
|
|
342
|
+
const clampedTwist = new Quaternion();
|
|
343
|
+
IKUtils.createTwist(twistAngle, newDirNorm, clampedTwist);
|
|
344
|
+
worldRotation = Quaternion.multiply(clampedTwist, swing, worldRotation);
|
|
345
|
+
// Blend with original rotation based on weight
|
|
346
|
+
if (weight < 1) {
|
|
347
|
+
Quaternion.slerp(joint.originalRotation, worldRotation, weight, worldRotation);
|
|
348
|
+
}
|
|
349
|
+
// Store this frame's world rotation for next frame's twist continuity
|
|
350
|
+
if (!joint.previousIKRotation) {
|
|
351
|
+
joint.previousIKRotation = worldRotation.clone();
|
|
352
|
+
} else {
|
|
353
|
+
joint.previousIKRotation.set(worldRotation);
|
|
354
|
+
}
|
|
355
|
+
// Convert world rotation to local rotation (relative to parent)
|
|
356
|
+
if (joint.node.parent) {
|
|
357
|
+
const parentWorldRotation = new Quaternion();
|
|
358
|
+
joint.node.parent.worldMatrix.decompose(null, parentWorldRotation, null);
|
|
359
|
+
// localRotation = conjugate(parentWorldRotation) * worldRotation
|
|
360
|
+
const parentInvRotation = Quaternion.conjugate(parentWorldRotation, new Quaternion());
|
|
361
|
+
const localRotation = Quaternion.multiply(parentInvRotation, worldRotation, new Quaternion());
|
|
362
|
+
joint.node.rotation = localRotation;
|
|
363
|
+
} else {
|
|
364
|
+
// Root node has no parent, world rotation is local rotation
|
|
365
|
+
joint.node.rotation = worldRotation;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export { CCDSolver };
|
|
372
|
+
//# sourceMappingURL=ccd_solver.js.map
|