forked from cocos/cocos-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
animation-clip.ts
1647 lines (1428 loc) · 53.9 KB
/
animation-clip.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2020-2023 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 { ccclass, serializable } from 'cc.decorator';
import { DEBUG } from 'internal:constants';
import { Asset } from '../asset/assets/asset';
import { SpriteFrame } from '../2d/assets/sprite-frame';
import { errorID, warnID, cclegacy, js, geometry, approx, clamp, Mat4, Quat, Vec3, murmurhash2_32_gc, binarySearchEpsilon, assertIsTrue, RealCurve } from '../core';
import { SkelAnimDataHub } from '../3d/skeletal-animation/skeletal-animation-data-hub';
import { WrapMode as AnimationWrapMode, WrapMode } from './types';
import { Node } from '../scene-graph/node';
import type { PoseOutput } from './pose-output';
import * as legacy from './legacy-clip-data';
import { BAKE_SKELETON_CURVE_SYMBOL } from './internal-symbols';
import { Binder, RuntimeBinding, Track, TrackBinding, trackBindingTag, TrackEval, TrackPath, TrsTrackPath } from './tracks/track';
import { createEvalSymbol } from './define';
import { UntypedTrack, UntypedTrackRefine } from './tracks/untyped-track';
import { Range } from './tracks/utils';
import { ObjectTrack } from './tracks/object-track';
import type { ExoticAnimation } from './exotic-animation/exotic-animation';
import './exotic-animation/exotic-animation';
import type { AnimationMask } from './marionette/animation-mask';
import { getGlobalAnimationManager } from './global-animation-manager';
import { EmbeddedPlayableState, EmbeddedPlayer } from './embedded-player/embedded-player';
import { AuxiliaryCurveEntry } from './auxiliary-curve-entry';
import { removeIf } from '../core/utils/array';
export declare namespace AnimationClip {
export interface IEvent {
frame: number;
func: string;
params: string[];
}
/**
* @internal
*/
export type { legacy as _legacy };
}
// #region Tracks
// Export for test
export const searchForRootBonePathSymbol = Symbol('SearchForRootBonePath');
// #endregion
interface SkeletonAnimationBakeInfo {
samples: number;
frames: number;
joints: Record<string, {
transforms?: Mat4[];
}>;
}
export const exoticAnimationTag = Symbol('ExoticAnimation');
export const embeddedPlayerCountTag = Symbol('[[EmbeddedPlayerCount]]');
export const getEmbeddedPlayersTag = Symbol('[[GetEmbeddedPlayers]]');
export const addEmbeddedPlayerTag = Symbol('[[AddEmbeddedPlayer]]');
export const removeEmbeddedPlayerTag = Symbol('[[RemoveEmbeddedPlayer]]');
export const clearEmbeddedPlayersTag = Symbol('[[ClearEmbeddedPlayers]]');
/**
* Tag to access the additive settings associated on animation clip.
*/
export const additiveSettingsTag = Symbol('[[Additive Settings]]');
/**
* @zh 动画剪辑表示一段使用动画编辑器编辑的关键帧动画或是外部美术工具生产的骨骼动画。
* 它的数据主要被分为几层:轨道、关键帧和曲线。
* @en The animation clip represents a sequence of key frame animation created with the animation editor or skeletal animation other DCC tools.
* The data is divided in different levels: tracks, key frames, curves.
*/
@ccclass('cc.AnimationClip')
export class AnimationClip extends Asset {
public static WrapMode = AnimationWrapMode;
/**
* @en Crate clip with a set of sprite frames
* @zh 使用一组序列帧图片来创建动画剪辑
* @example
* ```
* import { AnimationClip } from 'cc';
* const clip = AnimationClip.createWithSpriteFrames(spriteFrames, 10);
* ```
*/
public static createWithSpriteFrames (spriteFrames: SpriteFrame[], sample: number) {
const clip = new AnimationClip();
clip.sample = sample || clip.sample;
clip.duration = spriteFrames.length / clip.sample;
const step = 1 / clip.sample;
const track = new ObjectTrack<SpriteFrame>();
track.path = new TrackPath().toComponent('cc.Sprite').toProperty('spriteFrame');
const curve = track.channels()[0].curve;
curve.assignSorted(spriteFrames.map((spriteFrame, index) => [step * index, spriteFrame]));
clip.addTrack(track);
return clip;
}
/**
* @zh 动画帧率,单位为帧/秒。注意此属性仅用于编辑器动画编辑。
* @en Animation frame rate: frames per second.
* Note this property is only used for animation editing in Editor.
*/
@serializable
public sample = 60;
/**
* @zh 动画的播放速度。
* @en Animation playback speed.
*/
@serializable
public speed = 1;
/**
* @zh 动画的循环模式。
* @en Animation loop mode.
*/
@serializable
public wrapMode = AnimationWrapMode.Normal;
/**
* Sets if node TRS curves in this animation can be blended.
* Normally this flag is enabled for model animation and disabled for other case.
* @internal This is an internal slot. Never use it in your code.
*/
@serializable
public enableTrsBlending = false;
/**
* @zh 动画的周期。
* @en Animation duration.
*/
get duration () {
return this._duration;
}
set duration (value) {
this._duration = value;
}
/**
* @en
* Gets the count of tracks this animation owns.
* @zh
* 获取此动画中的轨道数量。
*/
get tracksCount () {
return this._tracks.length;
}
/**
* @en
* Gets an iterable to tracks.
* @zh
* 获取可用于迭代轨道的对象。
*/
get tracks (): Iterable<Track> {
return this._tracks;
}
get hash () {
// hashes should already be computed offline, but if not, make one
if (this._hash) { return this._hash; }
// Only hash exotic animations(including skeletal animations imported from model file).
// The behavior is consistent with how `.hash` implemented prior to 3.3.
const hashString = `Exotic:${this._exoticAnimation?.toHashString() ?? ''}`;
return this._hash = murmurhash2_32_gc(hashString, 666);
}
/**
* @zh 动画包含的事件数据。
* @en Associated event data.
*/
get events () {
return this._events;
}
set events (value) {
this._events = value;
const ratios: number[] = [];
const eventGroups: IAnimationEventGroup[] = [];
const events = this.events.sort((a, b) => a.frame - b.frame);
const nEvents = events.length;
for (let iEvent = 0; iEvent < nEvents; ++iEvent) {
const eventData = events[iEvent];
const ratio = eventData.frame / this._duration;
let i = ratios.findIndex((r) => r === ratio);
if (i < 0) {
i = ratios.length;
ratios.push(ratio);
eventGroups.push({
events: [],
});
}
eventGroups[i].events.push({
functionName: eventData.func,
parameters: eventData.params,
});
}
this._runtimeEvents = {
ratios,
eventGroups,
};
}
get [exoticAnimationTag] () {
return this._exoticAnimation;
}
set [exoticAnimationTag] (value) {
this._exoticAnimation = value;
}
/**
* Accesses the additive animation settings.
*/
get [additiveSettingsTag] () {
return this._additiveSettings;
}
public onLoaded () {
this.frameRate = this.sample;
this.events = this._events;
}
/**
* @en
* Counts the time range that the tracks within this animation span.
* @zh
* 获取此动画所有轨道占据的时间范围。
* @returns The time range.
*/
public range () {
const range: Range = { min: Infinity, max: -Infinity };
const { _tracks: tracks } = this;
const nTracks = tracks.length;
for (let iTrack = 0; iTrack < nTracks; ++iTrack) {
const track = tracks[iTrack];
const trackRange = track.range();
range.min = Math.min(range.min, trackRange.min);
range.max = Math.max(range.max, trackRange.max);
}
return range;
}
/**
* @en
* Gets the specified track.
* @zh
* 获取指定的轨道。
* @param index Index to the track.
* @returns The track.
*/
public getTrack (index: number) {
return this._tracks[index];
}
/**
* @en
* Adds a track into this animation.
* @zh
* 添加一个轨道到此动画中。
* @param track The track.
* @returns Index to the track.
*/
public addTrack (track: Track) {
const index = this._tracks.length;
this._tracks.push(track);
return index;
}
/**
* @en
* Removes a track from this animation.
* @zh
* 移除此动画中的指定轨道。
* @param index Index to the track.
*/
public removeTrack (index: number) {
this._tracks.splice(index, 1);
}
/**
* @en
* Removes all tracks from this animation.
* @zh
* 移除此动画的所有轨道。
*/
public clearTracks () {
this._tracks.length = 0;
}
/**
* Returns if this clip has any event.
* @internal Do not use this in your code.
*/
public containsAnyEvent () {
return this._events.length !== 0;
}
/**
* Creates an event evaluator for this animation.
* @param targetNode Target node used to fire events.
* @internal Do not use this in your code.
*/
public createEventEvaluator (targetNode: Node) {
return new EventEvaluator(
targetNode,
this._runtimeEvents.ratios,
this._runtimeEvents.eventGroups,
this.wrapMode,
);
}
/**
* Returns if this clip has any embedded player.
* @internal Do not use this in your code.
*/
public containsAnyEmbeddedPlayer () {
return this._embeddedPlayers.length !== 0;
}
/**
* Creates an embedded player evaluator for this animation.
* @param targetNode Target node.
* @internal Do not use this in your code.
*/
public createEmbeddedPlayerEvaluator (targetNode: Node) {
return new EmbeddedPlayerEvaluation(
this._embeddedPlayers,
targetNode,
);
}
/**
* Creates an evaluator for this animation.
* @param context The context.
* @returns The evaluator.
* @internal Do not use this in your code.
*/
public createEvaluator (context: AnimationClipEvalContext) {
const {
target,
} = context;
const binder: Binder = (binding: TrackBinding) => {
if (context.mask && binding.isMaskedOff(context.mask)) {
return undefined;
}
const trackTarget = binding.createRuntimeBinding(
target,
this.enableTrsBlending ? context.pose : undefined,
false,
);
if (DEBUG && !trackTarget) {
// If we got a null track target here, we should already have warn logged,
// To elaborate on error details, we warn here as well.
// Note: if in the future this log appears alone,
// it must be a BUG which break promise by above statement.
warnID(
3937,
this.name,
(context.target instanceof Node) ? context.target.name : context.target,
);
}
return trackTarget ?? undefined;
};
return this._createEvalWithBinder(target, binder, context.rootMotion);
}
public destroy () {
if (cclegacy.director.root?.dataPoolManager) {
(cclegacy.director.root.dataPoolManager).releaseAnimationClip(this);
}
SkelAnimDataHub.destroy(this);
return super.destroy();
}
public [BAKE_SKELETON_CURVE_SYMBOL] (start: number, samples: number, frames: number): SkeletonAnimationBakeInfo {
const step = 1.0 / samples;
const animatedJoints = this._collectAnimatedJoints();
const nAnimatedJoints = animatedJoints.length;
const jointsBakeInfo: Record<string, {
transforms: Mat4[];
}> = {};
for (let iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
const joint = animatedJoints[iAnimatedJoint];
jointsBakeInfo[joint] = {
transforms: Array.from({ length: frames }, () => new Mat4()),
};
}
const skeletonFrames = animatedJoints.reduce((result, joint) => {
result[joint] = new BoneGlobalTransform();
return result;
}, {} as Record<string, BoneGlobalTransform>);
for (const joint in skeletonFrames) {
const skeletonFrame = skeletonFrames[joint];
const parentJoint = joint.lastIndexOf('/');
if (parentJoint >= 0) {
const parentJointName = joint.substring(0, parentJoint);
const parentJointFrame = skeletonFrames[parentJointName];
// Parent joint can be nil since some of joints' parents
// are not in animation list. For example, joints under socket nodes.
if (parentJointFrame) {
skeletonFrame.parent = parentJointFrame;
}
}
}
const binder: Binder = (binding: TrackBinding) => {
const trsPath = binding.parseTrsPath();
if (!trsPath) {
return undefined;
}
const jointFrame = skeletonFrames[trsPath.node];
if (!jointFrame) {
return undefined;
}
return createBoneTransformBinding(jointFrame, trsPath.property);
};
const evaluator = this._createEvalWithBinder(undefined, binder, undefined);
for (let iFrame = 0; iFrame < frames; ++iFrame) {
const time = start + step * iFrame;
evaluator.evaluate(time);
for (let iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
const joint = animatedJoints[iAnimatedJoint];
Mat4.copy(
jointsBakeInfo[joint].transforms[iFrame],
skeletonFrames[joint].globalTransform,
);
}
for (let iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
const joint = animatedJoints[iAnimatedJoint];
skeletonFrames[joint].invalidate();
}
}
return {
samples,
frames,
joints: jointsBakeInfo,
};
}
/**
* Convert all untyped tracks into typed ones and delete the original.
* @param refine How to decide the type on specified path.
* @internal DO NOT USE THIS IN YOUR CODE.
*/
public upgradeUntypedTracks (refine: UntypedTrackRefine) {
const newTracks: Track[] = [];
const removals: Track[] = [];
const { _tracks: tracks } = this;
const nTracks = tracks.length;
for (let iTrack = 0; iTrack < nTracks; ++iTrack) {
const track = tracks[iTrack];
if (!(track instanceof UntypedTrack)) {
continue;
}
const newTrack = track.upgrade(refine);
if (newTrack) {
newTracks.push(newTrack);
removals.push(track);
}
}
const nRemovalTracks = removals.length;
for (let iRemovalTrack = 0; iRemovalTrack < nRemovalTracks; ++iRemovalTrack) {
js.array.remove(tracks, removals[iRemovalTrack]);
}
tracks.push(...newTracks);
}
/**
* @internal Export for test.
*/
public [searchForRootBonePathSymbol] () {
return this._searchForRootBonePath();
}
// #region Legacy area
// The following are significantly refactored and deprecated since 3.3.
// We deprecates the direct exposure of keys, values, events.
// Instead, we use track to organize them together.
/**
* @zh 曲线可引用的所有时间轴。
* @en Frame keys referenced by curves.
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
get keys () {
return this._getLegacyData().keys;
}
set keys (value) {
this._legacyDataDirty = true;
this._getLegacyData().keys = value;
}
/**
* @zh 此动画包含的所有曲线。
* @en Curves this animation contains.
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
get curves () {
this._legacyDataDirty = true;
return this._getLegacyData().curves;
}
set curves (value) {
this._getLegacyData().curves = value;
}
/**
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
get commonTargets () {
return this._getLegacyData().commonTargets;
}
set commonTargets (value) {
this._legacyDataDirty = true;
this._getLegacyData().commonTargets = value;
}
/**
* @en
* The animation's data.
* @zh
* 此动画的数据。
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
get data () {
return this._getLegacyData().data;
}
/**
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
public getPropertyCurves () {
return this._getLegacyData().getPropertyCurves();
}
/**
* @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
get eventGroups (): readonly IAnimationEventGroup[] {
return this._runtimeEvents.eventGroups;
}
/**
* @zh 提交事件数据的修改。
* 当你修改了 `this.events` 时,必须调用 `this.updateEventDatas()` 使修改生效。
* @en
* Commit event data update.
* You should call this function after you changed the `events` data to take effect.
* @deprecated Since V3.3. Please Assign to `this.events`.
*/
public updateEventDatas () {
this.events = this._events;
}
/**
* @zh 返回本动画是否包含事件数据。
* @en Returns if this animation contains event data.
* @protected
*/
public hasEvents () {
return this.events.length !== 0;
}
/**
* Migrates legacy data into tracks.
* NOTE: This method tend to be used as internal purpose or patch.
* DO NOT use it in your code since it might be removed for the future at any time.
* @internal Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3.
*/
public syncLegacyData () {
if (this._legacyData) {
this._fromLegacy(this._legacyData);
this._legacyData = undefined;
}
}
// #endregion
/**
* @internal
*/
get [embeddedPlayerCountTag] () {
return this._embeddedPlayers.length;
}
/**
* @internal
*/
public [getEmbeddedPlayersTag] (): Iterable<EmbeddedPlayer> {
return this._embeddedPlayers;
}
/**
* @internal
*/
public [addEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) {
this._embeddedPlayers.push(embeddedPlayer);
}
/**
* @internal
*/
public [removeEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) {
const iEmbeddedPlayer = this._embeddedPlayers.indexOf(embeddedPlayer);
if (iEmbeddedPlayer >= 0) {
this._embeddedPlayers.splice(iEmbeddedPlayer, 1);
}
}
/**
* @internal
*/
public [clearEmbeddedPlayersTag] () {
this._embeddedPlayers.length = 0;
}
/**
* @zh 获取此动画剪辑中的辅助曲线数量。
* @en Gets the count of auxiliary curves within this animation clip.
*/
public get auxiliaryCurveCount_experimental () {
return this._auxiliaryCurveEntries.length;
}
/**
* @zh 返回此动画剪辑中所有辅助曲线的名称。
* @en Returns names of all auxiliary curves within this animation clip.
*/
public getAuxiliaryCurveNames_experimental (): readonly string[] {
return this._auxiliaryCurveEntries.map((entry) => entry.name);
}
/**
* @zh 返回此动画剪辑中是否存在指定的辅助曲线。
* @en Returns if the specified auxiliary curve exists in this animation clip.
*/
public hasAuxiliaryCurve_experimental (name: string) {
return !!this._findAuxiliaryCurveEntry(name);
}
/**
* @zh 添加一条辅助曲线。如果已存在同名的辅助曲线,则直接返回。
* @en Adds an auxiliary curve. Directly return if there is already such named auxiliary curve.
* @param name @zh 辅助曲线的名称。@en The auxiliary curve's name.
* @returns @zh 新增或已存在的辅助曲线。 @en The newly created or existing auxiliary curve.
* @experimental
*/
public addAuxiliaryCurve_experimental (name: string): RealCurve {
let entry = this._findAuxiliaryCurveEntry(name);
if (!entry) {
entry = new AuxiliaryCurveEntry();
entry.name = name;
this._auxiliaryCurveEntries.push(entry);
}
return entry.curve;
}
/**
* @zh 获取指定的辅助曲线。
* @en Gets the specified auxiliary curve.
* @param name @zh 辅助曲线的名称。@en The auxiliary curve's name.
* @returns @zh 指定的辅助曲线。@en The specified auxiliary curve.
* @experimental
*/
public getAuxiliaryCurve_experimental (name: string) {
const entry = this._findAuxiliaryCurveEntry(name);
assertIsTrue(entry);
return entry.curve;
}
/**
* @zh 重命名指定的辅助曲线。
* @en Renames the specified auxiliary curve.
* @param name @zh 要重命名的辅助曲线的名称。@en Name of the auxiliary curve to rename.
* @param newName @zh 新名称。@en New name.
*/
public renameAuxiliaryCurve_experimental (name: string, newName: string) {
const entry = this._findAuxiliaryCurveEntry(name);
if (entry) {
entry.name = newName;
}
}
/**
* @zh 移除指定的辅助曲线。
* @en Removes the specified auxiliary curve.
* @param name @zh 辅助曲线的名称。@en The auxiliary curve's name.
* @experimental
*/
public removeAuxiliaryCurve_experimental (name: string) {
removeIf(this._auxiliaryCurveEntries, (entry) => entry.name === name);
}
/**
* @internal
*/
public _trySyncLegacyData () {
if (this._legacyDataDirty) {
this._legacyDataDirty = false;
this.syncLegacyData();
}
}
@serializable
private _duration = 0;
@serializable
private _hash = 0;
private frameRate = 0;
@serializable
private _tracks: Track[] = [];
@serializable
private _exoticAnimation: ExoticAnimation | null = null;
private _legacyData: legacy.AnimationClipLegacyData | undefined = undefined;
private _legacyDataDirty = false;
@serializable
private _events: AnimationClip.IEvent[] = [];
@serializable
private _embeddedPlayers: EmbeddedPlayer[] = [];
@serializable
private _additiveSettings = new AdditiveSettings();
@serializable
private _auxiliaryCurveEntries: AuxiliaryCurveEntry[] = [];
private _runtimeEvents: {
ratios: number[];
eventGroups: IAnimationEventGroup[];
} = {
ratios: [],
eventGroups: [],
};
private _createEvalWithBinder (target: unknown, binder: Binder, rootMotionOptions: RootMotionOptions | undefined) {
if (this._legacyDataDirty) {
this._legacyDataDirty = false;
this.syncLegacyData();
}
const rootMotionTrackExcludes: Track[] = [];
let rootMotionEvaluation: RootMotionEvaluation | undefined;
if (rootMotionOptions) {
rootMotionEvaluation = this._createRootMotionEvaluation(
target,
rootMotionOptions,
rootMotionTrackExcludes,
);
}
const trackEvalStatues: TrackEvalStatus<unknown>[] = [];
let exoticAnimationEvaluator: ExoticAnimationEvaluator | undefined;
const { _tracks: tracks } = this;
const nTracks = tracks.length;
for (let iTrack = 0; iTrack < nTracks; ++iTrack) {
const track = tracks[iTrack];
if (rootMotionTrackExcludes.includes(track)) {
continue;
}
if (Array.from(track.channels()).every(({ curve }) => curve.keyFramesCount === 0)) {
continue;
}
const runtimeBinding = binder(track[trackBindingTag]);
if (!runtimeBinding) {
continue;
}
let trackEval: TrackEval<unknown>;
if (!(track instanceof UntypedTrack)) {
trackEval = track[createEvalSymbol]();
} else {
// Handle untyped track specially.
if (!runtimeBinding.getValue) {
// If we can not get a value from binding,
// we're not able to instantiate the untyped track.
// This matches the behavior prior to V3.3.
errorID(3930);
continue;
}
const hintValue = runtimeBinding.getValue();
trackEval = track.createLegacyEval(hintValue);
}
trackEvalStatues.push(new TrackEvalStatus(runtimeBinding, trackEval));
}
if (this._exoticAnimation) {
exoticAnimationEvaluator = this._exoticAnimation.createEvaluator(binder);
}
const evaluation = new AnimationClipEvaluation(
trackEvalStatues,
exoticAnimationEvaluator,
rootMotionEvaluation,
);
return evaluation;
}
private _createRootMotionEvaluation (
target: unknown,
rootMotionOptions: RootMotionOptions,
rootMotionTrackExcludes: Track[],
) {
if (!(target instanceof Node)) {
errorID(3920);
return undefined;
}
const rootBonePath = this._searchForRootBonePath();
if (!rootBonePath) {
warnID(3923);
return undefined;
}
const rootBone = target.getChildByPath(rootBonePath);
if (!rootBone) {
warnID(3924);
return undefined;
}
// const { } = rootMotionOptions;
const boneTransform = new BoneTransform();
const rootMotionsTrackEvaluations: TrackEvalStatus<unknown>[] = [];
const { _tracks: tracks } = this;
const nTracks = tracks.length;
for (let iTrack = 0; iTrack < nTracks; ++iTrack) {
const track = tracks[iTrack];
const { [trackBindingTag]: trackBinding } = track;
const trsPath = trackBinding.parseTrsPath();
if (!trsPath) {
continue;
}
const bonePath = trsPath.node;
if (bonePath !== rootBonePath) {
continue;
}
rootMotionTrackExcludes.push(track);
const property = trsPath.property;
const runtimeBinding = createBoneTransformBinding(boneTransform, property);
if (!runtimeBinding) {
continue;
}
const trackEval = track[createEvalSymbol]();
rootMotionsTrackEvaluations.push(new TrackEvalStatus(runtimeBinding, trackEval));
}
const rootMotionEvaluation = new RootMotionEvaluation(
rootBone,
this._duration,
boneTransform,
rootMotionsTrackEvaluations,
);
return rootMotionEvaluation;
}
private _searchForRootBonePath () {
const paths = this._tracks.map((track) => {
const trsPath = track[trackBindingTag].parseTrsPath();
if (trsPath) {
const nodePath = trsPath.node;
return {
path: nodePath,
rank: nodePath.split('/').length,
};
} else {
return {
path: '',
rank: 0,
};
}
});
paths.sort((a, b) => a.rank - b.rank);
const iNonEmptyPath = paths.findIndex((p) => p.rank !== 0);
if (iNonEmptyPath < 0) {
return '';
}
const nPaths = paths.length;
const firstPath = paths[iNonEmptyPath];
let highestPathsAreSame = true;
for (let iPath = iNonEmptyPath + 1; iPath < nPaths; ++iPath) {
const path = paths[iPath];
if (path.rank !== firstPath.rank) {
break;
}
if (path.path !== firstPath.path) {
highestPathsAreSame = false;
break;
}
}
return highestPathsAreSame ? firstPath.path : '';
}
private _getLegacyData () {
if (!this._legacyData) {
this._legacyData = this._toLegacy();
}
return this._legacyData;
}
private _toLegacy (): legacy.AnimationClipLegacyData {
const keys: number[][] = [];
const legacyCurves: legacy.LegacyClipCurve[] = [];
const commonTargets: legacy.LegacyCommonTarget[] = [];
const legacyClipData = new legacy.AnimationClipLegacyData(this._duration);
legacyClipData.keys = keys;
legacyClipData.curves = legacyCurves;
legacyClipData.commonTargets = commonTargets;
return legacyClipData;
}
private _fromLegacy (legacyData: legacy.AnimationClipLegacyData) {
const newTracks = legacyData.toTracks();
const nNewTracks = newTracks.length;
for (let iNewTrack = 0; iNewTrack < nNewTracks; ++iNewTrack) {
this.addTrack(newTracks[iNewTrack]);
}
}
private _collectAnimatedJoints () {
const joints = new Set<string>();
const { _tracks: tracks } = this;
const nTracks = tracks.length;
for (let iTrack = 0; iTrack < nTracks; ++iTrack) {
const track = tracks[iTrack];
const trsPath = track[trackBindingTag].parseTrsPath();
if (trsPath) {
joints.add(trsPath.node);
}
}
if (this._exoticAnimation) {
const animatedJoints = this._exoticAnimation.collectAnimatedJoints();
const nAnimatedJoints = animatedJoints.length;
for (let iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
joints.add(animatedJoints[iAnimatedJoint]);
}
}