AnimationTrack.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Animations;
  4. using UnityEngine.Experimental.Animations;
  5. using UnityEngine.Playables;
  6. using UnityEngine.Serialization;
  7. #if UNITY_EDITOR
  8. using UnityEditor;
  9. #endif
  10. namespace UnityEngine.Timeline
  11. {
  12. /// <summary>
  13. /// Flags specifying which offset fields to match
  14. /// </summary>
  15. [Flags]
  16. public enum MatchTargetFields
  17. {
  18. /// <summary>
  19. /// Translation X value
  20. /// </summary>
  21. PositionX = 1 << 0,
  22. /// <summary>
  23. /// Translation Y value
  24. /// </summary>
  25. PositionY = 1 << 1,
  26. /// <summary>
  27. /// Translation Z value
  28. /// </summary>
  29. PositionZ = 1 << 2,
  30. /// <summary>
  31. /// Rotation Euler Angle X value
  32. /// </summary>
  33. RotationX = 1 << 3,
  34. /// <summary>
  35. /// Rotation Euler Angle Y value
  36. /// </summary>
  37. RotationY = 1 << 4,
  38. /// <summary>
  39. /// Rotation Euler Angle Z value
  40. /// </summary>
  41. RotationZ = 1 << 5
  42. }
  43. /// <summary>
  44. /// Describes what is used to set the starting position and orientation of each Animation Track.
  45. /// </summary>
  46. /// <remarks>
  47. /// By default, each Animation Track uses ApplyTransformOffsets to start from a set position and orientation.
  48. /// To offset each Animation Track based on the current position and orientation in the scene, use ApplySceneOffsets.
  49. /// </remarks>
  50. public enum TrackOffset
  51. {
  52. /// <summary>
  53. /// Use this setting to offset each Animation Track based on a set position and orientation.
  54. /// </summary>
  55. ApplyTransformOffsets,
  56. /// <summary>
  57. /// Use this setting to offset each Animation Track based on the current position and orientation in the scene.
  58. /// </summary>
  59. ApplySceneOffsets,
  60. /// <summary>
  61. /// Use this setting to offset root transforms based on the state of the animator.
  62. /// </summary>
  63. /// <remarks>
  64. /// Only use this setting to support legacy Animation Tracks. This mode may be deprecated in a future release.
  65. ///
  66. /// In Auto mode, when the animator bound to the animation track contains an AnimatorController, it offsets all animations similar to ApplySceneOffsets.
  67. /// If no controller is assigned, then all offsets are set to start from a fixed position and orientation, similar to ApplyTransformOffsets.
  68. /// In Auto mode, in most cases, root transforms are not affected by local scale or Animator.humanScale, unless the animator has an AnimatorController and Animator.applyRootMotion is set to true.
  69. /// </remarks>
  70. Auto
  71. }
  72. // offset mode
  73. enum AppliedOffsetMode
  74. {
  75. NoRootTransform,
  76. TransformOffset,
  77. SceneOffset,
  78. TransformOffsetLegacy,
  79. SceneOffsetLegacy,
  80. SceneOffsetEditor, // scene offset mode in editor
  81. SceneOffsetLegacyEditor,
  82. }
  83. // separate from the enum to hide them from UI elements
  84. static class MatchTargetFieldConstants
  85. {
  86. public static MatchTargetFields All = MatchTargetFields.PositionX | MatchTargetFields.PositionY |
  87. MatchTargetFields.PositionZ | MatchTargetFields.RotationX |
  88. MatchTargetFields.RotationY | MatchTargetFields.RotationZ;
  89. public static MatchTargetFields None = 0;
  90. public static MatchTargetFields Position = MatchTargetFields.PositionX | MatchTargetFields.PositionY |
  91. MatchTargetFields.PositionZ;
  92. public static MatchTargetFields Rotation = MatchTargetFields.RotationX | MatchTargetFields.RotationY |
  93. MatchTargetFields.RotationZ;
  94. public static bool HasAny(this MatchTargetFields me, MatchTargetFields fields)
  95. {
  96. return (me & fields) != None;
  97. }
  98. public static MatchTargetFields Toggle(this MatchTargetFields me, MatchTargetFields flag)
  99. {
  100. return me ^ flag;
  101. }
  102. }
  103. /// <summary>
  104. /// A Timeline track used for playing back animations on an Animator.
  105. /// </summary>
  106. [Serializable]
  107. [TrackClipType(typeof(AnimationPlayableAsset), false)]
  108. [TrackBindingType(typeof(Animator))]
  109. [ExcludeFromPreset]
  110. public partial class AnimationTrack : TrackAsset, ILayerable
  111. {
  112. const string k_DefaultInfiniteClipName = "Recorded";
  113. const string k_DefaultRecordableClipName = "Recorded";
  114. [SerializeField, FormerlySerializedAs("m_OpenClipPreExtrapolation")]
  115. TimelineClip.ClipExtrapolation m_InfiniteClipPreExtrapolation = TimelineClip.ClipExtrapolation.None;
  116. [SerializeField, FormerlySerializedAs("m_OpenClipPostExtrapolation")]
  117. TimelineClip.ClipExtrapolation m_InfiniteClipPostExtrapolation = TimelineClip.ClipExtrapolation.None;
  118. [SerializeField, FormerlySerializedAs("m_OpenClipOffsetPosition")]
  119. Vector3 m_InfiniteClipOffsetPosition = Vector3.zero;
  120. [SerializeField, FormerlySerializedAs("m_OpenClipOffsetEulerAngles")]
  121. Vector3 m_InfiniteClipOffsetEulerAngles = Vector3.zero;
  122. [SerializeField, FormerlySerializedAs("m_OpenClipTimeOffset")]
  123. double m_InfiniteClipTimeOffset;
  124. [SerializeField, FormerlySerializedAs("m_OpenClipRemoveOffset")]
  125. bool m_InfiniteClipRemoveOffset; // cached value for remove offset
  126. [SerializeField]
  127. bool m_InfiniteClipApplyFootIK = true;
  128. [SerializeField, HideInInspector]
  129. AnimationPlayableAsset.LoopMode mInfiniteClipLoop = AnimationPlayableAsset.LoopMode.UseSourceAsset;
  130. [SerializeField]
  131. MatchTargetFields m_MatchTargetFields = MatchTargetFieldConstants.All;
  132. [SerializeField]
  133. Vector3 m_Position = Vector3.zero;
  134. [SerializeField]
  135. Vector3 m_EulerAngles = Vector3.zero;
  136. [SerializeField] AvatarMask m_AvatarMask;
  137. [SerializeField] bool m_ApplyAvatarMask = true;
  138. [SerializeField] TrackOffset m_TrackOffset = TrackOffset.ApplyTransformOffsets;
  139. [SerializeField, HideInInspector] AnimationClip m_InfiniteClip;
  140. #if UNITY_EDITOR
  141. private AnimationClip m_DefaultPoseClip;
  142. private AnimationClip m_CachedPropertiesClip;
  143. private int m_CachedHash;
  144. private EditorCurveBinding[] m_CachedBindings;
  145. AnimationOffsetPlayable m_ClipOffset;
  146. private Vector3 m_SceneOffsetPosition = Vector3.zero;
  147. private Vector3 m_SceneOffsetRotation = Vector3.zero;
  148. private bool m_HasPreviewComponents = false;
  149. #endif
  150. /// <summary>
  151. /// The translation offset of the entire track.
  152. /// </summary>
  153. public Vector3 position
  154. {
  155. get { return m_Position; }
  156. set { m_Position = value; }
  157. }
  158. /// <summary>
  159. /// The rotation offset of the entire track, expressed as a quaternion.
  160. /// </summary>
  161. public Quaternion rotation
  162. {
  163. get { return Quaternion.Euler(m_EulerAngles); }
  164. set { m_EulerAngles = value.eulerAngles; }
  165. }
  166. /// <summary>
  167. /// The euler angle representation of the rotation offset of the entire track.
  168. /// </summary>
  169. public Vector3 eulerAngles
  170. {
  171. get { return m_EulerAngles; }
  172. set { m_EulerAngles = value; }
  173. }
  174. /// <summary>
  175. /// Specifies whether to apply track offsets to all clips on the track.
  176. /// </summary>
  177. /// <remarks>
  178. /// This can be used to offset all clips on a track, in addition to the clips individual offsets.
  179. /// </remarks>
  180. [Obsolete("applyOffset is deprecated. Use trackOffset instead", true)]
  181. public bool applyOffsets
  182. {
  183. get { return false; }
  184. set {}
  185. }
  186. /// <summary>
  187. /// Specifies what is used to set the starting position and orientation of an Animation Track.
  188. /// </summary>
  189. /// <remarks>
  190. /// Track Offset is only applied when the Animation Track contains animation that modifies the root Transform.
  191. /// </remarks>
  192. public TrackOffset trackOffset
  193. {
  194. get { return m_TrackOffset; }
  195. set { m_TrackOffset = value; }
  196. }
  197. /// <summary>
  198. /// Specifies which fields to match when aligning offsets of clips.
  199. /// </summary>
  200. public MatchTargetFields matchTargetFields
  201. {
  202. get { return m_MatchTargetFields; }
  203. set { m_MatchTargetFields = value & MatchTargetFieldConstants.All; }
  204. }
  205. /// <summary>
  206. /// An AnimationClip storing the data for an infinite track.
  207. /// </summary>
  208. /// <remarks>
  209. /// The value of this property is null when the AnimationTrack is in Clip Mode.
  210. /// </remarks>
  211. public AnimationClip infiniteClip
  212. {
  213. get { return m_InfiniteClip; }
  214. internal set { m_InfiniteClip = value; }
  215. }
  216. // saved value for converting to/from infinite mode
  217. internal bool infiniteClipRemoveOffset
  218. {
  219. get { return m_InfiniteClipRemoveOffset; }
  220. set { m_InfiniteClipRemoveOffset = value; }
  221. }
  222. /// <summary>
  223. /// Specifies the AvatarMask to be applied to all clips on the track.
  224. /// </summary>
  225. /// <remarks>
  226. /// Applying an AvatarMask to an animation track will allow discarding portions of the animation being applied on the track.
  227. /// </remarks>
  228. public AvatarMask avatarMask
  229. {
  230. get { return m_AvatarMask; }
  231. set { m_AvatarMask = value; }
  232. }
  233. /// <summary>
  234. /// Specifies whether to apply the AvatarMask to the track.
  235. /// </summary>
  236. public bool applyAvatarMask
  237. {
  238. get { return m_ApplyAvatarMask; }
  239. set { m_ApplyAvatarMask = value; }
  240. }
  241. // is this track compilable
  242. internal override bool CanCompileClips()
  243. {
  244. return !muted && (m_Clips.Count > 0 || (m_InfiniteClip != null && !m_InfiniteClip.empty));
  245. }
  246. /// <inheritdoc/>
  247. public override IEnumerable<PlayableBinding> outputs
  248. {
  249. get { yield return AnimationPlayableBinding.Create(name, this); }
  250. }
  251. /// <summary>
  252. /// Specifies whether the Animation Track has clips, or is in infinite mode.
  253. /// </summary>
  254. public bool inClipMode
  255. {
  256. get { return clips != null && clips.Length != 0; }
  257. }
  258. /// <summary>
  259. /// The translation offset of a track in infinite mode.
  260. /// </summary>
  261. public Vector3 infiniteClipOffsetPosition
  262. {
  263. get { return m_InfiniteClipOffsetPosition; }
  264. set { m_InfiniteClipOffsetPosition = value; }
  265. }
  266. /// <summary>
  267. /// The rotation offset of a track in infinite mode.
  268. /// </summary>
  269. public Quaternion infiniteClipOffsetRotation
  270. {
  271. get { return Quaternion.Euler(m_InfiniteClipOffsetEulerAngles); }
  272. set { m_InfiniteClipOffsetEulerAngles = value.eulerAngles; }
  273. }
  274. /// <summary>
  275. /// The euler angle representation of the rotation offset of the track when in infinite mode.
  276. /// </summary>
  277. public Vector3 infiniteClipOffsetEulerAngles
  278. {
  279. get { return m_InfiniteClipOffsetEulerAngles; }
  280. set { m_InfiniteClipOffsetEulerAngles = value; }
  281. }
  282. internal bool infiniteClipApplyFootIK
  283. {
  284. get { return m_InfiniteClipApplyFootIK; }
  285. set { m_InfiniteClipApplyFootIK = value; }
  286. }
  287. internal double infiniteClipTimeOffset
  288. {
  289. get { return m_InfiniteClipTimeOffset; }
  290. set { m_InfiniteClipTimeOffset = value; }
  291. }
  292. /// <summary>
  293. /// The saved state of pre-extrapolation for clips converted to infinite mode.
  294. /// </summary>
  295. public TimelineClip.ClipExtrapolation infiniteClipPreExtrapolation
  296. {
  297. get { return m_InfiniteClipPreExtrapolation; }
  298. set { m_InfiniteClipPreExtrapolation = value; }
  299. }
  300. /// <summary>
  301. /// The saved state of post-extrapolation for clips when converted to infinite mode.
  302. /// </summary>
  303. public TimelineClip.ClipExtrapolation infiniteClipPostExtrapolation
  304. {
  305. get { return m_InfiniteClipPostExtrapolation; }
  306. set { m_InfiniteClipPostExtrapolation = value; }
  307. }
  308. /// <summary>
  309. /// The saved state of animation clip loop state when converted to infinite mode
  310. /// </summary>
  311. internal AnimationPlayableAsset.LoopMode infiniteClipLoop
  312. {
  313. get { return mInfiniteClipLoop; }
  314. set { mInfiniteClipLoop = value; }
  315. }
  316. [ContextMenu("Reset Offsets")]
  317. void ResetOffsets()
  318. {
  319. m_Position = Vector3.zero;
  320. m_EulerAngles = Vector3.zero;
  321. UpdateClipOffsets();
  322. }
  323. /// <summary>
  324. /// Creates a TimelineClip on this track that uses an AnimationClip.
  325. /// </summary>
  326. /// <param name="clip">Source animation clip of the resulting TimelineClip.</param>
  327. /// <returns>A new TimelineClip which has an AnimationPlayableAsset asset attached.</returns>
  328. public TimelineClip CreateClip(AnimationClip clip)
  329. {
  330. if (clip == null)
  331. return null;
  332. var newClip = CreateClip<AnimationPlayableAsset>();
  333. AssignAnimationClip(newClip, clip);
  334. return newClip;
  335. }
  336. /// <summary>
  337. /// Creates an AnimationClip that stores the data for an infinite track.
  338. /// </summary>
  339. /// <remarks>
  340. /// If an infiniteClip already exists, this method produces no result, even if you provide a different value
  341. /// for infiniteClipName.
  342. /// </remarks>
  343. /// <remarks>
  344. /// This method can't create an infinite clip for an AnimationTrack that contains one or more Timeline clips.
  345. /// Use AnimationTrack.inClipMode to determine whether it is possible to create an infinite clip on an AnimationTrack.
  346. /// </remarks>
  347. /// <remarks>
  348. /// When used from the editor, this method attempts to save the created infinite clip to the TimelineAsset.
  349. /// The TimelineAsset must already exist in the AssetDatabase to save the infinite clip. If the TimelineAsset
  350. /// does not exist, the infinite clip is still created but it is not saved.
  351. /// </remarks>
  352. /// <param name="infiniteClipName">
  353. /// The name of the AnimationClip to create.
  354. /// This method does not ensure unique names. If you want a unique clip name, you must provide one.
  355. /// See ObjectNames.GetUniqueName for information on a method that creates unique names.
  356. /// </param>
  357. public void CreateInfiniteClip(string infiniteClipName)
  358. {
  359. if (inClipMode)
  360. {
  361. Debug.LogWarning("CreateInfiniteClip cannot create an infinite clip for an AnimationTrack that contains one or more Timeline Clips.");
  362. return;
  363. }
  364. if (m_InfiniteClip != null)
  365. return;
  366. m_InfiniteClip = TimelineCreateUtilities.CreateAnimationClipForTrack(string.IsNullOrEmpty(infiniteClipName) ? k_DefaultInfiniteClipName : infiniteClipName, this, false);
  367. }
  368. /// <summary>
  369. /// Creates a TimelineClip, AnimationPlayableAsset and an AnimationClip. Use this clip to record in a timeline.
  370. /// </summary>
  371. /// <remarks>
  372. /// When used from the editor, this method attempts to save the created recordable clip to the TimelineAsset.
  373. /// The TimelineAsset must already exist in the AssetDatabase to save the recordable clip. If the TimelineAsset
  374. /// does not exist, the recordable clip is still created but it is not saved.
  375. /// </remarks>
  376. /// <param name="animClipName">
  377. /// The name of the AnimationClip to create.
  378. /// This method does not ensure unique names. If you want a unique clip name, you must provide one.
  379. /// See ObjectNames.GetUniqueName for information on a method that creates unique names.
  380. /// </param>
  381. /// <returns>
  382. /// Returns a new TimelineClip with an AnimationPlayableAsset asset attached.
  383. /// </returns>
  384. public TimelineClip CreateRecordableClip(string animClipName)
  385. {
  386. var clip = TimelineCreateUtilities.CreateAnimationClipForTrack(string.IsNullOrEmpty(animClipName) ? k_DefaultRecordableClipName : animClipName, this, false);
  387. var timelineClip = CreateClip(clip);
  388. timelineClip.displayName = animClipName;
  389. timelineClip.recordable = true;
  390. timelineClip.start = 0;
  391. timelineClip.duration = 1;
  392. var apa = timelineClip.asset as AnimationPlayableAsset;
  393. if (apa != null)
  394. apa.removeStartOffset = false;
  395. return timelineClip;
  396. }
  397. #if UNITY_EDITOR
  398. internal Vector3 sceneOffsetPosition
  399. {
  400. get { return m_SceneOffsetPosition; }
  401. set { m_SceneOffsetPosition = value; }
  402. }
  403. internal Vector3 sceneOffsetRotation
  404. {
  405. get { return m_SceneOffsetRotation; }
  406. set { m_SceneOffsetRotation = value; }
  407. }
  408. internal bool hasPreviewComponents
  409. {
  410. get
  411. {
  412. if (m_HasPreviewComponents)
  413. return true;
  414. var parentTrack = parent as AnimationTrack;
  415. if (parentTrack != null)
  416. {
  417. return parentTrack.hasPreviewComponents;
  418. }
  419. return false;
  420. }
  421. }
  422. #endif
  423. /// <summary>
  424. /// Used to initialize default values on a newly created clip
  425. /// </summary>
  426. /// <param name="clip">The clip added to the track</param>
  427. protected override void OnCreateClip(TimelineClip clip)
  428. {
  429. var extrapolation = TimelineClip.ClipExtrapolation.None;
  430. if (!isSubTrack)
  431. extrapolation = TimelineClip.ClipExtrapolation.Hold;
  432. clip.preExtrapolationMode = extrapolation;
  433. clip.postExtrapolationMode = extrapolation;
  434. }
  435. protected internal override int CalculateItemsHash()
  436. {
  437. return GetAnimationClipHash(m_InfiniteClip).CombineHash(base.CalculateItemsHash());
  438. }
  439. internal void UpdateClipOffsets()
  440. {
  441. #if UNITY_EDITOR
  442. if (m_ClipOffset.IsValid())
  443. {
  444. m_ClipOffset.SetPosition(position);
  445. m_ClipOffset.SetRotation(rotation);
  446. }
  447. #endif
  448. }
  449. Playable CompileTrackPlayable(PlayableGraph graph, AnimationTrack track, GameObject go, IntervalTree<RuntimeElement> tree, AppliedOffsetMode mode)
  450. {
  451. var mixer = AnimationMixerPlayable.Create(graph, track.clips.Length);
  452. for (int i = 0; i < track.clips.Length; i++)
  453. {
  454. var c = track.clips[i];
  455. var asset = c.asset as PlayableAsset;
  456. if (asset == null)
  457. continue;
  458. var animationAsset = asset as AnimationPlayableAsset;
  459. if (animationAsset != null)
  460. animationAsset.appliedOffsetMode = mode;
  461. var source = asset.CreatePlayable(graph, go);
  462. if (source.IsValid())
  463. {
  464. var clip = new RuntimeClip(c, source, mixer);
  465. tree.Add(clip);
  466. graph.Connect(source, 0, mixer, i);
  467. mixer.SetInputWeight(i, 0.0f);
  468. }
  469. }
  470. if (!track.AnimatesRootTransform())
  471. return mixer;
  472. return ApplyTrackOffset(graph, mixer, go, mode);
  473. }
  474. /// <inheritdoc cref="ILayerable.CreateLayerMixer"/>
  475. /// <returns>Returns <c>Playable.Null</c></returns>
  476. Playable ILayerable.CreateLayerMixer(PlayableGraph graph, GameObject go, int inputCount)
  477. {
  478. return Playable.Null;
  479. }
  480. internal override Playable OnCreateClipPlayableGraph(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree)
  481. {
  482. if (isSubTrack)
  483. throw new InvalidOperationException("Nested animation tracks should never be asked to create a graph directly");
  484. List<AnimationTrack> flattenTracks = new List<AnimationTrack>();
  485. if (CanCompileClips())
  486. flattenTracks.Add(this);
  487. var genericRoot = GetGenericRootNode(go);
  488. var animatesRootTransformNoMask = AnimatesRootTransform();
  489. var animatesRootTransform = animatesRootTransformNoMask && !IsRootTransformDisabledByMask(go, genericRoot);
  490. foreach (var subTrack in GetChildTracks())
  491. {
  492. var child = subTrack as AnimationTrack;
  493. if (child != null && child.CanCompileClips())
  494. {
  495. var childAnimatesRoot = child.AnimatesRootTransform();
  496. animatesRootTransformNoMask |= child.AnimatesRootTransform();
  497. animatesRootTransform |= (childAnimatesRoot && !child.IsRootTransformDisabledByMask(go, genericRoot));
  498. flattenTracks.Add(child);
  499. }
  500. }
  501. // figure out which mode to apply
  502. AppliedOffsetMode mode = GetOffsetMode(go, animatesRootTransform);
  503. int defaultBlendCount = GetDefaultBlendCount();
  504. var layerMixer = CreateGroupMixer(graph, go, flattenTracks.Count + defaultBlendCount);
  505. for (int c = 0; c < flattenTracks.Count; c++)
  506. {
  507. int blendIndex = c + defaultBlendCount;
  508. // if the child is masking the root transform, compile it as if we are non-root mode
  509. var childMode = mode;
  510. if (mode != AppliedOffsetMode.NoRootTransform && flattenTracks[c].IsRootTransformDisabledByMask(go, genericRoot))
  511. childMode = AppliedOffsetMode.NoRootTransform;
  512. var compiledTrackPlayable = flattenTracks[c].inClipMode ?
  513. CompileTrackPlayable(graph, flattenTracks[c], go, tree, childMode) :
  514. flattenTracks[c].CreateInfiniteTrackPlayable(graph, go, tree, childMode);
  515. graph.Connect(compiledTrackPlayable, 0, layerMixer, blendIndex);
  516. layerMixer.SetInputWeight(blendIndex, flattenTracks[c].inClipMode ? 0 : 1);
  517. if (flattenTracks[c].applyAvatarMask && flattenTracks[c].avatarMask != null)
  518. {
  519. layerMixer.SetLayerMaskFromAvatarMask((uint)blendIndex, flattenTracks[c].avatarMask);
  520. }
  521. }
  522. var requiresMotionXPlayable = RequiresMotionXPlayable(mode, go);
  523. // In the editor, we may require the motion X playable if we are animating the root transform but it is masked out, because the default poses
  524. // need to properly update root motion
  525. requiresMotionXPlayable |= (defaultBlendCount > 0 && RequiresMotionXPlayable(GetOffsetMode(go, animatesRootTransformNoMask), go));
  526. // Attach the default poses
  527. AttachDefaultBlend(graph, layerMixer, requiresMotionXPlayable);
  528. // motionX playable not required in scene offset mode, or root transform mode
  529. Playable mixer = layerMixer;
  530. if (requiresMotionXPlayable)
  531. {
  532. // If we are animating a root transform, add the motionX to delta playable as the root node
  533. var motionXToDelta = AnimationMotionXToDeltaPlayable.Create(graph);
  534. graph.Connect(mixer, 0, motionXToDelta, 0);
  535. motionXToDelta.SetInputWeight(0, 1.0f);
  536. motionXToDelta.SetAbsoluteMotion(UsesAbsoluteMotion(mode));
  537. mixer = (Playable)motionXToDelta;
  538. }
  539. #if UNITY_EDITOR
  540. if (!Application.isPlaying)
  541. {
  542. var animator = GetBinding(go != null ? go.GetComponent<PlayableDirector>() : null);
  543. if (animator != null)
  544. {
  545. GameObject targetGO = animator.gameObject;
  546. IAnimationWindowPreview[] previewComponents = targetGO.GetComponents<IAnimationWindowPreview>();
  547. m_HasPreviewComponents = previewComponents.Length > 0;
  548. if (m_HasPreviewComponents)
  549. {
  550. foreach (var component in previewComponents)
  551. {
  552. mixer = component.BuildPreviewGraph(graph, mixer);
  553. }
  554. }
  555. }
  556. }
  557. #endif
  558. return mixer;
  559. }
  560. private int GetDefaultBlendCount()
  561. {
  562. #if UNITY_EDITOR
  563. if (Application.isPlaying)
  564. return 0;
  565. return ((m_CachedPropertiesClip != null) ? 1 : 0) + ((m_DefaultPoseClip != null) ? 1 : 0);
  566. #else
  567. return 0;
  568. #endif
  569. }
  570. // Attaches the default blends to the layer mixer
  571. // the base layer is a default clip of all driven properties
  572. // the next layer is optionally the desired default pose (in the case of humanoid, the TPose)
  573. private void AttachDefaultBlend(PlayableGraph graph, AnimationLayerMixerPlayable mixer, bool requireOffset)
  574. {
  575. #if UNITY_EDITOR
  576. if (Application.isPlaying)
  577. return;
  578. int mixerInput = 0;
  579. if (m_CachedPropertiesClip)
  580. {
  581. var cachedPropertiesClip = AnimationClipPlayable.Create(graph, m_CachedPropertiesClip);
  582. cachedPropertiesClip.SetApplyFootIK(false);
  583. var defaults = (Playable)cachedPropertiesClip;
  584. if (requireOffset)
  585. defaults = AttachOffsetPlayable(graph, defaults, m_SceneOffsetPosition, Quaternion.Euler(m_SceneOffsetRotation));
  586. graph.Connect(defaults, 0, mixer, mixerInput);
  587. mixer.SetInputWeight(mixerInput, 1.0f);
  588. mixerInput++;
  589. }
  590. if (m_DefaultPoseClip)
  591. {
  592. var defaultPose = AnimationClipPlayable.Create(graph, m_DefaultPoseClip);
  593. defaultPose.SetApplyFootIK(false);
  594. var blendDefault = (Playable)defaultPose;
  595. if (requireOffset)
  596. blendDefault = AttachOffsetPlayable(graph, blendDefault, m_SceneOffsetPosition, Quaternion.Euler(m_SceneOffsetRotation));
  597. graph.Connect(blendDefault, 0, mixer, mixerInput);
  598. mixer.SetInputWeight(mixerInput, 1.0f);
  599. }
  600. #endif
  601. }
  602. private Playable AttachOffsetPlayable(PlayableGraph graph, Playable playable, Vector3 pos, Quaternion rot)
  603. {
  604. var offsetPlayable = AnimationOffsetPlayable.Create(graph, pos, rot, 1);
  605. offsetPlayable.SetInputWeight(0, 1.0f);
  606. graph.Connect(playable, 0, offsetPlayable, 0);
  607. return offsetPlayable;
  608. }
  609. #if UNITY_EDITOR
  610. private static string k_DefaultHumanoidClipPath = "Packages/com.unity.timeline/Editor/StyleSheets/res/HumanoidDefault.anim";
  611. private static AnimationClip s_DefaultHumanoidClip = null;
  612. AnimationClip GetDefaultHumanoidClip()
  613. {
  614. if (s_DefaultHumanoidClip == null)
  615. {
  616. s_DefaultHumanoidClip = AssetDatabase.LoadAssetAtPath<AnimationClip>(k_DefaultHumanoidClipPath);
  617. if (s_DefaultHumanoidClip == null)
  618. Debug.LogError("Could not load default humanoid animation clip for Timeline");
  619. }
  620. return s_DefaultHumanoidClip;
  621. }
  622. #endif
  623. bool RequiresMotionXPlayable(AppliedOffsetMode mode, GameObject gameObject)
  624. {
  625. if (mode == AppliedOffsetMode.NoRootTransform)
  626. return false;
  627. if (mode == AppliedOffsetMode.SceneOffsetLegacy)
  628. {
  629. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  630. return animator != null && animator.hasRootMotion;
  631. }
  632. return true;
  633. }
  634. static bool UsesAbsoluteMotion(AppliedOffsetMode mode)
  635. {
  636. #if UNITY_EDITOR
  637. // in editor, previewing is always done in absolute motion
  638. if (!Application.isPlaying)
  639. return true;
  640. #endif
  641. return mode != AppliedOffsetMode.SceneOffset &&
  642. mode != AppliedOffsetMode.SceneOffsetLegacy;
  643. }
  644. bool HasController(GameObject gameObject)
  645. {
  646. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  647. return animator != null && animator.runtimeAnimatorController != null;
  648. }
  649. internal Animator GetBinding(PlayableDirector director)
  650. {
  651. if (director == null)
  652. return null;
  653. UnityEngine.Object key = this;
  654. if (isSubTrack)
  655. key = parent;
  656. UnityEngine.Object binding = null;
  657. if (director != null)
  658. binding = director.GetGenericBinding(key);
  659. Animator animator = null;
  660. if (binding != null) // the binding can be an animator or game object
  661. {
  662. animator = binding as Animator;
  663. var gameObject = binding as GameObject;
  664. if (animator == null && gameObject != null)
  665. animator = gameObject.GetComponent<Animator>();
  666. }
  667. return animator;
  668. }
  669. static AnimationLayerMixerPlayable CreateGroupMixer(PlayableGraph graph, GameObject go, int inputCount)
  670. {
  671. return AnimationLayerMixerPlayable.Create(graph, inputCount);
  672. }
  673. Playable CreateInfiniteTrackPlayable(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree, AppliedOffsetMode mode)
  674. {
  675. if (m_InfiniteClip == null)
  676. return Playable.Null;
  677. var mixer = AnimationMixerPlayable.Create(graph, 1);
  678. // In infinite mode, we always force the loop mode of the clip off because the clip keys are offset in infinite mode
  679. // which causes loop to behave different.
  680. // The inline curve editor never shows loops in infinite mode.
  681. var playable = AnimationPlayableAsset.CreatePlayable(graph, m_InfiniteClip, m_InfiniteClipOffsetPosition, m_InfiniteClipOffsetEulerAngles, false, mode, infiniteClipApplyFootIK, AnimationPlayableAsset.LoopMode.Off);
  682. if (playable.IsValid())
  683. {
  684. tree.Add(new InfiniteRuntimeClip(playable));
  685. graph.Connect(playable, 0, mixer, 0);
  686. mixer.SetInputWeight(0, 1.0f);
  687. }
  688. if (!AnimatesRootTransform())
  689. return mixer;
  690. var rootTrack = isSubTrack ? (AnimationTrack)parent : this;
  691. return rootTrack.ApplyTrackOffset(graph, mixer, go, mode);
  692. }
  693. Playable ApplyTrackOffset(PlayableGraph graph, Playable root, GameObject go, AppliedOffsetMode mode)
  694. {
  695. #if UNITY_EDITOR
  696. m_ClipOffset = AnimationOffsetPlayable.Null;
  697. #endif
  698. // offsets don't apply in scene offset, or if there is no root transform (globally or on this track)
  699. if (mode == AppliedOffsetMode.SceneOffsetLegacy ||
  700. mode == AppliedOffsetMode.SceneOffset ||
  701. mode == AppliedOffsetMode.NoRootTransform
  702. )
  703. return root;
  704. var pos = position;
  705. var rot = rotation;
  706. #if UNITY_EDITOR
  707. // in the editor use the preview position to playback from if available
  708. if (mode == AppliedOffsetMode.SceneOffsetEditor)
  709. {
  710. pos = m_SceneOffsetPosition;
  711. rot = Quaternion.Euler(m_SceneOffsetRotation);
  712. }
  713. #endif
  714. var offsetPlayable = AnimationOffsetPlayable.Create(graph, pos, rot, 1);
  715. #if UNITY_EDITOR
  716. m_ClipOffset = offsetPlayable;
  717. #endif
  718. graph.Connect(root, 0, offsetPlayable, 0);
  719. offsetPlayable.SetInputWeight(0, 1);
  720. return offsetPlayable;
  721. }
  722. // the evaluation time is large so that the properties always get evaluated
  723. internal override void GetEvaluationTime(out double outStart, out double outDuration)
  724. {
  725. if (inClipMode)
  726. {
  727. base.GetEvaluationTime(out outStart, out outDuration);
  728. }
  729. else
  730. {
  731. outStart = 0;
  732. outDuration = TimelineClip.kMaxTimeValue;
  733. }
  734. }
  735. internal override void GetSequenceTime(out double outStart, out double outDuration)
  736. {
  737. if (inClipMode)
  738. {
  739. base.GetSequenceTime(out outStart, out outDuration);
  740. }
  741. else
  742. {
  743. outStart = 0;
  744. outDuration = Math.Max(GetNotificationDuration(), TimeUtility.GetAnimationClipLength(m_InfiniteClip));
  745. }
  746. }
  747. void AssignAnimationClip(TimelineClip clip, AnimationClip animClip)
  748. {
  749. if (clip == null || animClip == null)
  750. return;
  751. if (animClip.legacy)
  752. throw new InvalidOperationException("Legacy Animation Clips are not supported");
  753. AnimationPlayableAsset asset = clip.asset as AnimationPlayableAsset;
  754. if (asset != null)
  755. {
  756. asset.clip = animClip;
  757. asset.name = animClip.name;
  758. var duration = asset.duration;
  759. if (!double.IsInfinity(duration) && duration >= TimelineClip.kMinDuration && duration < TimelineClip.kMaxTimeValue)
  760. clip.duration = duration;
  761. }
  762. clip.displayName = animClip.name;
  763. }
  764. /// <summary>
  765. /// Called by the Timeline Editor to gather properties requiring preview.
  766. /// </summary>
  767. /// <param name="director">The PlayableDirector invoking the preview</param>
  768. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  769. public override void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  770. {
  771. #if UNITY_EDITOR
  772. m_SceneOffsetPosition = Vector3.zero;
  773. m_SceneOffsetRotation = Vector3.zero;
  774. var animator = GetBinding(director);
  775. if (animator == null)
  776. return;
  777. var animClips = new List<AnimationClip>(this.clips.Length + 2);
  778. GetAnimationClips(animClips);
  779. var hasHumanMotion = animClips.Exists(clip => clip.humanMotion);
  780. // case 1174752 - recording root transform on humanoid clips clips cause invalid pose. This will apply the default T-Pose, only if it not already driven by another track
  781. if (!hasHumanMotion && animator.isHuman && AnimatesRootTransform() &&
  782. !DrivenPropertyManagerInternal.IsDriven(animator.transform, "m_LocalPosition.x") &&
  783. !DrivenPropertyManagerInternal.IsDriven(animator.transform, "m_LocalRotation.x"))
  784. hasHumanMotion = true;
  785. m_SceneOffsetPosition = animator.transform.localPosition;
  786. m_SceneOffsetRotation = animator.transform.localEulerAngles;
  787. // Create default pose clip from collected properties
  788. if (hasHumanMotion)
  789. animClips.Add(GetDefaultHumanoidClip());
  790. m_DefaultPoseClip = hasHumanMotion ? GetDefaultHumanoidClip() : null;
  791. var hash = AnimationPreviewUtilities.GetClipHash(animClips);
  792. if (m_CachedBindings == null || m_CachedHash != hash)
  793. {
  794. m_CachedBindings = AnimationPreviewUtilities.GetBindings(animator.gameObject, animClips);
  795. m_CachedPropertiesClip = AnimationPreviewUtilities.CreateDefaultClip(animator.gameObject, m_CachedBindings);
  796. m_CachedHash = hash;
  797. }
  798. AnimationPreviewUtilities.PreviewFromCurves(animator.gameObject, m_CachedBindings); // faster to preview from curves then an animation clip
  799. #endif
  800. }
  801. /// <summary>
  802. /// Gather all the animation clips for this track
  803. /// </summary>
  804. /// <param name="animClips"></param>
  805. private void GetAnimationClips(List<AnimationClip> animClips)
  806. {
  807. foreach (var c in clips)
  808. {
  809. var a = c.asset as AnimationPlayableAsset;
  810. if (a != null && a.clip != null)
  811. animClips.Add(a.clip);
  812. }
  813. if (m_InfiniteClip != null)
  814. animClips.Add(m_InfiniteClip);
  815. foreach (var childTrack in GetChildTracks())
  816. {
  817. var animChildTrack = childTrack as AnimationTrack;
  818. if (animChildTrack != null)
  819. animChildTrack.GetAnimationClips(animClips);
  820. }
  821. }
  822. // calculate which offset mode to apply
  823. AppliedOffsetMode GetOffsetMode(GameObject go, bool animatesRootTransform)
  824. {
  825. if (!animatesRootTransform)
  826. return AppliedOffsetMode.NoRootTransform;
  827. if (m_TrackOffset == TrackOffset.ApplyTransformOffsets)
  828. return AppliedOffsetMode.TransformOffset;
  829. if (m_TrackOffset == TrackOffset.ApplySceneOffsets)
  830. return (Application.isPlaying) ? AppliedOffsetMode.SceneOffset : AppliedOffsetMode.SceneOffsetEditor;
  831. if (HasController(go))
  832. {
  833. if (!Application.isPlaying)
  834. return AppliedOffsetMode.SceneOffsetLegacyEditor;
  835. return AppliedOffsetMode.SceneOffsetLegacy;
  836. }
  837. return AppliedOffsetMode.TransformOffsetLegacy;
  838. }
  839. private bool IsRootTransformDisabledByMask(GameObject gameObject, Transform genericRootNode)
  840. {
  841. if (avatarMask == null || !applyAvatarMask)
  842. return false;
  843. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  844. if (animator == null)
  845. return false;
  846. if (animator.isHuman)
  847. return !avatarMask.GetHumanoidBodyPartActive(AvatarMaskBodyPart.Root);
  848. if (avatarMask.transformCount == 0)
  849. return false;
  850. // no special root supplied
  851. if (genericRootNode == null)
  852. return string.IsNullOrEmpty(avatarMask.GetTransformPath(0)) && !avatarMask.GetTransformActive(0);
  853. // walk the avatar list to find the matching transform
  854. for (int i = 0; i < avatarMask.transformCount; i++)
  855. {
  856. if (genericRootNode == animator.transform.Find(avatarMask.GetTransformPath(i)))
  857. return !avatarMask.GetTransformActive(i);
  858. }
  859. return false;
  860. }
  861. // Returns the generic root transform node. Returns null if it is the root node, OR if it not a generic node
  862. private Transform GetGenericRootNode(GameObject gameObject)
  863. {
  864. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  865. if (animator == null)
  866. return null;
  867. if (animator.isHuman)
  868. return null;
  869. if (animator.avatar == null)
  870. return null;
  871. // this returns the bone name, but not the full path
  872. var rootName = animator.avatar.humanDescription.m_RootMotionBoneName;
  873. if (rootName == animator.name || string.IsNullOrEmpty(rootName))
  874. return null;
  875. // walk the hierarchy to find the first bone with this name
  876. return FindInHierarchyBreadthFirst(animator.transform, rootName);
  877. }
  878. internal bool AnimatesRootTransform()
  879. {
  880. // infinite mode
  881. if (AnimationPlayableAsset.HasRootTransforms(m_InfiniteClip))
  882. return true;
  883. // clip mode
  884. foreach (var c in GetClips())
  885. {
  886. var apa = c.asset as AnimationPlayableAsset;
  887. if (apa != null && apa.hasRootTransforms)
  888. return true;
  889. }
  890. return false;
  891. }
  892. private static readonly Queue<Transform> s_CachedQueue = new Queue<Transform>(100);
  893. private static Transform FindInHierarchyBreadthFirst(Transform t, string name)
  894. {
  895. s_CachedQueue.Clear();
  896. s_CachedQueue.Enqueue(t);
  897. while (s_CachedQueue.Count > 0)
  898. {
  899. var r = s_CachedQueue.Dequeue();
  900. if (r.name == name)
  901. return r;
  902. for (int i = 0; i < r.childCount; i++)
  903. s_CachedQueue.Enqueue(r.GetChild(i));
  904. }
  905. return null;
  906. }
  907. }
  908. }