[tween] Add bezier / catmullrom support (#17216)

This commit is contained in:
James Chen
2024-06-25 15:41:15 +08:00
committed by GitHub
parent db5c05d10c
commit d9bd3c3dc0
7 changed files with 5150 additions and 2 deletions
+5
View File
@@ -592,6 +592,11 @@ export class RepeatForever extends ActionInterval {
}
}
stop (): void {
if (this._innerAction) this._innerAction.stop();
super.stop();
}
step (dt: number): void {
if (this._paused || this._speed === 0) return;
const locInnerAction = this._innerAction;
+6 -1
View File
@@ -22,7 +22,12 @@
THE SOFTWARE.
*/
export { TweenSystem } from './tween-system';
import * as tweenProgress from './tween-progress';
export * from './tween';
export * from './export-api';
export { TweenSystem } from './tween-system';
export { TweenAction } from './tween-action';
export { tweenProgress };
+30
View File
@@ -187,6 +187,9 @@ export class TweenAction<T extends object> extends ActionInterval {
prop.sub = value.sub;
prop.legacyProgress = value.legacyProgress ?? true;
prop.toFixed = value.toFixed;
prop.onStart = value.onStart;
prop.onStop = value.onStop;
prop.onComplete = value.onComplete;
prop.valid = true;
this._props[name] = prop;
}
@@ -323,11 +326,34 @@ export class TweenAction<T extends object> extends ActionInterval {
prop.current = _t;
prop.end = relative ? (reversed ? startNumValue - targetNumValue : startNumValue + targetNumValue) : targetNumValue;
}
if (prop.onStart) {
prop.onStart({
relative,
reversed,
start: prop.start,
end: prop.end,
});
}
}
if (this._opts.onStart) { this._opts.onStart(workerTarget); }
}
stop (): void {
const props = this._props;
for (const name in props) {
const prop = props[name];
if (!prop.valid) continue;
if (prop.onStop) {
prop.onStop();
}
}
super.stop();
}
update (t: number): void {
const workerTarget = (this.workerTarget ?? this.target) as T;
if (!workerTarget) return;
@@ -375,6 +401,10 @@ export class TweenAction<T extends object> extends ActionInterval {
}
workerTarget[name] = prop.current;
if (t === 1 && prop.onComplete) {
prop.onComplete();
}
}
if (opts.onUpdate) { opts.onUpdate(workerTarget, t); }
if (t === 1 && opts.onComplete) { opts.onComplete(workerTarget); }
+96
View File
@@ -0,0 +1,96 @@
/*
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import type { ITweenCustomProperty, ITweenCustomPropertyStartParameter } from './tween';
import { Spline, SplineMode } from '../core/geometry';
import { Vec3 } from '../core/math';
const _v3_tmp_1 = new Vec3();
const _v3_tmp_2 = new Vec3();
function createSplineProperty (mode: SplineMode, knots: ReadonlyArray<Vec3>): ITweenCustomProperty<Vec3> {
let spline: Spline | null = null;
return {
value: knots.length > 0 ? knots[knots.length - 1] : Vec3.ZERO,
progress (start: Vec3, end: Vec3, current: Vec3, ratio: number): Vec3 {
return spline!.getPoint(ratio);
},
clone (v: Vec3): Vec3 {
return Vec3.clone(v);
},
add (a, b): Vec3 {
return a.clone().add(b);
},
sub (a, b): Vec3 {
return a.clone().subtract(b);
},
onStart (param: ITweenCustomPropertyStartParameter<Vec3>): void {
const { start, end, relative, reversed } = param;
spline = Spline.create(mode);
spline.addKnot(start);
let reversedLast: Vec3 | null = null;
if (relative && reversed) {
reversedLast = _v3_tmp_2;
Vec3.subtract(reversedLast, start, knots[knots.length - 1]);
}
for (let i = 0, len = knots.length; i < len; ++i) {
const v = reversed ? knots[len - 1 - i] : knots[i];
if (relative) {
if (reversed) {
// Skip the start point ( i = 0 )
if (i > 0) {
// addKnot will copy the knot, so use a temporary Vec3 object here to avoid GC object being generated.
spline.addKnot(Vec3.copy(_v3_tmp_1, reversedLast!).add(v));
}
} else {
spline.addKnot(Vec3.copy(_v3_tmp_1, start).add(v));
}
} else {
spline.addKnot(v);
}
}
if (relative && reversed) {
spline.addKnot(end);
}
},
onComplete (): void {
spline = null;
},
onStop (): void {
spline = null;
},
legacyProgress: false,
};
}
export function bezier (...knots: ReadonlyArray<Vec3>): ITweenCustomProperty<Vec3> {
return createSplineProperty(SplineMode.BEZIER, knots);
}
export function catmullRom (...knots: ReadonlyArray<Vec3>): ITweenCustomProperty<Vec3> {
return createSplineProperty(SplineMode.CATMULL_ROM, knots);
}
+14
View File
@@ -47,6 +47,14 @@ type ExtendsReturnResultOrNever<T, Base, Result> = ExtendsReturnResults<T, Base,
type MaybeUnionStringNumber<T> = ExtendsReturnResults<T, string, string | number, T>;
type StringToNumberOrNever<T> = ExtendsReturnResultOrNever<T, string, string | number>;
export interface ITweenCustomPropertyStartParameter<Value> {
relative: boolean;
reversed: boolean;
start: Value;
end: Value;
}
export interface ITweenCustomProperty<Value> {
value: MaybeUnionStringNumber<Value> | (() => MaybeUnionStringNumber<Value>);
progress?: TweenCustomProgress;
@@ -57,6 +65,9 @@ export interface ITweenCustomProperty<Value> {
sub?: (a: Value, b: Value) => Value; // Supported from v3.8.5
legacyProgress?: ExtendsReturnResultOrNever<Value, object, boolean>; // Supported from v3.8.5, the default value is true for compatiblity
toFixed?: ExtendsReturnResultOrNever<Value, string, number>; // Supported from v3.8.5
onStart?: (param: ITweenCustomPropertyStartParameter<Value>) => void;
onStop?: () => void;
onComplete?: () => void;
}
type KeyPartial<T, K extends keyof T> = { [P in K]?: (T[P] | (() => T[P]) | ITweenCustomProperty<T[P]> | StringToNumberOrNever<T[P]>) };
@@ -312,6 +323,7 @@ export class Tween<T extends object = any> {
final.setTag(this._tag);
final.setSpeed(this._timeScale);
final.setStartTime(time);
final.setPaused(false); // If a tween was paused, starting the tween again should clear the 'paused' flag for the final action.
TweenSystem.instance.ActionManager.addAction(final, this._target, false);
} else {
warn(`start: no actions in Tween`);
@@ -328,6 +340,8 @@ export class Tween<T extends object = any> {
*/
stop (): Tween<T> {
if (this._finalAction) {
// ActionManager.removeAction will not stop action, so stop it before removeAction.
this._finalAction.stop();
TweenSystem.instance.ActionManager.removeAction(this._finalAction);
this._finalAction = null;
}
File diff suppressed because it is too large Load Diff
+158 -1
View File
@@ -1,5 +1,5 @@
import { Vec3, System, size, Size, approx, color, v3, lerp, EPSILON } from "../../cocos/core";
import { ITweenOption, ITweenCustomProperty, tween, Tween, TweenSystem } from "../../cocos/tween";
import { ITweenOption, ITweenCustomProperty, tween, Tween, TweenSystem, tweenProgress } from "../../cocos/tween";
import { Node, Scene } from "../../cocos/scene-graph";
import { Component } from "../../cocos/scene-graph/component";
import { game, director } from "../../cocos/game";
@@ -2599,6 +2599,38 @@ test('pause/resume 3', function () {
director.unregisterSystem(sys);
});
test('pause/start a repeatForever action', function () {
const sys = new TweenSystem();
(TweenSystem.instance as any) = sys;
director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
//
const node = new Node();
node.setScale(0, 0, 0);
const t = tween(node)
.by(1, { position: v3(90, 90, 90) })
.repeatForever()
.start();
t.pause();
t.start();
// Start
runFrames(1);
runFrames(20);
expect(node.position.equals(new Vec3(30, 30, 30))).toBeTruthy();
runFrames(20);
expect(node.position.equals(new Vec3(60, 60, 60))).toBeTruthy();
runFrames(20);
expect(node.position.equals(new Vec3(90, 90, 90))).toBeTruthy();
//
director.unregisterSystem(sys);
});
test('pauseAllByTarget/resumeAllByTarget', function () {
const sys = new TweenSystem();
(TweenSystem.instance as any) = sys;
@@ -4494,3 +4526,128 @@ test('update destroyed node', function () {
director.unregisterSystem(sys);
});
test('Bezier Curve', function () {
const sys = new TweenSystem();
(TweenSystem.instance as any) = sys;
director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
const originalKnots: ReadonlyArray<Vec3> = [
// v3(-360, -180, 0), // start
v3(-270, 80, 0),
v3(-100, -80, 0),
v3(0, 0, 0),
v3(0, 0, 0),
v3(100, -80, 0),
v3(270, 80, 0),
v3(360, -180, 0),
];
const node = new Node();
node.setPosition(-360, -180, 0);
const pos = node.getPosition().clone();
const offsetKnots = originalKnots.map((v: Vec3) => v.clone().subtract(pos));
tween(node)
.by(2, { position: tweenProgress.bezier(...offsetKnots) }).id(1)
.reverse(1)
.start();
const positionFootprintsBy: Vec3[] = [];
for (let i = 0, len = 4 * 60 + 1; i < len; ++i) {
runFrames(1);
positionFootprintsBy.push(node.getPosition().clone());
}
expect(positionFootprintsBy).toMatchSnapshot('BezierBy Positions');
// Reset position
node.setPosition(-360, -180, 0);
const reverseKnots = originalKnots.slice();
reverseKnots.reverse();
reverseKnots.push(pos);
reverseKnots.splice(0, 1);
tween(node)
.to(2, { position: tweenProgress.bezier(...originalKnots)})
.to(2, { position: tweenProgress.bezier(...reverseKnots)})
.start();
const positionFootprintsTo: Vec3[] = [];
for (let i = 0, len = 4 * 60 + 1; i < len; ++i) {
runFrames(1);
positionFootprintsTo.push(node.getPosition().clone());
}
expect(positionFootprintsBy).toMatchSnapshot('BezierTo Positions');
expect(positionFootprintsBy.length).toBe(positionFootprintsTo.length);
positionFootprintsBy.forEach((v: Vec3, i: number) => {
expect(v.equals(positionFootprintsTo[i])).toBeTruthy();
});
director.unregisterSystem(sys);
});
test('CatmullRom Curve', function () {
const sys = new TweenSystem();
(TweenSystem.instance as any) = sys;
director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
const originalKnots: ReadonlyArray<Vec3> = [
// v3(-360, -180, 0), // start
v3(-270, 80, 0),
v3(-100, -80, 0),
v3(0, 0, 0),
v3(100, -80, 0),
v3(270, 80, 0),
v3(360, -180, 0),
];
const node = new Node();
node.setPosition(-360, -180, 0);
const pos = node.getPosition().clone();
const offsetKnots = originalKnots.map((v: Vec3) => v.clone().subtract(pos));
tween(node)
.by(2, { position: tweenProgress.catmullRom(...offsetKnots) }).id(1)
.reverse(1)
.start();
const positionFootprintsBy: Vec3[] = [];
for (let i = 0, len = 4 * 60 + 1; i < len; ++i) {
runFrames(1);
positionFootprintsBy.push(node.getPosition().clone());
}
expect(positionFootprintsBy).toMatchSnapshot('CatmullRomBy Positions');
// Reset position
node.setPosition(-360, -180, 0);
const reverseKnots = originalKnots.slice();
reverseKnots.reverse();
reverseKnots.push(pos);
reverseKnots.splice(0, 1);
tween(node)
.to(2, { position: tweenProgress.catmullRom(...originalKnots)})
.to(2, { position: tweenProgress.catmullRom(...reverseKnots)})
.start();
const positionFootprintsTo: Vec3[] = [];
for (let i = 0, len = 4 * 60 + 1; i < len; ++i) {
runFrames(1);
positionFootprintsTo.push(node.getPosition().clone());
}
expect(positionFootprintsBy).toMatchSnapshot('CatmullRomTo Positions');
expect(positionFootprintsBy.length).toBe(positionFootprintsTo.length);
positionFootprintsBy.forEach((v: Vec3, i: number) => {
expect(v.equals(positionFootprintsTo[i])).toBeTruthy();
});
director.unregisterSystem(sys);
});