From 25660046fb84e80a03b13c047ba23a45f20a4f24 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Tue, 11 Jun 2019 10:23:09 +0800 Subject: [PATCH] make cubic spline lerp as custom lerp; animation documents (#4577) --- cocos/animation/animation-curve.ts | 206 ++------------ cocos/animation/cross-fade.ts | 39 ++- cocos/animation/cubic-spline-value.ts | 102 +++++++ cocos/animation/index.ts | 1 + cocos/animation/types.ts | 3 +- cocos/components/animation-component.ts | 354 +++++++++++------------- 6 files changed, 315 insertions(+), 390 deletions(-) create mode 100644 cocos/animation/cubic-spline-value.ts diff --git a/cocos/animation/animation-curve.ts b/cocos/animation/animation-curve.ts index 4cc0f0bb1d..6761641c02 100644 --- a/cocos/animation/animation-curve.ts +++ b/cocos/animation/animation-curve.ts @@ -37,38 +37,6 @@ export type EasingMethodName = keyof (typeof easing); */ export type EasingMethod = EasingMethodName | BezierControlPoints; -/** - * 动画的插值方式。 - */ -export enum AnimationInterpolation { - /** - * 曲线值之间进行线性插值。 - * 当使用此插值方式时,曲线值的类型必须为 `number`、`Number` 或继承自 `ValueType`。 - */ - Linear = 0, - - /** - * 直接使用起始曲线值作为插值结果。 - */ - Step = 1, - - /** - * 曲线值之间进行三次样条插值。 - * 当使用此插值方式时,曲线值的类型必须为 `ICubicSpline` - * 并且类型参数 `T` 必须为 `number`、`Number` 或继承自 `ValueType`。 - */ - CubicSpline = 2, - - /** - * 使用自定义插值方式,插值结果为 `from.lerp.call(from, to, ratio)`,其中 - * `from` 为起始曲线值;`to` 为结束曲线值;`ratio` 表示插值比例,范围为 `(0,1)`。 - * 当使用此插值方式时,曲线值的类型必须为 `ILerpable`。 - */ - Custom = 3, -} -ccenum(AnimationInterpolation); -cc.AnimationInterpolation = AnimationInterpolation; - type LerpFunction = (from: T, to: T, t: number, dt: number) => T; /** @@ -102,35 +70,10 @@ export interface IPropertyCurveData { motionPaths?: MotionPath | MotionPath[]; /** - * 曲线的插值方式。 + * 是否进行插值。 + * @default true */ - interpolation?: AnimationInterpolation; -} - -interface ICubicSplineValue { - inTangent: T; - dataPoint: T; - outTangent: T; -} - -function fullfillInterpolationRequirement (interpolation: AnimationInterpolation, value: any) { - const isNumberLikeOrValueType = (v: any) => { - return typeof v === 'number' || - (typeof v === 'object' && v !== null && - (v instanceof Number || v instanceof ValueType)); - }; - switch (interpolation) { - case AnimationInterpolation.Linear: - return isNumberLikeOrValueType(value); - case AnimationInterpolation.CubicSpline: - return (typeof value === 'object' && value !== null) && - isNumberLikeOrValueType(value.inTangent) && - isNumberLikeOrValueType(value.outTangent) && - isNumberLikeOrValueType(value.dataPoint); - case AnimationInterpolation.Custom: - return isLerpable(value); - } - return true; + interpolate?: boolean; } export class RatioSampler { @@ -205,12 +148,10 @@ export class AnimCurve { /** * Lerp function used. If undefined, no lerp is performed. */ - private _lerp: LerpFunction | undefined = undefined; + private _lerp: undefined | ((from: any, to: any, t: number, dt: number) => any) = undefined; private _stepfiedValues?: any[]; - private _interpolation: AnimationInterpolation; - constructor (propertyCurveData: IPropertyCurveData, propertyName: string, isNode: boolean, ratioSampler: RatioSampler | null) { this._ratioSampler = ratioSampler; @@ -241,33 +182,12 @@ export class AnimCurve { const firstValue = propertyCurveData.values[0]; - // If no interpolation is explicit specified, deduce the interpolation. - if (propertyCurveData.interpolation !== undefined) { - this._interpolation = propertyCurveData.interpolation; - } else { - this._interpolation = deduceInterpolation(firstValue); - } + const interpolate = propertyCurveData.interpolate === undefined ? + true : propertyCurveData.interpolate; // Setup the lerp function. - if (CC_DEV) { - if (!this._values.every( - (value) => fullfillInterpolationRequirement(this._interpolation, value))) { - error( - `Curve values for which ` + - `${AnimationInterpolation[this._interpolation]} ` + - `is used do not satify the type requirements.`); - } - } - switch (this._interpolation) { - case AnimationInterpolation.Custom: - this._lerp = customLerpFxInvoker; - break; - case AnimationInterpolation.Linear: - this._lerp = selectLinearLerpFx(firstValue); - break; - case AnimationInterpolation.CubicSpline: - this._lerp = selectCubicSplineLerpFx(firstValue); - break; + if (interpolate) { + this._lerp = selectLerpFx(firstValue); } // Setup the blend function. @@ -362,10 +282,8 @@ export class AnimCurve { } } } - if (!isLerped) { - if (this._interpolation === AnimationInterpolation.CubicSpline) { - return value.dataPoint; - } + if (!isLerped && value && value.getNoLerp) { + return value.getNoLerp(); } return value; } @@ -439,20 +357,7 @@ function quickFindIndex (ratios: number[], ratio: number) { return ~(floorIndex + 1); } -function customLerpFxInvoker (from: ILerpable, to: ILerpable, t: number): any { - return from.lerp(to, t); -} - -/** - * Try deduce interpolation method from curve's value. - * @param value Any value in the curve. - */ -function deduceInterpolation (value: any): AnimationInterpolation { - // If linear interpolation is valid, use it; or do not do interpolation. - return selectLinearLerpFx(value) ? AnimationInterpolation.Linear : AnimationInterpolation.Step; -} - -const selectLinearLerpFx = (() => { +const selectLerpFx = (() => { function makeValueTypeLerpFx (constructor: Constructor) { const tempValue = new constructor(); return (from: T, to: T, ratio: number) => { @@ -460,10 +365,11 @@ const selectLinearLerpFx = (() => { }; } - const lerpNumber = vmath.lerp; + function callLerpable (from: ILerpable, to: ILerpable, t: number, dt: number): any { + return from.lerp(to, t, dt); + } - const builtinLerpFxTable: Map = new Map(); - builtinLerpFxTable.set(Number, lerpNumber); + const lerpNumber = vmath.lerp; return (value: any): LerpFunction | undefined => { if (value === null) { @@ -471,81 +377,13 @@ const selectLinearLerpFx = (() => { } if (typeof value === 'number') { return lerpNumber; - } else if (value instanceof ValueType) { - return makeValueTypeLerpFx(value.constructor as typeof ValueType); - } else if (typeof value === 'object') { - const result = builtinLerpFxTable.get(value.constructor); - if (result) { - return result; - } - } - return undefined; - }; -})(); - -const selectCubicSplineLerpFx = (() => { - type ScaleFx = (out: T, v: T, s: number) => T; - type ScaleAndAddFx = (out: T, v1: T, v2: T, s: number) => T; - function makeValueTypeLerpFx ( - constructor: Constructor, - scaleFx: ScaleFx, - scaleAndAdd: ScaleAndAddFx) { - let tempValue = new constructor(); - let m0 = new constructor(); - let m1 = new constructor(); - return (from: ICubicSplineValue, to: ICubicSplineValue, t: number, dt: number) => { - const p0 = from.dataPoint; - const p1 = to.dataPoint; - // dt => t_k+1 - t_k - m0 = scaleFx(m0, from.outTangent, dt); - m1 = scaleFx(m1, to.inTangent, dt); - const t_3 = t * t * t; - const t_2 = t * t; - const f_0 = 2 * t_3 - 3 * t_2 + 1; - const f_1 = t_3 - 2 * t_2 + t; - const f_2 = -2 * t_3 + 3 * t_2; - const f_3 = t_3 - t_2; - tempValue = scaleFx(tempValue, p0, f_0); - tempValue = scaleAndAdd(tempValue, tempValue, m0, f_1); - tempValue = scaleAndAdd(tempValue, tempValue, p1, f_2); - tempValue = scaleAndAdd(tempValue, tempValue, m1, f_3); - return tempValue; - }; - } - - const lerpNumber = (from: ICubicSplineValue, to: ICubicSplineValue, t: number, dt: number) => { - const p0 = from.dataPoint; - const p1 = to.dataPoint; - // dt => t_k+1 - t_k - const m0 = from.outTangent * dt; - const m1 = to.inTangent * dt; - const t_3 = t * t * t; - const t_2 = t * t; - const f_0 = 2 * t_3 - 3 * t_2 + 1; - const f_1 = t_3 - 2 * t_2 + t; - const f_2 = -2 * t_3 + 3 * t_2; - const f_3 = t_3 - t_2; - return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3; - }; - - const builtinLerpFxTable: Map = new Map(); - builtinLerpFxTable.set(Number, lerpNumber); - builtinLerpFxTable.set(Vec2, makeValueTypeLerpFx(Vec2, vmath.vec2.scale, vmath.vec2.scaleAndAdd)); - builtinLerpFxTable.set(Vec3, makeValueTypeLerpFx(Vec3, vmath.vec3.scale, vmath.vec3.scaleAndAdd)); - builtinLerpFxTable.set(Vec4, makeValueTypeLerpFx(Vec4, vmath.vec4.scale, vmath.vec4.scaleAndAdd)); - builtinLerpFxTable.set(Quat, makeValueTypeLerpFx(Quat, vmath.quat.scale, vmath.quat.scaleAndAdd)); - - return (value: any): LerpFunction | undefined => { - if (value === null || !Reflect.has(value, 'dataPoint')) { - return undefined; - } - const dataValue = value.dataPoint; - if (typeof dataValue === 'number') { - return lerpNumber; - } else if (typeof dataValue === 'object') { - const result = builtinLerpFxTable.get(dataValue.constructor); - if (result) { - return result; + } else if (typeof value === 'object' && value.constructor) { + if (value instanceof ValueType) { + return makeValueTypeLerpFx(value.constructor as typeof ValueType); + } else if (value.constructor === Number) { + return lerpNumber; + } else if (isLerpable(value)) { + return callLerpable; } } return undefined; diff --git a/cocos/animation/cross-fade.ts b/cocos/animation/cross-fade.ts index 896262275b..dcae841d9e 100644 --- a/cocos/animation/cross-fade.ts +++ b/cocos/animation/cross-fade.ts @@ -13,7 +13,7 @@ interface IFadeState { export class CrossFade extends Playable { private _fadings: IFadeState[] = []; - constructor (public target: Node) { + constructor () { super(); this._unshiftDefault(); } @@ -26,9 +26,9 @@ export class CrossFade extends Playable { for (let i = 0; i < this._fadings.length; ++i) { if (absoluteWeight === 0) { for (let j = i; j < this._fadings.length; ++j) { - const fading = this._fadings[j]; - if (fading.state) { - this._directStopState(fading.state); + const follingFading = this._fadings[j]; + if (follingFading.state) { + this._directStopState(follingFading.state); } } this._fadings.splice(i); @@ -48,6 +48,11 @@ export class CrossFade extends Playable { // } } + /** + * 在指定时间内将从当前动画状态切换到指定的动画状态。 + * @param state 指定的动画状态。 + * @param duration 切换时间。 + */ public crossFade (state: AnimationState | null, duration: number) { let es = removeIf(this._fadings, (animation) => animation.state === state); if (es === undefined) { @@ -63,13 +68,9 @@ export class CrossFade extends Playable { } } - public sample () { - const currentFading = this._fadings[0]; - if (currentFading.state) { - currentFading.state.sample(); - } - } - + /** + * 停止我们淡入淡出的所有动画状态并停止淡入淡出。 + */ public onPause () { super.onPause(); for (const fading of this._fadings) { @@ -79,6 +80,9 @@ export class CrossFade extends Playable { } } + /** + * 恢复我们淡入淡出的所有动画状态并继续淡入淡出。 + */ public onResume () { super.onResume(); for (const fading of this._fadings) { @@ -88,6 +92,9 @@ export class CrossFade extends Playable { } } + /** + * 停止所有淡入淡出的动画状态并移除最后一个动画状态之外的所有动画状态。 + */ public onStop () { super.onStop(); const currentFading = this._fadings[0]; @@ -124,15 +131,7 @@ export class CrossFade extends Playable { } private _directPlayState (state: AnimationState) { - if (!state.clip) { - return; - } - - if (!state.curveLoaded) { - state.initialize(this.target); - } - - state.play(); state.weight = 1; + state.play(); } } diff --git a/cocos/animation/cubic-spline-value.ts b/cocos/animation/cubic-spline-value.ts new file mode 100644 index 0000000000..9a2007b35c --- /dev/null +++ b/cocos/animation/cubic-spline-value.ts @@ -0,0 +1,102 @@ + +import { ccclass, property } from '../core/data/class-decorator'; +import { Quat, Vec2, Vec3, Vec4 } from '../core/value-types'; +import * as vmath from '../core/vmath'; +import { ILerpable } from './types'; + +class CubicSplineValueBase implements ILerpable { + @property + public dataPoint: T; + + @property + public inTangent: T; + + @property + public outTangent: T; + + constructor (dataPoint: T, inTangent: T, outTangent: T) { + this.dataPoint = dataPoint; + this.inTangent = inTangent; + this.outTangent = outTangent; + } + + public getNoLerp () { + return this.dataPoint; + } + + public lerp (to: CubicSplineValueBase, t: number, dt: number) { + return this.dataPoint; + } +} + +type ScaleFx = (out: T, v: T, s: number) => T; +type ScaleAndAddFx = (out: T, v1: T, v2: T, s: number) => T; +function makeCubicSplineValueConstructor ( + name: string, + constructorX: new () => T, + scaleFx: ScaleFx, + scaleAndAdd: ScaleAndAddFx): typeof CubicSplineValueBase { + + let tempValue = new constructorX(); + let m0 = new constructorX(); + let m1 = new constructorX(); + + @ccclass(name) + class CubicSplineValueClass extends CubicSplineValueBase { + public lerp (to: CubicSplineValueClass, t: number, dt: number) { + const p0 = this.dataPoint; + const p1 = to.dataPoint; + // dt => t_k+1 - t_k + m0 = scaleFx(m0, this.outTangent, dt); + m1 = scaleFx(m1, to.inTangent, dt); + const t_3 = t * t * t; + const t_2 = t * t; + const f_0 = 2 * t_3 - 3 * t_2 + 1; + const f_1 = t_3 - 2 * t_2 + t; + const f_2 = -2 * t_3 + 3 * t_2; + const f_3 = t_3 - t_2; + tempValue = scaleFx(tempValue, p0, f_0); + tempValue = scaleAndAdd(tempValue, tempValue, m0, f_1); + tempValue = scaleAndAdd(tempValue, tempValue, p1, f_2); + tempValue = scaleAndAdd(tempValue, tempValue, m1, f_3); + return tempValue; + } + } + + return CubicSplineValueClass; +} + +export const CubicSplineVec2Value: typeof CubicSplineValueBase = makeCubicSplineValueConstructor( + 'cc.CubicSplineVec2Value', Vec2, vmath.vec2.scale, vmath.vec2.scaleAndAdd); +cc.CubicSplineVec2Value = CubicSplineVec2Value; + +export const CubicSplineVec3Value: typeof CubicSplineValueBase = makeCubicSplineValueConstructor( + 'cc.CubicSplineVec3Value', Vec3, vmath.vec3.scale, vmath.vec3.scaleAndAdd); +cc.CubicSplineVec3Value = CubicSplineVec3Value; + +export const CubicSplineVec4Value: typeof CubicSplineValueBase = makeCubicSplineValueConstructor( + 'cc.CubicSplineVec4Value', Vec4, vmath.vec4.scale, vmath.vec4.scaleAndAdd); +cc.CubicSplineVec4Value = CubicSplineVec4Value; + +export const CubicSplineQuatValue: typeof CubicSplineValueBase = makeCubicSplineValueConstructor( + 'cc.CubicSplineQuatValue', Quat, vmath.quat.scale, vmath.quat.scaleAndAdd); +cc.CubicSplineQuatValue = CubicSplineQuatValue; + +@ccclass('cc.CubicSplineNumberValue') +export class CubicSplineNumberValue extends CubicSplineValueBase { + public lerp (to: CubicSplineNumberValue, t: number, dt: number) { + const p0 = this.dataPoint; + const p1 = to.dataPoint; + // dt => t_k+1 - t_k + const m0 = this.outTangent * dt; + const m1 = to.inTangent * dt; + const t_3 = t * t * t; + const t_2 = t * t; + const f_0 = 2 * t_3 - 3 * t_2 + 1; + const f_1 = t_3 - 2 * t_2 + t; + const f_2 = -2 * t_3 + 3 * t_2; + const f_3 = t_3 - t_2; + return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3; + } +} +cc.CubicSplineNumberValue = CubicSplineNumberValue; diff --git a/cocos/animation/index.ts b/cocos/animation/index.ts index 44f2018d49..f35b592df4 100644 --- a/cocos/animation/index.ts +++ b/cocos/animation/index.ts @@ -6,3 +6,4 @@ export * from './animation-curve'; export * from './animation-clip'; export * from './animation-manager'; export * from './animation-state'; +export * from './cubic-spline-value'; diff --git a/cocos/animation/types.ts b/cocos/animation/types.ts index 680d20994d..eca247da6b 100644 --- a/cocos/animation/types.ts +++ b/cocos/animation/types.ts @@ -90,7 +90,8 @@ export class WrappedInfo { } export interface ILerpable { - lerp (to: this, t: number): this; + lerp (to: any, t: number, dt: number): any; + getNoLerp? (): any; } export function isLerpable (object: any): object is ILerpable { diff --git a/cocos/components/animation-component.ts b/cocos/components/animation-component.ts index 4a2fbd5af0..cd5500aa73 100644 --- a/cocos/components/animation-component.ts +++ b/cocos/components/animation-component.ts @@ -1,6 +1,7 @@ import { AnimationClip, AnimationState } from '../animation'; import { CrossFade } from '../animation/cross-fade'; +import { Playable } from '../animation/playable'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; import { Event, EventTarget } from '../core/event'; import { CallbacksInvoker, ICallbackTable } from '../core/event/callbacks-invoker'; @@ -50,140 +51,125 @@ export enum EventType { ccenum(EventType); /** - * @en The animation component is used to play back animations. - * - * Animation provide several events to register: - * - play : Emit when begin playing animation - * - stop : Emit when stop playing animation - * - pause : Emit when pause animation - * - resume : Emit when resume animation - * - lastframe : If animation repeat count is larger than 1, emit when animation play to the last frame - * - finished : Emit when finish playing animation - * - * @zh Animation 组件用于播放动画。 - * - * Animation 提供了一系列可注册的事件: - * - play : 开始播放时 - * - stop : 停止播放时 - * - pause : 暂停播放时 - * - resume : 恢复播放时 - * - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 - * - finished : 动画播放完成时 + * 动画组件管理动画状态来控制动画的播放。 + * 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件: + * - play : 开始播放时 + * - stop : 停止播放时 + * - pause : 暂停播放时 + * - resume : 恢复播放时 + * - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 + * - finished : 动画播放完成时 */ @ccclass('cc.AnimationComponent') @executionOrder(99) @executeInEditMode @menu('Components/AnimationComponent') export class AnimationComponent extends Component implements IEventTarget { - /** - * @en Animation will play the default clip when start game. - * @zh 在勾选自动播放或调用 play() 时默认播放的动画剪辑。 - */ - @property({ type: AnimationClip }) - get defaultClip () { - return this._defaultClip; - } - - set defaultClip (value) { - if (!CC_EDITOR || (cc.engine && cc.engine.isPlaying)) { - return; - } - - this._defaultClip = value; - - if (!value) { - return; - } - - const clips = this._clips; - - for (let i = 0, l = clips.length; i < l; i++) { - if (equalClips(value, clips[i])) { - return; - } - } - - this.addClip(value); - } - - /** - * @en Current played clip. - * @zh 当前播放的动画剪辑。 - */ - get currentClip () { - return this._currentClip; - } - - set currentClip (value) { - this._currentClip = value; - } - - /** - * @en - * Get or (re)set all the clips can be used in this animation. - * Once clips are (re)set, old animation states will be stoped. - * You shall no longer operate on them. - * @zh - * 获取或(重新)设置可以在此动画中使用的所有剪辑。 -     * 一旦(重新)设置了剪辑,旧的动画状态将被停止。 -     * 你将不再对旧动画进行操作。 + * 获取此动画组件的自有动画剪辑。 + * 动画组件开始运行时会为每个自有动画剪辑创建动画状态。 */ @property({ type: [AnimationClip] }) get clips () { return this._clips; } + /** + * 设置此动画组件的自有动画剪辑。 + * 设置时将移除已有的动画剪辑,并将其动画状态设为停止;若默认动画剪辑不在新的自有动画剪辑中,将被重置为空。 + */ set clips (value) { if (this._crossFade) { this._crossFade.clear(); } - for (const key of Object.keys(this._nameToState)) { - const state = this._nameToState[key]; - state.stop(); + // Remove state for old automatic clips. + for (const clip of this._clips) { + if (clip) { + this._removeStateOfAutomaticClip(clip); + } } - this._nameToState = {}; - this._currentClip = null; + // Create state for new clips. + for (const clip of value) { + if (clip) { + this.createState(clip); + } + } + // Default clip should be in the list of automatic clips. const newDefaultClip = value.find((clip) => equalClips(clip, this._defaultClip)); - if (newDefaultClip !== undefined) { + if (newDefaultClip) { this._defaultClip = newDefaultClip; + } else { + this._defaultClip = null; } + this._clips = value; - this._createStates(); + } + + /** + * 获取默认动画剪辑。 + * @see [[playOnLoad]] + */ + @property({ type: AnimationClip }) + get defaultClip () { + return this._defaultClip; + } + + /** + * 设置默认动画剪辑。当指定的剪辑不在 `this.clips` 中时会被自动添加至 `this.clips`。 + */ + set defaultClip (value) { + this._defaultClip = value; + if (!value) { + return; + } + const isBoundedDefaultClip = this._clips.findIndex((clip) => equalClips(clip, value)) >= 0; + if (!isBoundedDefaultClip) { + this._clips.push(value); + this.createState(value); + } + } + + get currentPlaying () { + return this._currentPlaying; } public static EventType = EventType; - public _callbackTable: ICallbackTable = createMap(true); /** - * @en Whether the animation should auto play the default clip when start game. - * @zh 是否在运行游戏后自动播放默认动画剪辑。 + * 是否在动画组件开始运行时自动播放默认动画剪辑。 */ @property public playOnLoad = false; - private _crossFade: CrossFade | null = null; - private _nameToState: { [name: string]: AnimationState; } = createMap(true); - private _didInit = false; - private _currentClip: AnimationClip | null = null; + public _callbackTable: ICallbackTable = createMap(true); + + private _crossFade = new CrossFade(); + + private _nameToState: { [name: string]: AnimationState; } = createMap(true); - /** - * @en All the clips used in this animation. - * @zh 通过脚本可以访问并播放的 AnimationClip 列表。 - */ @property({ type: [AnimationClip] }) private _clips: Array<(AnimationClip | null)> = []; @property private _defaultClip: AnimationClip | null = null; + private _currentPlaying: Playable = this._crossFade; + constructor () { super(); } + public onLoad () { + this.clips = this._clips; + } + public start () { - this._init(); - this._startCrossFade(); + for (const stateName of Object.keys(this._nameToState)) { + const state = this._nameToState[stateName]; + state.initialize(this.node); + } + cc.director.getAnimationManager().addCrossFade(this._crossFade); + this._crossFade.play(); if (!CC_EDITOR && this.playOnLoad && this._defaultClip) { this.crossFade(this._defaultClip.name, 0); } @@ -206,7 +192,6 @@ export class AnimationComponent extends Component implements IEventTarget { this._crossFade.stop(); cc.director.getAnimationManager().removeCrossFade(this._crossFade); this._crossFade.stop(); - this._crossFade = null; } } @@ -224,25 +209,48 @@ export class AnimationComponent extends Component implements IEventTarget { * ``` */ public play (name?: string, startTime = 0) { - const state = this.crossFade(name); + if (!name) { + if (!this._defaultClip) { + return null; + } else { + name = this._defaultClip.name; + } + } + const state = this._nameToState[name]; if (state) { - state.time = startTime; + this._currentPlaying.stop(); + this._currentPlaying = state; + state.setTime(startTime); + state.play(); } return state; } - public crossFade (name?: string, duration = 0.3) { - const state = this.getAnimationState(name || (this._defaultClip && this._defaultClip.name) || ''); - this._crossFade!.crossFade(state, duration); - return state; + public crossFade (name: string, duration = 0.3) { + const state = this._nameToState[name]; + if (state) { + if (this._currentPlaying !== this._crossFade) { + this._currentPlaying.stop(); + } + this._currentPlaying = this._crossFade; + this._crossFade.crossFade(state, duration); + } } /** - * @en Returns the animation state named name. If no animation with the specified name, the function will return null. - * @zh 获取当前或者指定的动画状态,如果未找到指定动画剪辑则返回 null。 + * 获取指定的动画状态。 + * @deprecated 请使用 `this.getState`。 */ public getAnimationState (name: string) { - this._init(); + return this.getState(name); + } + + /** + * 获取指定的动画状态。 + * @param name 动画状态的名称。 + * @returns 不存在指定名称的动画状态时返回空,否则返回指定的动画状态。 + */ + public getState (name: string) { const state = this._nameToState[name]; if (state && !state.curveLoaded) { state.initialize(this.node); @@ -251,42 +259,43 @@ export class AnimationComponent extends Component implements IEventTarget { } /** - * @en Adds a clip to the animation with name newName. If a clip with that name already exists it will be replaced with the new clip. - * @zh 添加动画剪辑,并且可以重新设置该动画剪辑的名称。 - * @param clip 要添加的动画剪辑 - * @return 能够完全控制动画片段的 AnimationState + * 使用指定的动画剪辑创建一个动画状态,并将其命名为指定的名称。 + * 若指定名称的动画状态已存在,已存在的动画状态将先被设为停止并被移除。 + * @param clip 动画剪辑。 + * @param name 动画状态的名称,若未指定,则使用动画剪辑的名称。 + * @returns 新创建的动画状态。 */ - public addClip (clip: AnimationClip, newName?: string): AnimationState | undefined { - if (!clip) { - warnID(3900); - return; - } - this._init(); + public createState (clip: AnimationClip, name?: string) { + name = name || clip.name; + this.removeState(name); - // add clip + return this._doCreateState(clip, name); + } + + /** + * 停止并移除指定名称的动画状态。 + * @param name 动画状态的名称。 + */ + public removeState (name: string) { + const state = this._nameToState[name]; + if (state) { + state.stop(); + delete this._nameToState[name]; + } + } + + /** + * 添加一个动画剪辑到 `this.clips`中并以此剪辑创建动画状态。 + * @param clip 动画剪辑。 + * @param name 动画状态的名称,若未指定,则使用动画剪辑的名称。 + * @returns 新创建的动画状态。 + * @deprecated 请使用 `this.createState`. + */ + public addClip (clip: AnimationClip, name?: string): AnimationState { if (!ArrayUtils.contains(this._clips, clip)) { this._clips.push(clip); } - - // replace same name clip - newName = newName || clip.name; - const oldState = this._nameToState[newName]; - if (oldState) { - if (oldState.clip === clip) { - return oldState; - } - else { - const index = this._clips.indexOf(oldState.clip); - if (index !== -1) { - this._clips.splice(index, 1); - } - } - } - - // replace state - const newState = new AnimationState(clip, newName); - this._nameToState[newName] = newState; - return newState; + return this.createState(clip, name); } /** @@ -296,17 +305,12 @@ export class AnimationComponent extends Component implements IEventTarget { * But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null * @zh * 从动画列表中移除指定的动画剪辑,
- * 如果依赖于 clip 的 AnimationState 正在播放或者 clip 是 defaultClip 的话,默认是不会删除 clip 的。
- * 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。
- * @param {Boolean} force - 如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。 + * 如果依赖于 clip 的 AnimationState 正在播放或者 clip 是 defaultClip 的话,默认是不会删除 clip 的。 + * 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。 + * @param {Boolean} [force=false] - If force is true, then will always remove the clip and any animation states based on it. + * @deprecated 请使用 `this.removeState`. */ - public removeClip (clip: AnimationClip, force: boolean = false) { - if (!clip) { - warnID(3901); - return; - } - this._init(); - + public removeClip (clip: AnimationClip, force?: boolean) { let state: AnimationState | undefined; for (const name of Object.keys(this._nameToState)) { state = this._nameToState[name]; @@ -365,7 +369,6 @@ export class AnimationComponent extends Component implements IEventTarget { * ``` */ public on (type: string, callback: (state: AnimationState) => void, target?: Object) { - this._init(); const ret = EventTarget.prototype.on.call(this, type, callback, target); if (type === 'lastframe') { for (const stateName of Object.keys(this._nameToState)) { @@ -390,8 +393,6 @@ export class AnimationComponent extends Component implements IEventTarget { * ``` */ public off (type: string, callback: Function, target?: Object) { - this._init(); - if (type === 'lastframe') { const nameToState = this._nameToState; for (const name of Object.keys(nameToState)) { @@ -417,53 +418,36 @@ export class AnimationComponent extends Component implements IEventTarget { public removeAll (keyOrTarget?: string | Object | undefined): void {} public emit (key: string, ...args: any[]): void {} - /////////////////////////////////////////////////////////////////////////////// - // Internal Methods - /////////////////////////////////////////////////////////////////////////////// - - // Dont forget to call _init before every actual process in public methods. - // Just invoking _init by onLoad is not enough because onLoad is called only if the entity is active. - - private _init () { - if (this._didInit) { - return; - } - this._didInit = true; - this._crossFade = new CrossFade(this.node); - this._createStates(); - } - - private _startCrossFade () { - if (!this._crossFade) { - return; - } - cc.director.getAnimationManager().addCrossFade(this._crossFade); - this._crossFade.play(); - } - - private _createStates () { - this._nameToState = createMap(true); - // Create animation states. - for (const clip of this._clips) { - if (clip) { - const state = this._createState(clip); - if (CC_EDITOR) { - state.initialize(this.node); - } + private _getStateByNameOrDefaultClip (name?: string) { + if (!name) { + if (!this._defaultClip) { + return null; + } else { + name = this._defaultClip.name; } } - const isDefaultClipBounded = this._clips.findIndex((clip) => equalClips(clip, this._defaultClip)) >= 0; - if (this._defaultClip && !isDefaultClipBounded) { - const state = this._createState(this._defaultClip); - if (CC_EDITOR) { - state.initialize(this.node); - } + const state = this._nameToState[name]; + if (state) { + return state; + } else { + return null; } } - private _createState (clip: AnimationClip, name?: string) { + private _removeStateOfAutomaticClip (clip: AnimationClip) { + const state = this._nameToState[name]; + if (state && equalClips(clip, state.clip)) { + state.stop(); + delete this._nameToState[name]; + } + } + + private _doCreateState (clip: AnimationClip, name: string) { const state = new AnimationState(clip, name); state._setEventTarget(this); + if (this.node) { + state.initialize(this.node); + } this._nameToState[state.name] = state; return state; }