diff --git a/cocos/animation/animation-animator.ts b/cocos/animation/animation-animator.ts new file mode 100644 index 0000000000..93935d59b7 --- /dev/null +++ b/cocos/animation/animation-animator.ts @@ -0,0 +1,228 @@ +import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; +import { MutableForwardIterator } from '../core/utils/array'; +import { Node } from '../scene-graph'; +import { LegacyAnimationClip } from './animation-clip'; +import { EventAnimCurve, EventInfo } from './animation-curve'; +import { LegacyAnimationState } from './animation-state'; +import { Playable } from './playable'; +import { WrapModeMask } from './types'; + +/** + * The actual animator for Animation Component. + */ +export class AnimationAnimator extends Playable { + private _anims = new MutableForwardIterator([]); + + constructor (public target: Node, public animation: LegacyAnimationClip) { + super(); + } + + public playState (state: LegacyAnimationState, startTime: number) { + if (!state.clip) { + return; + } + + if (!state.curveLoaded) { + initClipData(this.target, state); + } + + state.animator = this; + state.play(); + + if (typeof startTime === 'number') { + state.setTime(startTime); + } + + this.play(); + } + + public stopStatesExcept (state: LegacyAnimationState) { + const iterator = this._anims; + const array = iterator.array; + for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { + const anim = array[iterator.i]; + if (anim === state) { + continue; + } + + this.stopState(anim); + } + } + + public addAnimation (anim) { + const index = this._anims.array.indexOf(anim); + if (index === -1) { + this._anims.push(anim); + } + + anim._setEventTarget(this.animation); + } + + public removeAnimation (anim) { + const index = this._anims.array.indexOf(anim); + if (index >= 0) { + this._anims.fastRemoveAt(index); + + if (this._anims.array.length === 0) { + this.stop(); + } + } + else { + cc.errorID(3908); + } + + anim.animator = null; + } + + public sample () { + const iterator = this._anims; + const array = iterator.array; + for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { + const anim = array[iterator.i]; + anim.sample(); + } + } + + public stopState (state: LegacyAnimationState) { + if (state) { + state.stop(); + } + } + + public pauseState (state: LegacyAnimationState) { + if (state) { + state.pause(); + } + } + + public resumeState (state: LegacyAnimationState) { + if (state) { + state.resume(); + } + + if (this.isPaused) { + this.resume(); + } + } + + public setStateTime (state: LegacyAnimationState, time: number): void; + + public setStateTime (time: number): void; + + public setStateTime (state: LegacyAnimationState | number, time?: number) { + if (time !== undefined) { + (state as LegacyAnimationState).setTime(time); + (state as LegacyAnimationState).sample(); + } + else { + for (const anim of this._anims.array) { + anim.setTime(state as number); + anim.sample(); + } + } + } + + public onStop () { + const iterator = this._anims; + const array = iterator.array; + for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { + const anim = array[iterator.i]; + anim.stop(); + } + } + + public onPause () { + for (const anim of this._anims.array) { + anim.pause(); + // need to unbind animator to anim, or it maybe cannot be gc. + anim.animator = null; + } + } + + public onResume () { + for (const anim of this._anims.array) { + // rebind animator to anim + anim.animator = this; + + anim.resume(); + } + } + + private _reloadClip (state: LegacyAnimationState) { + initClipData(this.target, state); + } +} + +// 这个方法应该是 SampledAnimCurve 才能用 +function createBatchedProperty (propPath, firstDotIndex, mainValue, animValue) { + mainValue = mainValue.clone(); + let nextValue = mainValue; + let leftIndex = firstDotIndex + 1; + let rightIndex = propPath.indexOf('.', leftIndex); + + // scan property path + while (rightIndex !== -1) { + const nextName = propPath.slice(leftIndex, rightIndex); + nextValue = nextValue[nextName]; + leftIndex = rightIndex + 1; + rightIndex = propPath.indexOf('.', leftIndex); + } + const lastPropName = propPath.slice(leftIndex); + nextValue[lastPropName] = animValue; + + return mainValue; +} + +if (CC_TEST) { + cc._Test.createBatchedProperty = createBatchedProperty; +} + +function initClipData (root, state) { + const clip = state.clip; + + state.duration = clip.duration; + state.speed = clip.speed; + state.wrapMode = clip.wrapMode; + state.frameRate = clip.sample; + + if ((state.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop) { + state.repeatCount = Infinity; + } + else { + state.repeatCount = 1; + } + + const curves = state.curves = clip.createCurves(state, root); + + // events curve + + const events = clip.events; + + if (!CC_EDITOR && events) { + let curve; + + for (let i = 0, l = events.length; i < l; i++) { + if (!curve) { + curve = new EventAnimCurve(); + curve.target = root; + curves.push(curve); + } + + const eventData = events[i]; + const ratio = eventData.frame / state.duration; + + let eventInfo; + const index = binarySearch(curve.ratios, ratio); + if (index >= 0) { + eventInfo = curve.events[index]; + } + else { + eventInfo = new EventInfo(); + curve.ratios.push(ratio); + curve.events.push(eventInfo); + } + + eventInfo.add(eventData.func, eventData.params); + } + } +} diff --git a/cocos/animation/animation-clip.ts b/cocos/animation/animation-clip.ts index e69de29bb2..8c736e9ae3 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/animation/animation-clip.ts @@ -0,0 +1,292 @@ +import { Asset, SpriteFrame } from '../assets'; +import { ccclass, property } from '../core/data/class-decorator'; +import Quat, { quat } from '../core/value-types/quat'; +import Vec3, { v3 } from '../core/value-types/vec3'; +import { lerp } from '../core/vmath'; +import { find, Node } from '../scene-graph'; +import { CurveValue, DynamicAnimCurve, EasingMethodName, ICurveTarget, LerpFunction, quickFindIndex } from './animation-curve'; +import { MotionPath, sampleMotionPaths } from './motion-path-helper'; +import { WrapMode } from './types'; + +interface IAnimationEvent { + frame: number; + func: string; + params: string[]; +} + +interface IKeyframe { + frame: number; + value: CurveValue; + curve?: EasingMethodName | number[]; + motionPath?: MotionPath; +} + +interface ICurveData { + props?: { + [propertyName: string]: IKeyframe[]; + }; + comps?: { + [componentName: string]: { + [propertyName: string]: IKeyframe[]; + }; + }; + paths?: { + [path: string]: ICurveData; + }; +} + +interface ILerpable { + lerp (to: this, t: number): this; +} + +function isLerpable (object: any): object is ILerpable { + return object.lerp; +} + +@ccclass('cc.LegacyAnimationClip') +export class LegacyAnimationClip extends Asset { + + /** + * !#en Duration of this animation. + * !#zh 动画的持续时间。 + */ + get duration () { + return this._duration; + } + + /** + * !#en Crate clip with a set of sprite frames + * !#zh 使用一组序列帧图片来创建动画剪辑 + * @example + * const clip = cc.AnimationClip.createWithSpriteFrames(spriteFrames, 10); + * + */ + public static createWithSpriteFrames (spriteFrames: SpriteFrame[], sample: number) { + if (!Array.isArray(spriteFrames)) { + cc.errorID(3905); + return null; + } + + const clip = new LegacyAnimationClip(); + clip.sample = sample || clip.sample; + + clip._duration = spriteFrames.length / clip.sample; + + const frames: IKeyframe[] = []; + const step = 1 / clip.sample; + + for (let i = 0, l = spriteFrames.length; i < l; i++) { + frames[i] = { frame: (i * step), value: spriteFrames[i] }; + } + + clip.curveData = { + comps: { + // component + 'cc.Sprite': { + // component properties + spriteFrame: frames, + }, + }, + }; + + return clip; + } + + /** + * !#en FrameRate of this animation. + * !#zh 动画的帧速率。 + */ + @property + public sample = 60; + + /** + * !#en Speed of this animation. + * !#zh 动画的播放速度。 + */ + @property + public speed = 1; + + /** + * !#en WrapMode of this animation. + * !#zh 动画的循环模式。 + */ + @property + public wrapMode = WrapMode.Normal; + + /** + * !#en Curve data. + * !#zh 曲线数据。 + * @example {@link cocos2d/core/animation-clip/curve-data.js} + */ + @property({visible: false}) + public curveData: ICurveData = {}; + + /** + * !#en Event data. + * !#zh 事件数据。 + * @example {@link cocos2d/core/animation-clip/event-data.js} + * @typescript events: {frame: number, func: string, params: string[]}[] + */ + @property({visible: false}) + public events: IAnimationEvent[] = []; + + @property + private _duration = 0; + + private frameRate = 0; + + public onLoad () { + this._duration = this.duration; + this.speed = this.speed; + this.wrapMode = this.wrapMode; + this.frameRate = this.sample; + } + + public createPropCurve (target: ICurveTarget, propPath: string, keyframes: IKeyframe[]) { + const motionPaths: Array<(MotionPath | undefined)> = []; + const isMotionPathProp = target instanceof cc.Node && propPath === 'position'; + + const curve = new DynamicAnimCurve(); + + // 缓存目标对象,所以 Component 必须一开始都创建好并且不能运行时动态替换…… + curve.target = target; + curve.prop = propPath; + + // For each keyframe. + for (const keyframe of keyframes) { + const ratio = keyframe.frame / this.duration; + curve.ratios.push(ratio); + + if (isMotionPathProp) { + motionPaths.push(keyframe.motionPath); + } + + const curveValue = keyframe.value; + curve.values.push(curveValue); + + const curveTypes = keyframe.curve; + if (curveTypes) { + if (typeof curveTypes === 'string') { + curve.types.push(curveTypes); + continue; + } else if (Array.isArray(curveTypes)) { + if (curveTypes[0] === curveTypes[1] && + curveTypes[2] === curveTypes[3]) { + curve.types.push(DynamicAnimCurve.Linear); + } else { + curve.types.push(DynamicAnimCurve.Bezier(curveTypes)); + } + continue; + } + } + curve.types.push(DynamicAnimCurve.Linear); + } + + if (isMotionPathProp) { + sampleMotionPaths(motionPaths, curve, this.duration, this.sample, target); + } + + // if every piece of ratios are the same, we can use the quick function to find frame index. + const ratios = curve.ratios; + let currRatioDif; + let lastRatioDif; + let canOptimize = true; + const EPSILON = 1e-6; + for (let i = 1, l = ratios.length; i < l; i++) { + currRatioDif = ratios[i] - ratios[i - 1]; + if (i === 1) { + lastRatioDif = currRatioDif; + } + else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) { + canOptimize = false; + break; + } + } + + if (canOptimize) { + curve._findFrameIndex = quickFindIndex; + } + + // Setup the lerp function. + const firstValue = curve.values[0]; + if (!curve._lerp && firstValue !== undefined) { + if (typeof firstValue === 'number') { + curve._lerp = lerpNumber; + } else if (firstValue instanceof cc.Quat) { + curve._lerp = lerpQuat; + } else if (firstValue instanceof cc.Vec2 || firstValue instanceof cc.Vec3) { + curve._lerp = lerpVector; + } else if (isLerpable(firstValue)) { + curve._lerp = lerpObject; + } + } + + return curve; + } + + public createTargetCurves (target: ICurveTarget, curveData: ICurveData, curves: DynamicAnimCurve[]) { + const propsData = curveData.props; + if (propsData) { + for (const propPath of Object.keys(propsData)) { + const data = propsData[propPath]; + const curve = this.createPropCurve(target, propPath, data); + curves.push(curve); + } + } + + const compsData = curveData.comps; + if (compsData) { + for (const compName of Object.keys(compsData)) { + const comp = target.getComponent(compName); + if (!comp) { + continue; + } + const compData = compsData[compName]; + for (const propPath of Object.keys(compData)) { + const data = compData[propPath]; + const curve = this.createPropCurve(comp, propPath, data); + curves.push(curve); + } + } + } + } + + public createCurves (state, root: Node) { + const curveData = this.curveData; + const childrenCurveDatas = curveData.paths; + const curves = []; + + this.createTargetCurves(root, curveData, curves); + if (childrenCurveDatas) { + for (const namePath of Object.keys(childrenCurveDatas)) { + const target = find(namePath, root); + if (!target) { + continue; + } + const childCurveDatas = childrenCurveDatas[namePath]; + this.createTargetCurves(target, childCurveDatas, curves); + } + } + + return curves; + } +} + +const lerpNumber = lerp; +const lerpQuat = (() => { + const out = quat(); + return (from: Quat, to: Quat, t: number) => { + return from.lerp(to, t, out); + }; +})(); +const lerpVector = (() => { + const out = v3(); + return (from: Vec3, to: Vec3, t: number) => { + return from.lerp(to, t, out); + }; +})(); +function lerpObject (from: ILerpable, to: ILerpable, t: number): ILerpable { + return from.lerp(to, t); +} + +cc.LegacyAnimationClip = LegacyAnimationClip; diff --git a/cocos/animation/animation-curve.ts b/cocos/animation/animation-curve.ts new file mode 100644 index 0000000000..cd1d19880e --- /dev/null +++ b/cocos/animation/animation-curve.ts @@ -0,0 +1,367 @@ +import { Quat, ValueType, Vec3 } from '../core'; +import { ccclass, property } from '../core/data/class-decorator'; +import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; +import { quat } from '../core/value-types/quat'; +import { v3 } from '../core/value-types/vec3'; +import { bezierByTime } from './bezier'; +// import { easing } from './easing'; +import * as easing from './easing'; +import { WrapModeMask, WrappedInfo } from './types'; + +/** + * 动画数据类,相当于 AnimationClip。 + * 虽然叫做 AnimCurve,但除了曲线,可以保存任何类型的值。 + */ +@ccclass('cc.AnimCurve') +export class AnimCurve { + public onTimeChangedManually? (time: number, state): void; + + /** + * @param time + * @param ratio The normalized time specified as a number between 0.0 and 1.0 inclusive. + * @param state + */ + public sample (time: number, ratio: number, state) { + + } +} + +export type CurveValue = any; + +export interface ICurveTarget { + [x: string]: any; +} + +export type LerpFunction = (from: CurveValue, to: CurveValue, t: number) => CurveValue; + +export type FrameFinder = (framevalues: number[], value: number) => number; + +export type LinearType = null; + +export type BezierType = [number, number, number, number]; + +export type EasingMethodName = keyof (typeof easing); + +export type CurveType = LinearType | BezierType | EasingMethodName; + +@ccclass('cc.DynamicAnimCurve') +export class DynamicAnimCurve extends AnimCurve { + public static Linear = null; + + public static Bezier (controlPoints: number[]) { + return controlPoints as BezierType; + } + + public static _lerpNumber (from: number, to: number, t: number) { + return from + (to - from) * t; + } + + public static _lerpObject (from: ValueType, to: ValueType, t: number) { + return from.lerp(to, t); + } + + public static _lerpQuat (from: Quat, to: Quat, t: number) { + return from.lerp(to, t, _lerpQuatResult); + } + + public static _lerpVector (from: Vec3, to: Vec3, t: number) { + return from.lerp(to, t, _lerpVec3Result); + } + + /** + * The object being animated. + */ + @property + public target: ICurveTarget | null = null; + + /** + * The name of the property being animated. + */ + @property + public prop: string = ''; + + /** + * The values of the keyframes. (y) + */ + @property + public values: CurveValue[] = []; + + /** + * The keyframe ratio of the keyframe specified as a number between 0.0 and 1.0 inclusive. (x) + */ + @property + public ratios: number[] = []; + + @property + public types: CurveType[] = []; + + /** + * Lerp function used. If undefined, no lerp is performed. + */ + public _lerp: LerpFunction | undefined = undefined; + + public _findFrameIndex: FrameFinder = binarySearch; + + public sample (time: number, ratio: number, state) { + const values = this.values; + const ratios = this.ratios; + const frameCount = ratios.length; + if (frameCount === 0) { + return; + } + + // evaluate value + let value: CurveValue; + let index = this._findFrameIndex(ratios, ratio); + if (index >= 0) { + value = values[index]; + } else { + index = ~index; + if (index <= 0) { + value = values[0]; + } else if (index >= frameCount) { + value = values[frameCount - 1]; + } else { + const fromVal = values[index - 1]; + if (!this._lerp) { + value = fromVal; + } else { + const fromRatio = ratios[index - 1]; + const toRatio = ratios[index]; + const type = this.types[index - 1]; + let ratioBetweenFrames = (ratio - fromRatio) / (toRatio - fromRatio); + if (type) { + ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type); + } + // calculate value + const toVal = values[index]; + value = this._lerp(fromVal, toVal, ratioBetweenFrames); + } + } + } + + if (this.target) { + this.target[this.prop] = value; + } + } +} + +const _lerpQuatResult = quat(); +const _lerpVec3Result = v3(); + +export class EventInfo { + public events: any[] = []; + + /** + * @param func event function + * @param params event params + */ + public add (func: string, params: any[]) { + this.events.push({ + func: func || '', + params: params || [], + }); + } +} + +@ccclass('cc.EventAnimCurve') +export class EventAnimCurve extends AnimCurve { + @property + public target: ICurveTarget | null = null; + + @property + public ratios: number[] = []; + + @property + public events: EventInfo[] = []; + + @property + private _wrappedInfo = new WrappedInfo(); + + @property + private _lastWrappedInfo: WrappedInfo | null = null; + + @property + private _ignoreIndex: number = NaN; + + public sample (time: number, ratio: number, state) { + const length = this.ratios.length; + + const currentWrappedInfo = state.getWrappedInfo(state.time, this._wrappedInfo); + let direction = currentWrappedInfo.direction; + let currentIndex = binarySearch(this.ratios, currentWrappedInfo.ratio); + if (currentIndex < 0) { + currentIndex = ~currentIndex - 1; + + // if direction is inverse, then increase index + if (direction < 0) { currentIndex += 1; } + } + + if (this._ignoreIndex !== currentIndex) { + this._ignoreIndex = NaN; + } + + currentWrappedInfo.frameIndex = currentIndex; + + if (!this._lastWrappedInfo) { + this._fireEvent(currentIndex); + this._lastWrappedInfo = new WrappedInfo(currentWrappedInfo); + return; + } + + const wrapMode = state.wrapMode; + const currentIterations = this._wrapIterations(currentWrappedInfo.iterations); + + const lastWrappedInfo = this._lastWrappedInfo; + let lastIterations = this._wrapIterations(lastWrappedInfo.iterations); + let lastIndex = lastWrappedInfo.frameIndex; + const lastDirection = lastWrappedInfo.direction; + + const interationsChanged = lastIterations !== -1 && currentIterations !== lastIterations; + + if (lastIndex === currentIndex && interationsChanged && length === 1) { + this._fireEvent(0); + } else if (lastIndex !== currentIndex || interationsChanged) { + direction = lastDirection; + + do { + if (lastIndex !== currentIndex) { + if (direction === -1 && lastIndex === 0 && currentIndex > 0) { + if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { + direction *= -1; + } else { + lastIndex = length; + } + lastIterations++; + } else if (direction === 1 && lastIndex === length - 1 && currentIndex < length - 1) { + if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { + direction *= -1; + } else { + lastIndex = -1; + } + lastIterations++; + } + + if (lastIndex === currentIndex) { + break; + } + if (lastIterations > currentIterations) { + break; + } + } + + lastIndex += direction; + + cc.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); + } while (lastIndex !== currentIndex && lastIndex > -1 && lastIndex < length); + } + + this._lastWrappedInfo.set(currentWrappedInfo); + } + + public onTimeChangedManually (time: number, state) { + this._lastWrappedInfo = null; + this._ignoreIndex = NaN; + + const info = state.getWrappedInfo(time, this._wrappedInfo); + const direction = info.direction; + let frameIndex = binarySearch(this.ratios, info.ratio); + + // only ignore when time not on a frame index + if (frameIndex < 0) { + frameIndex = ~frameIndex - 1; + + // if direction is inverse, then increase index + if (direction < 0) { frameIndex += 1; } + + this._ignoreIndex = frameIndex; + } + } + + private _wrapIterations (iterations: number) { + if (iterations - (iterations | 0) === 0) { + iterations -= 1; + } + return iterations | 0; + } + + private _fireEvent (index: number) { + if (index < 0 || index >= this.events.length || this._ignoreIndex === index) { + return; + } + + const eventInfo = this.events[index]; + const events = eventInfo.events; + + if (!this.target || !this.target.isValid) { + return; + } + + const components = this.target._components; + + for (const event of events) { + const funcName = event.func; + for (const component of components) { + const func = component[funcName]; + if (func) { + func.apply(component, event.params); + } + } + } + } +} + +/** + * Compute a new ratio by curve type + * @param ratio - The origin ratio + * @param type - If it's Array, then ratio will be computed with bezierByTime. + * If it's string, then ratio will be computed with cc.easing function + */ +export function computeRatioByType (ratio: number, type: CurveType) { + if (typeof type === 'string') { + const func = cc.easing[type]; + if (func) { + ratio = func(ratio); + } + else { + cc.errorID(3906, type); + } + } + else if (Array.isArray(type)) { + // bezier curve + ratio = bezierByTime(type, ratio); + } + + return ratio; +} + +/** + * 当每两帧之前的间隔都一样的时候可以使用此函数快速查找 index + */ +export function quickFindIndex (ratios: number[], ratio: number) { + const length = ratios.length - 1; + + if (length === 0) { return 0; } + + const start = ratios[0]; + if (ratio < start) { return 0; } + + const end = ratios[length]; + if (ratio > end) { return length; } + + ratio = (ratio - start) / (end - start); + + const eachLength = 1 / length; + const index = ratio / eachLength; + const floorIndex = index | 0; + const EPSILON = 1e-6; + + if ((index - floorIndex) < EPSILON) { + return floorIndex; + } + else if ((floorIndex + 1 - index) < EPSILON) { + return floorIndex + 1; + } + + return ~(floorIndex + 1); +} diff --git a/cocos/animation/animation-manager.ts b/cocos/animation/animation-manager.ts new file mode 100644 index 0000000000..cf35b9e240 --- /dev/null +++ b/cocos/animation/animation-manager.ts @@ -0,0 +1,64 @@ +import { ccclass } from '../core/data/class-decorator'; +import { errorID } from '../core/platform/CCDebug'; +import { Node } from '../scene-graph'; +import { LegacyAnimationState } from './animation-state'; + +@ccclass +export class AnimationManager { + private _anims = new cc.js.array.MutableForwardIterator([]); + private _delayEvents: Array<{target: Node; func: string; args: any[]; }> = []; + + constructor () { + if (cc.director._scheduler) { + cc.director._scheduler.enableForTarget(this); + } + } + + public update (dt: number) { + const iterator = this._anims; + const array = iterator.array; + for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { + const anim = array[iterator.i]; + if (anim._isPlaying && !anim._isPaused) { + anim.update(dt); + } + } + + const events = this._delayEvents; + for (let i = 0, l = events.length; i < l; i++) { + const event = events[i]; + event.target[event.func].apply(event.target, event.args); + } + events.length = 0; + } + + public destruct () { + + } + + public addAnimation (anim: LegacyAnimationState) { + const index = this._anims.array.indexOf(anim); + if (index === -1) { + this._anims.push(anim); + } + } + + public removeAnimation (anim: LegacyAnimationState) { + const index = this._anims.array.indexOf(anim); + if (index >= 0) { + this._anims.fastRemoveAt(index); + } else { + errorID(3907); + } + } + + public pushDelayEvent (target: Node, func: string, args: any[]) { + this._delayEvents.push({ + target, + func, + args, + }); + } +} + +cc.AnimationManager = AnimationManager; diff --git a/cocos/animation/animation-state.ts b/cocos/animation/animation-state.ts new file mode 100644 index 0000000000..2a7e173c23 --- /dev/null +++ b/cocos/animation/animation-state.ts @@ -0,0 +1,463 @@ +import { Node } from '../scene-graph'; +import { AnimationAnimator } from './animation-animator'; +import { LegacyAnimationClip } from './animation-clip'; +import { AnimCurve } from './animation-curve'; +import { Playable } from './playable'; +import { WrapMode, WrapModeMask, WrappedInfo } from './types'; + +/** + * !#en + * The AnimationState gives full control over animation playback process. + * In most cases the Animation Component is sufficient and easier to use. Use the AnimationState if you need full control. + * !#zh + * AnimationState 完全控制动画播放过程。
+ * 大多数情况下 动画组件 是足够和易于使用的。如果您需要更多的动画控制接口,请使用 AnimationState。 + * + */ +export class LegacyAnimationState extends Playable { + + /** + * !#en The clip that is being played by this animation state. + * !#zh 此动画状态正在播放的剪辑。 + */ + get clip () { + return this._clip; + } + + /** + * !#en The name of the playing animation. + * !#zh 动画的名字 + */ + get name () { + return this._name; + } + + get length () { + return this.duration; + } + + get curveLoaded () { + return this.curves.length > 0; + } + + set curveLoaded (value: boolean) { + this.curves.length = 0; + } + + /** + * !#en + * Wrapping mode of the playing animation. + * Notice : dynamic change wrapMode will reset time and repeatCount property + * !#zh + * 动画循环方式。 + * 需要注意的是,动态修改 wrapMode 时,会重置 time 以及 repeatCount + * @default: WrapMode.Normal + */ + get wrapMode () { + return this.wrapMode; + } + + set wrapMode (value: WrapMode) { + this._wrapMode = value; + + if (CC_EDITOR) { return; } + + // dynamic change wrapMode will need reset time to 0 + this.time = 0; + + if (value & WrapModeMask.Loop) { + this.repeatCount = Infinity; + } + else { + this.repeatCount = 1; + } + } + + /** + * !#en The animation's iteration count property. + * + * A real number greater than or equal to zero (including positive infinity) representing the number of times + * to repeat the animation node. + * + * Values less than zero and NaN values are treated as the value 1.0 for the purpose of timing model + * calculations. + * + * !#zh 迭代次数,指动画播放多少次后结束, normalize time。 如 2.5(2次半) + * + * @property repeatCount + * @type {Number} + * @default 1 + */ + get repeatCount () { + return this._repeatCount; + } + + set repeatCount (value: number) { + this._repeatCount = value; + + const shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap; + const reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse; + if (value === Infinity && !shouldWrap && !reverse) { + this._process = this.simpleProcess; + } + else { + this._process = this.process; + } + } + + /** + * !#en The start delay which represents the number of seconds from an animation's start time to the start of + * the active interval. + * !#zh 延迟多少秒播放。 + * @default 0 + */ + get delay () { + return this._delay; + } + + set delay (value: number) { + this._delayTime = this._delay = value; + } + public animator: AnimationAnimator | null = null; + /** + * !#en The curves list. + * !#zh 曲线列表。 + */ + public curves: AnimCurve[] = []; + + // http://www.w3.org/TR/web-animations/#idl-def-AnimationTiming + + /** + * !#en The iteration duration of this animation in seconds. (length) + * !#zh 单次动画的持续时间,秒。 + * @readOnly + */ + public duration = 1; + + /** + * !#en The animation's playback speed. 1 is normal playback speed. + * !#zh 播放速率。 + * @default: 1.0 + */ + public speed = 1; + + /** + * !#en The current time of this animation in seconds. + * !#zh 动画当前的时间,秒。 + * @default 0 + */ + public time = 0; + + private _wrapMode = WrapMode.Normal; + + /** + * !#en The animation's iteration count property. + * + * A real number greater than or equal to zero (including positive infinity) representing the number of times + * to repeat the animation node. + * + * Values less than zero and NaN values are treated as the value 1.0 for the purpose of timing model + * calculations. + * + * !#zh 迭代次数,指动画播放多少次后结束, normalize time。 如 2.5(2次半) + * @default 1 + */ + private _repeatCount = 1; + + /** + * Mark whether the current frame is played. + * When set new time to animation state, we should ensure the frame at the specified time being played at next update. + */ + private _currentFramePlayed = false; + private _delay = 0; + private _delayTime = 0; + private _wrappedInfo = new WrappedInfo(); + private _lastWrappedInfo: WrappedInfo | null = null; + private _process = this.process; + private _target: Node | null = null; + private _lastframeEventOn = false; + private _clip: LegacyAnimationClip; + private _name: string; + private _lastIterations?: number; + + constructor (clip: LegacyAnimationClip, name?: string) { + super(); + this._clip = clip; + this._name = name || (clip && clip.name); + } + + public _emit (type, state) { + if (this._target && this._target.isValid) { + this._target.emit(type, type, state); + } + } + + public emit (...restargs: any[]) { + const args = new Array(restargs.length); + for (let i = 0, l = args.length; i < l; i++) { + args[i] = restargs[i]; + } + cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args); + } + + public on (type, callback, target) { + if (this._target && this._target.isValid) { + if (type === 'lastframe') { + this._lastframeEventOn = true; + } + return this._target.on(type, callback, target); + } + else { + return null; + } + } + + public once (type, callback, target) { + if (this._target && this._target.isValid) { + if (type === 'lastframe') { + this._lastframeEventOn = true; + } + return this._target.once(type, (event) => { + callback.call(target, event); + this._lastframeEventOn = false; + }); + } + else { + return null; + } + } + + public off (type, callback, target) { + if (this._target && this._target.isValid) { + if (type === 'lastframe') { + if (!this._target.hasEventListener(type)) { + this._lastframeEventOn = false; + } + } + this._target.off(type, callback, target); + } + } + + public _setEventTarget (target) { + this._target = target; + } + + public setTime (time: number) { + this._currentFramePlayed = false; + this.time = time || 0; + + const curves = this.curves; + for (let i = 0, l = curves.length; i < l; i++) { + const curve = curves[i]; + if (curve.onTimeChangedManually) { + curve.onTimeChangedManually(time, this); + } + } + } + + public update (delta: number) { + // calculate delay time + + if (this._delayTime > 0) { + this._delayTime -= delta; + if (this._delayTime > 0) { + // still waiting + return; + } + } + + // make first frame perfect + + // var playPerfectFirstFrame = (this.time === 0); + if (this._currentFramePlayed) { + this.time += (delta * this.speed); + } + else { + this._currentFramePlayed = true; + } + + this._process(); + } + + public _needRevers (currentIterations: number) { + const wrapMode = this.wrapMode; + let needRevers = false; + + if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { + const isEnd = currentIterations - (currentIterations | 0) === 0; + if (isEnd && (currentIterations > 0)) { + currentIterations -= 1; + } + + const isOddIteration = currentIterations & 1; + if (isOddIteration) { + needRevers = !needRevers; + } + } + if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { + needRevers = !needRevers; + } + return needRevers; + } + + public getWrappedInfo (time: number, info?: WrappedInfo) { + info = info || new WrappedInfo(); + + let stopped = false; + const duration = this.duration; + const repeatCount = this.repeatCount; + + let currentIterations = time > 0 ? (time / duration) : -(time / duration); + if (currentIterations >= repeatCount) { + currentIterations = repeatCount; + + stopped = true; + let tempRatio = repeatCount - (repeatCount | 0); + if (tempRatio === 0) { + tempRatio = 1; // 如果播放过,动画不复位 + } + time = tempRatio * duration * (time > 0 ? 1 : -1); + } + + if (time > duration) { + const tempTime = time % duration; + time = tempTime === 0 ? duration : tempTime; + } + else if (time < 0) { + time = time % duration; + if (time !== 0) { time += duration; } + } + + let needRevers = false; + const shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap; + if (shouldWrap) { + needRevers = this._needRevers(currentIterations); + } + + let direction = needRevers ? -1 : 1; + if (this.speed < 0) { + direction *= -1; + } + + // calculate wrapped time + if (shouldWrap && needRevers) { + time = duration - time; + } + + info.ratio = time / duration; + info.time = time; + info.direction = direction; + info.stopped = stopped; + info.iterations = currentIterations; + + return info; + } + + public sample () { + const info = this.getWrappedInfo(this.time, this._wrappedInfo); + const curves = this.curves; + for (let i = 0, len = curves.length; i < len; i++) { + const curve = curves[i]; + curve.sample(info.time, info.ratio, this); + } + + return info; + } + + public process () { + // sample + const info = this.sample(); + + if (this._lastframeEventOn) { + let lastInfo; + if (!this._lastWrappedInfo) { + lastInfo = this._lastWrappedInfo = new WrappedInfo(info); + } else { + lastInfo = this._lastWrappedInfo; + } + + if (this.repeatCount > 1 && ((info.iterations | 0) > (lastInfo.iterations | 0))) { + this.emit('lastframe', this); + } + + lastInfo.set(info); + } + + if (info.stopped) { + this.stop(); + this.emit('finished', this); + } + } + + public simpleProcess () { + let time = this.time; + const duration = this.duration; + + if (time > duration) { + time = time % duration; + if (time === 0) { time = duration; } + } + else if (time < 0) { + time = time % duration; + if (time !== 0) { time += duration; } + } + + const ratio = time / duration; + + const curves = this.curves; + for (let i = 0, len = curves.length; i < len; i++) { + const curve = curves[i]; + curve.sample(time, ratio, this); + } + + if (this._lastframeEventOn) { + if (this._lastIterations === undefined) { + this._lastIterations = ratio; + } + + if ((this.time > 0 && this._lastIterations > ratio) || (this.time < 0 && this._lastIterations < ratio)) { + this.emit('lastframe', this); + } + + this._lastIterations = ratio; + } + } + + protected onPlay () { + // replay + this.setTime(0); + this._delayTime = this._delay; + + cc.director.getAnimationManager().addAnimation(this); + + if (this.animator) { + this.animator.addAnimation(this); + } + + this.emit('play', this); + } + + protected onStop () { + if (!this.isPaused) { + cc.director.getAnimationManager().removeAnimation(this); + } + + if (this.animator) { + this.animator.removeAnimation(this); + } + + this.emit('stop', this); + } + + protected onResume () { + cc.director.getAnimationManager().addAnimation(this); + this.emit('resume', this); + } + + protected onPause () { + cc.director.getAnimationManager().removeAnimation(this); + this.emit('pause', this); + } +} + +cc.LegacyAnimationState = LegacyAnimationState; diff --git a/cocos/animation/bezier.ts b/cocos/animation/bezier.ts new file mode 100644 index 0000000000..d6a5f9d1b6 --- /dev/null +++ b/cocos/animation/bezier.ts @@ -0,0 +1,156 @@ + +export function bezier (C1: number, C2: number, C3: number, C4: number, t: number) { + const t1 = 1 - t; + return C1 * t1 * t1 * t1 + + C2 * 3 * t1 * t1 * t + + C3 * 3 * t1 * t * t + + C4 * t * t * t; +} + +// var sin = Math.sin; +const cos = Math.cos; +const acos = Math.acos; +const max = Math.max; +// var atan2 = Math.atan2; +const pi = Math.PI; +const tau = 2 * pi; +const sqrt = Math.sqrt; + +function crt (v: number) { + if (v < 0) { + return -Math.pow(-v, 1 / 3); + } + else { + return Math.pow(v, 1 / 3); + } +} + +// Modified from http://jsbin.com/yibipofeqi/1/edit, optimized for animations. +// The origin Cardano's algorithm is based on http://www.trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm +function cardano (curve: number[], x: number) { + // align curve with the intersecting line: + // var line = {p1: {x: x, y: 0}, p2: {x: x, y: 1}}; + // var aligned = align(curve, line); + //// and rewrite from [a(1-t)^3 + 3bt(1-t)^2 + 3c(1-t)t^2 + dt^3] form + // pa = aligned[0].y, + // pb = aligned[1].y, + // pc = aligned[2].y, + // pd = aligned[3].y; + ////// curve = [{x:0, y:1}, {x: curve[0], y: 1-curve[1]}, {x: curve[2], y: 1-curve[3]}, {x:1, y:0}]; + const pa = x - 0; + const pb = x - curve[0]; + const pc = x - curve[2]; + const pd = x - 1; + + // to [t^3 + at^2 + bt + c] form: + const pa3 = pa * 3; + const pb3 = pb * 3; + const pc3 = pc * 3; + const d = (-pa + pb3 - pc3 + pd); + const rd = 1 / d; + const r3 = 1 / 3; + const a = (pa3 - 6 * pb + pc3) * rd; + const a3 = a * r3; + const b = (-pa3 + pb3) * rd; + const c = pa * rd; + // then, determine p and q: + const p = (3 * b - a * a) * r3; + const p3 = p * r3; + const q = (2 * a * a * a - 9 * a * b + 27 * c) / 27; + const q2 = q / 2; + // and determine the discriminant: + const discriminant = q2 * q2 + p3 * p3 * p3; + // and some reserved variables + let u1; + let v1; + let x1; + let x2; + let x3; + + // If the discriminant is negative, use polar coordinates + // to get around square roots of negative numbers + if (discriminant < 0) { + const mp3 = -p * r3; + const mp33 = mp3 * mp3 * mp3; + const r = sqrt(mp33); + // compute cosphi corrected for IEEE float rounding: + const t = -q / (2 * r); + const cosphi = t < -1 ? -1 : t > 1 ? 1 : t; + const phi = acos(cosphi); + const crtr = crt(r); + const t1 = 2 * crtr; + x1 = t1 * cos(phi * r3) - a3; + x2 = t1 * cos((phi + tau) * r3) - a3; + x3 = t1 * cos((phi + 2 * tau) * r3) - a3; + + // choose best percentage + if (0 <= x1 && x1 <= 1) { + if (0 <= x2 && x2 <= 1) { + if (0 <= x3 && x3 <= 1) { + return max(x1, x2, x3); + } + else { + return max(x1, x2); + } + } + else if (0 <= x3 && x3 <= 1) { + return max(x1, x3); + } + else { + return x1; + } + } + else { + if (0 <= x2 && x2 <= 1) { + if (0 <= x3 && x3 <= 1) { + return max(x2, x3); + } + else { + return x2; + } + } + else { + return x3; + } + } + } + else if (discriminant === 0) { + u1 = q2 < 0 ? crt(-q2) : -crt(q2); + x1 = 2 * u1 - a3; + x2 = -u1 - a3; + + // choose best percentage + if (0 <= x1 && x1 <= 1) { + if (0 <= x2 && x2 <= 1) { + return max(x1, x2); + } + else { + return x1; + } + } + else { + return x2; + } + } + // one real root, and two imaginary roots + else { + const sd = sqrt(discriminant); + u1 = crt(-q2 + sd); + v1 = crt(q2 + sd); + x1 = u1 - v1 - a3; + return x1; + } +} + +export function bezierByTime (controlPoints, x) { + const percent = cardano(controlPoints, x); // t + const p0y = 0; // a + const p1y = controlPoints[1]; // b + const p2y = controlPoints[3]; // c + const p3y = 1; // d + const t1 = 1 - percent; + return p0y * t1 * t1 * t1 + + p1y * 3 * percent * t1 * t1 + + p2y * 3 * percent * percent * t1 + + p3y * percent * percent * percent; +} diff --git a/cocos/animation/easing.ts b/cocos/animation/easing.ts new file mode 100644 index 0000000000..8c0f1a5769 --- /dev/null +++ b/cocos/animation/easing.ts @@ -0,0 +1,271 @@ + +export function constant () { + return 0; +} + +export function linear (k: number) { + return k; +} + +export function quadIn (k: number) { + return k * k; +} + +export function quadOut (k: number) { + return k * (2 - k); +} + +export function quadInOut (k: number) { + k *= 2; + if (k < 1) { + return 0.5 * k * k; + } + return -0.5 * (--k * (k - 2) - 1); +} + +export function cubicIn (k: number) { + return k * k * k; +} + +export function cubicOut (k: number) { + return --k * k * k + 1; +} + +export function cubicInOut (k: number) { + k *= 2; + if (k < 1) { + return 0.5 * k * k * k; + } + return 0.5 * ((k -= 2) * k * k + 2); +} + +export function quartIn (k: number) { + return k * k * k * k; +} + +export function quartOut (k: number) { + return 1 - (--k * k * k * k); +} + +export function quartInOut (k: number) { + k *= 2; + if (k < 1) { + return 0.5 * k * k * k * k; + } + return -0.5 * ((k -= 2) * k * k * k - 2); +} + +export function quintIn (k: number) { + return k * k * k * k * k; +} + +export function quintOut (k: number) { + return --k * k * k * k * k + 1; +} + +export function quintInOut (k: number) { + k *= 2; + if (k < 1) { + return 0.5 * k * k * k * k * k; + } + return 0.5 * ((k -= 2) * k * k * k * k + 2); +} + +export function sineIn (k: number) { + return 1 - Math.cos(k * Math.PI / 2); +} + +export function sineOut (k: number) { + return Math.sin(k * Math.PI / 2); +} + +export function sineInOut (k: number) { + return 0.5 * (1 - Math.cos(Math.PI * k)); +} + +export function expoIn (k: number) { + return k === 0 ? 0 : Math.pow(1024, k - 1); +} + +export function expoOut (k: number) { + return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); +} + +export function expoInOut (k: number) { + if (k === 0) { + return 0; + } + if (k === 1) { + return 1; + } + k *= 2; + if (k < 1) { + return 0.5 * Math.pow(1024, k - 1); + } + return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); +} + +export function circIn (k: number) { + return 1 - Math.sqrt(1 - k * k); +} + +export function circOut (k: number) { + return Math.sqrt(1 - (--k * k)); +} + +export function circInOut (k: number) { + k *= 2; + if (k < 1) { + return -0.5 * (Math.sqrt(1 - k * k) - 1); + } + return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); +} + +export function elasticIn (k: number) { + let s; + let a = 0.1; + const p = 0.4; + if (k === 0) { + return 0; + } + if (k === 1) { + return 1; + } + if (!a || a < 1) { + a = 1; + s = p / 4; + } + else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); +} + +export function elasticOut (k: number) { + let s; + let a = 0.1; + const p = 0.4; + if (k === 0) { + return 0; + } + if (k === 1) { + return 1; + } + if (!a || a < 1) { + a = 1; + s = p / 4; + } + else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); +} + +export function elasticInOut (k: number) { + let s; + let a = 0.1; + const p = 0.4; + if (k === 0) { + return 0; + } + if (k === 1) { + return 1; + } + if (!a || a < 1) { + a = 1; + s = p / 4; + } + else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + k *= 2; + if (k < 1) { + return -0.5 * + (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + } + return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; +} + +export function backIn (k: number) { + const s = 1.70158; + return k * k * ((s + 1) * k - s); +} + +export function backOut (k: number) { + const s = 1.70158; + return --k * k * ((s + 1) * k + s) + 1; +} + +export function backInOut (k: number) { + const s = 1.70158 * 1.525; + k *= 2; + if (k < 1) { + return 0.5 * (k * k * ((s + 1) * k - s)); + } + return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); +} + +export function bounceIn (k: number) { + return 1 - bounceOut(1 - k); +} + +export function bounceOut (k: number) { + if (k < (1 / 2.75)) { + return 7.5625 * k * k; + } + else if (k < (2 / 2.75)) { + return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; + } + else if (k < (2.5 / 2.75)) { + return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; + } + else { + return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; + } +} + +export function bounceInOut (k: number) { + if (k < 0.5) { + return bounceIn(k * 2) * 0.5; + } + return bounceOut(k * 2 - 1) * 0.5 + 0.5; +} + +export function smooth (k: number) { + if (k <= 0) { + return 0; + } + if (k >= 1) { + return 1; + } + return k * k * (3 - 2 * k); +} + +export function fade (k: number) { + if (k <= 0) { + return 0; + } + if (k >= 1) { + return 1; + } + return k * k * k * (k * (k * 6 - 15) + 10); +} + +export const quadOutIn = _makeOutIn(quadIn, quadOut); +export const cubicOutIn = _makeOutIn(cubicIn, cubicOut); +export const quartOutIn = _makeOutIn(quartIn, quartOut); +export const quintOutIn = _makeOutIn(quintIn, quintOut); +export const sineOutIn = _makeOutIn(sineIn, sineOut); +export const expoOutIn = _makeOutIn(expoIn, expoOut); +export const circOutIn = _makeOutIn(circIn, circOut); +export const backOutIn = _makeOutIn(backIn, backOut); +export const bounceOutIn = _makeOutIn(bounceIn, bounceOut); + +function _makeOutIn (fnIn: (k: number) => number, fnOut: (k: number) => number) { + return (k: number) => { + if (k < 0.5) { + return fnOut(k * 2) / 2; + } + return fnIn(2 * k - 1) / 2 + 0.5; + }; +} diff --git a/cocos/animation/index.ts b/cocos/animation/index.ts new file mode 100644 index 0000000000..244b1893c0 --- /dev/null +++ b/cocos/animation/index.ts @@ -0,0 +1,10 @@ +import * as easing from './easing'; +export * from './bezier'; +export { easing }; +export * from './types'; +export * from './motion-path-helper'; +export * from './animation-curve'; +export * from './animation-clip'; +export * from './animation-manager'; +export * from './animation-state'; +export * from './animation-animator'; diff --git a/cocos/animation/motion-path-helper.ts b/cocos/animation/motion-path-helper.ts new file mode 100644 index 0000000000..c26af8a0bc --- /dev/null +++ b/cocos/animation/motion-path-helper.ts @@ -0,0 +1,394 @@ +import { Vec2 } from '../core'; +import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; +import { computeRatioByType, CurveType, CurveValue, DynamicAnimCurve, ICurveTarget } from './animation-curve'; +import { bezier } from './bezier'; + +// tslint:disable:no-shadowed-variable + +export class Curve { + public beziers: Bezier[] = []; + + public ratios: number[] = []; + + public progresses: number[] = []; + + public length = 0; + + constructor (public points: IControlPoint[] = []) { + this.computeBeziers(); + } + + public computeBeziers () { + this.beziers.length = 0; + this.ratios.length = 0; + this.progresses.length = 0; + this.length = 0; + + for (let i = 1; i < this.points.length; i++) { + const startPoint = this.points[i - 1]; + const endPoint = this.points[i]; + const bezier = new Bezier(); + bezier.start = startPoint.pos; + bezier.startCtrlPoint = startPoint.out; + bezier.end = endPoint.pos; + bezier.endCtrlPoint = endPoint.in; + this.beziers.push(bezier); + + this.length += bezier.getLength(); + } + + let current = 0; + for (let i = 0; i < this.beziers.length; i++) { + const bezier = this.beziers[i]; + this.ratios[i] = bezier.getLength() / this.length; + this.progresses[i] = current = current + this.ratios[i]; + } + + return this.beziers; + } +} + +export class Bezier { + public start = new Vec2(); + + public end = new Vec2(); + + /** + * cp0, cp1 + */ + public startCtrlPoint = new Vec2(); + + /** + * cp2, cp3 + */ + public endCtrlPoint = new Vec2(); + + public __arcLengthDivisions?: number; + + private cacheArcLengths?: number[]; + + /** + * Get point at relative position in curve according to arc length + * @param u [0 .. 1] + */ + public getPointAt (u: number) { + const t = this.getUtoTmapping(u); + return this.getPoint(t); + } + + /** + * Get point at time t. + * @param t [0 .. 1] + */ + public getPoint (t: number) { + const x = bezier(this.start.x, this.startCtrlPoint.x, this.endCtrlPoint.x, this.end.x, t); + const y = bezier(this.start.y, this.startCtrlPoint.y, this.endCtrlPoint.y, this.end.y, t); + return new Vec2(x, y); + } + + /** + * Get total curve arc length. + */ + public getLength () { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + + /** + * Get list of cumulative segment lengths. + */ + public getLengths (divisions?: number) { + if (!divisions) { + divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200; + } + + if (this.cacheArcLengths + && (this.cacheArcLengths.length === divisions + 1)) { + + // console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; + + } + + const cache: number[] = []; + let current; + let last = this.getPoint(0); + const vector = new Vec2(); + let p; + let sum = 0; + + cache.push(0); + + for (p = 1; p <= divisions; p++) { + + current = this.getPoint(p / divisions); + vector.x = last.x - current.x; + vector.y = last.y - current.y; + sum += vector.mag(); + cache.push(sum); + last = current; + + } + + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum:sum }; Sum is in the last element. + } + + public getUtoTmapping (u: number, distance?: number) { + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + + // var time = Date.now(); + + // binary search for the index with largest value smaller than target u distance + + let low = 0; + let high = il - 1; + let comparison; + + while (low <= high) { + // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + continue; + } else if (comparison > 0) { + high = i - 1; + continue; + } else { + high = i; + break; // DONE + } + } + + i = high; + + // console.log('b' , i, low, high, Date.now()- time); + + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + + // we could get finer grain at lengths, or use simple interpolatation between two points + + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + + // add that fractional amount to t + + const t = (i + segmentFraction) / (il - 1); + + return t; + } +} + +function checkMotionPath (motionPath) { + if (!Array.isArray(motionPath)) { return false; } + + for (let i = 0, l = motionPath.length; i < l; i++) { + const controls = motionPath[i]; + + if (!Array.isArray(controls) || controls.length !== 6) { return false; } + } + + return true; +} + +interface IControlPoint { + in: Vec2; + pos: Vec2; + out: Vec2; +} + +export type MotionPath = Vec2[]; + +export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, data: DynamicAnimCurve, duration: number, fps: number, target: ICurveTarget) { + const createControlPoints = (array: number[] | Vec2): IControlPoint => { + if (array instanceof Vec2) { + return { + in: array, + pos: array, + out: array, + }; + } else if (Array.isArray(array) && array.length === 6) { + return { + in: new Vec2(array[2], array[3]), + pos: new Vec2(array[0], array[1]), + out: new Vec2(array[4], array[5]), + }; + } + return { + in: Vec2.ZERO, + pos: Vec2.ZERO, + out: Vec2.ZERO, + }; + }; + + const values = data.values = data.values.map((value) => { + if (Array.isArray(value)) { + value = value.length === 2 ? cc.v2(value[0], value[1]) : cc.v3(value[0], value[1], value[2]); + } + return value; + }); + + if (motionPaths.length === 0 || values.length === 0) { + return; + } + + let motionPathValid = false; + for (let i = 0; i < motionPaths.length; i++) { + let motionPath = motionPaths[i]; + if (motionPath && !checkMotionPath(motionPath)) { + cc.errorID(3904, target ? target.name : '', 'position', i); + motionPath = undefined; + } + if (motionPath && motionPath.length > 0) { + motionPathValid = true; + break; + } + } + + if (!motionPathValid) { + return; + } + + if (values.length === 1) { + return; + } + + const types = data.types; + const ratios = data.ratios; + + const newValues: CurveValue[] = data.values = []; + const newTypes: CurveType[] = data.types = []; + const newRatios: number[] = data.ratios = []; + + function addNewDatas (value: CurveValue, type: CurveType, ratio: number) { + newValues.push(value); + newTypes.push(type); + newRatios.push(ratio); + } + + // ensure every ratio section's length is the same + let startRatioOffset = 0; + + const EPSILON = 1e-6; + let newType: CurveType = DynamicAnimCurve.Linear; + + // do not need to compute last path + for (let i = 0, l = motionPaths.length; i < l - 1; i++) { + const motionPath = motionPaths[i]; + + const ratio = ratios[i]; + const nextRatio = ratios[i + 1]; + const betweenRatio = nextRatio - ratio; + + const value = values[i]; + const nextValue = values[i + 1]; + + const type = types[i]; + + const results: Vec2[] = []; + let progress = startRatioOffset / betweenRatio; + const speed = 1 / (betweenRatio * duration * fps); + let finalProgress; + + if (motionPath && motionPath.length > 0) { + const points: IControlPoint[] = []; + points.push(createControlPoints(value)); + + for (let j = 0, l2 = motionPath.length; j < l2; j++) { + const controlPoints = createControlPoints(motionPath[j]); + points.push(controlPoints); + } + + points.push(createControlPoints(nextValue)); + + // create Curve to compute beziers + const curve = new Curve(points); + curve.computeBeziers(); + + // sample beziers + const progresses = curve.progresses; + + while (1 - progress > EPSILON) { + finalProgress = progress; + + finalProgress = computeRatioByType(finalProgress, type); + + let pos: Vec2; + + if (finalProgress < 0) { + const bezier = curve.beziers[0]; + const length = (0 - finalProgress) * bezier.getLength(); + const normal = bezier.start.sub(bezier.endCtrlPoint).normalize(); + pos = bezier.start.add(normal.mul(length)); + } else if (finalProgress > 1) { + const bezier = curve.beziers[curve.beziers.length - 1]; + const length = (finalProgress - 1) * bezier.getLength(); + const normal = bezier.end.sub(bezier.startCtrlPoint).normalize(); + pos = bezier.end.add(normal.mul(length)); + } else { + let bezierIndex = binarySearch(progresses, finalProgress); + if (bezierIndex < 0) { bezierIndex = ~bezierIndex; } + + finalProgress -= bezierIndex > 0 ? progresses[bezierIndex - 1] : 0; + finalProgress = finalProgress / curve.ratios[bezierIndex]; + + pos = curve.beziers[bezierIndex].getPointAt(finalProgress); + } + + results.push(pos); + progress += speed; + } + + } + else { + while (1 - progress > EPSILON) { + finalProgress = progress; + + finalProgress = computeRatioByType(finalProgress, type); + + results.push(value.lerp(nextValue, finalProgress)); + + progress += speed; + } + } + + newType = type === 'constant' ? type : DynamicAnimCurve.Linear; + + for (let j = 0, l2 = results.length; j < l2; j++) { + const newRatio = ratio + startRatioOffset + speed * j * betweenRatio; + addNewDatas(results[j], newType, newRatio); + } + + if (Math.abs(progress - 1) > EPSILON) { // progress > 1 + startRatioOffset = (progress - 1) * betweenRatio; + } + else { + startRatioOffset = 0; + } + } + + if (ratios[ratios.length - 1] !== newRatios[newRatios.length - 1]) { + addNewDatas(values[values.length - 1], newType, ratios[ratios.length - 1]); + } +} diff --git a/cocos/animation/playable.ts b/cocos/animation/playable.ts new file mode 100644 index 0000000000..61908cff84 --- /dev/null +++ b/cocos/animation/playable.ts @@ -0,0 +1,111 @@ +import { getError } from '../core/platform/CCDebug'; + +export class Playable { + + /** + * !#en Is playing or paused in play mode? + * !#zh 当前是否正在播放。 + * @default false + */ + get isPlaying () { + return this._isPlaying; + } + + /** + * !#en Is currently paused? This can be true even if in edit mode(isPlaying == false). + * !#zh 当前是否正在暂停 + * @default false + */ + get isPaused () { + return this._isPaused; + } + private _isPlaying = false; + private _isPaused = false; + private _stepOnce = false; + + /** + * !#en Play this animation. + * !#zh 播放动画。 + */ + public play () { + if (this._isPlaying) { + if (this._isPaused) { + this._isPaused = false; + this.onResume(); + } else { + this.onError(getError(3912)); + } + } else { + this._isPlaying = true; + this.onPlay(); + } + } + + /** + * !#en Stop this animation. + * !#zh 停止动画播放。 + */ + public stop () { + if (this._isPlaying) { + this._isPlaying = false; + this.onStop(); + + // need reset pause flag after onStop + this._isPaused = false; + } + } + + /** + * !#en Pause this animation. + * !#zh 暂停动画。 + */ + public pause () { + if (this._isPlaying && !this._isPaused) { + this._isPaused = true; + this.onPause(); + } + } + + /** + * !#en Resume this animation. + * !#zh 重新播放动画。 + */ + public resume () { + if (this._isPlaying && this._isPaused) { + this._isPaused = false; + this.onResume(); + } + } + + /** + * !#en Perform a single frame step. + * !#zh 执行一帧动画。 + */ + public step () { + this.pause(); + this._stepOnce = true; + if (!this._isPlaying) { + this.play(); + } + } + + protected onPlay () { + + } + + protected onPause () { + + } + + protected onResume () { + + } + + protected onStop () { + + } + + protected onError (message: string) { + + } +} diff --git a/cocos/animation/types.ts b/cocos/animation/types.ts index c3cde1b735..60594f784a 100644 --- a/cocos/animation/types.ts +++ b/cocos/animation/types.ts @@ -1,7 +1,7 @@ import { ccenum } from '../core/value-types/enum'; -enum WrapModeMask { +export enum WrapModeMask { Loop = 1 << 1, ShouldWrap = 1 << 2, // Reserved: 1 << 3, @@ -62,3 +62,30 @@ export enum WrapMode { ccenum(WrapMode); cc.WrapMode = WrapMode; + +/** + * For internal + */ +export class WrappedInfo { + public ratio = 0; + public time = 0; + public direction = 1; + public stopped = true; + public iterations = 0; + public frameIndex: number = NaN; + + constructor (info?: WrappedInfo) { + if (info) { + this.set(info); + } + } + + public set (info: WrappedInfo) { + this.ratio = info.ratio; + this.time = info.time; + this.direction = info.direction; + this.stopped = info.stopped; + this.iterations = info.iterations; + this.frameIndex = info.frameIndex; + } +} diff --git a/cocos/core/data/index.js b/cocos/core/data/index.ts similarity index 100% rename from cocos/core/data/index.js rename to cocos/core/data/index.ts diff --git a/cocos/core/data/utils/binary-search.ts b/cocos/core/data/utils/binary-search.ts new file mode 100644 index 0000000000..c41abe8b28 --- /dev/null +++ b/cocos/core/data/utils/binary-search.ts @@ -0,0 +1,19 @@ + +const EPSILON = 1e-6; + +export function binarySearchEpsilon (array: number[], value: number) { + let l = 0; + for (let h = array.length - 1, m = h >>> 1; l <= h; m = (l + h) >>> 1) { + const test = array[m]; + if (test > value + EPSILON) { + h = m - 1; + } + else if (test < value - EPSILON) { + l = m + 1; + } + else { + return m; + } + } + return ~l; +} diff --git a/cocos/core/utils/array.js b/cocos/core/utils/array.ts similarity index 83% rename from cocos/core/utils/array.js rename to cocos/core/utils/array.ts index 9fd66998bf..f852871cca 100644 --- a/cocos/core/utils/array.js +++ b/cocos/core/utils/array.ts @@ -48,7 +48,7 @@ export function removeAt (array, index) { * @param {Number} index */ export function fastRemoveAt (array, index) { - var length = array.length; + const length = array.length; if (index < 0 || index >= length) { return; } @@ -64,7 +64,7 @@ export function fastRemoveAt (array, index) { * @return {Boolean} */ export function remove (array, value) { - var index = array.indexOf(value); + const index = array.indexOf(value); if (index >= 0) { removeAt(array, index); return true; @@ -82,7 +82,7 @@ export function remove (array, value) { * @param {Number} value */ export function fastRemove (array, value) { - var index = array.indexOf(value); + const index = array.indexOf(value); if (index >= 0) { array[index] = array[array.length - 1]; --array.length; @@ -98,8 +98,8 @@ export function fastRemove (array, value) { */ export function verifyType (array, type) { if (array && array.length > 0) { - for (var i = 0; i < array.length; i++) { - if (!(array[i] instanceof type)) { + for (const item of array) { + if (!(item instanceof type)) { cc.logID(1300); return false; } @@ -115,7 +115,7 @@ export function verifyType (array, type) { * @param {Array} minusArr minus Array */ export function removeArray (array, minusArr) { - for (var i = 0, l = minusArr.length; i < l; i++) { + for (let i = 0, l = minusArr.length; i < l; i++) { remove(array, minusArr[i]); } } @@ -135,8 +135,12 @@ export function appendObjectsAt (array, addObjs, index) { /** * Exact same function as Array.prototype.indexOf.
- * HACK: ugliy hack for Baidu mobile browser compatibility, stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, their version changes strict comparison to non-strict comparison, it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop.
- * Baidu developers, if you ever see this documentation, here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf, Seriously! + * HACK: ugliy hack for Baidu mobile browser compatibility, + * stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, + * their version changes strict comparison to non-strict comparison, + * it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop.
+ * Baidu developers, if you ever see this documentation, + * here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf, Seriously! * * @method indexOf * @param {any} searchElement - Element to locate in the array. @@ -163,8 +167,10 @@ export function contains (array, value) { * @return {Array} */ export function copy (array) { - var i, len = array.length, arr_clone = new Array(len); - for (i = 0; i < len; i += 1) + const len = array.length; + const arr_clone = new Array(len); + for (let i = 0; i < len; i += 1) { arr_clone[i] = array[i]; + } return arr_clone; } diff --git a/cocos/core/utils/mutable-forward-iterator.js b/cocos/core/utils/mutable-forward-iterator.ts similarity index 77% rename from cocos/core/utils/mutable-forward-iterator.js rename to cocos/core/utils/mutable-forward-iterator.ts index 91a11a57e9..5fdcea16c1 100644 --- a/cocos/core/utils/mutable-forward-iterator.js +++ b/cocos/core/utils/mutable-forward-iterator.ts @@ -34,33 +34,48 @@ * ... * } */ -export default class MutableForwardIterator { - constructor (array) { - this.i = 0; +export default class MutableForwardIterator { + public i = 0; + + constructor (public array: T[]) { this.array = array; } - remove (value) { - var index = this.array.indexOf(value); + get length () { + return this.array.length; + } + + set length (value: number) { + this.array.length = value; + if (this.i >= value) { + this.i = value - 1; + } + } + + public remove (value: T) { + const index = this.array.indexOf(value); if (index >= 0) { this.removeAt(index); } } - removeAt (i) { + + public removeAt (i: number) { this.array.splice(i, 1); if (i <= this.i) { --this.i; } } - fastRemove (value) { - var index = this.array.indexOf(value); + + public fastRemove (value: T) { + const index = this.array.indexOf(value); if (index >= 0) { this.fastRemoveAt(index); } } - fastRemoveAt (i) { - var array = this.array; + + public fastRemoveAt (i: number) { + const array = this.array; array[i] = array[array.length - 1]; --array.length; @@ -68,19 +83,8 @@ export default class MutableForwardIterator { --this.i; } } - push (item) { + + public push (item: T) { this.array.push(item); } } - -//js.getset(proto, 'length', -// function () { -// return this.array.length; -// }, -// function (len) { -// this.array.length = len; -// if (this.i >= len) { -// this.i = len - 1; -// } -// } -//); \ No newline at end of file diff --git a/cocos/load-pipeline/uuid-loader.js b/cocos/load-pipeline/uuid-loader.js index f8617e6a6f..71074f3679 100644 --- a/cocos/load-pipeline/uuid-loader.js +++ b/cocos/load-pipeline/uuid-loader.js @@ -275,7 +275,8 @@ export function loadUuid (item, callback) { catch (e) { cc.deserialize.Details.pool.put(tdInfo); var err = CC_JSB ? (e + '\n' + e.stack) : e.stack; - return new Error(debug.getError(4925, item.id, err)); + return new Error(`Failed to load asset ${item.id}, exception occurs during serialization: ${err}.`); + // return new Error(debug.getError(4925, item.id, err)); } asset._uuid = item.uuid;