TrackAsset.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Animations;
  4. using UnityEngine.Playables;
  5. namespace UnityEngine.Timeline
  6. {
  7. /// <summary>
  8. /// A PlayableAsset representing a track inside a timeline.
  9. /// </summary>
  10. ///
  11. /// <remarks>
  12. /// Derive from TrackAsset to implement custom timeline tracks. TrackAsset derived classes support the following attributes:
  13. /// <seealso cref="UnityEngine.Timeline.HideInMenuAttribute"/>
  14. /// <seealso cref="UnityEngine.Timeline.TrackColorAttribute"/>
  15. /// <seealso cref="UnityEngine.Timeline.TrackClipTypeAttribute"/>
  16. /// <seealso cref="UnityEngine.Timeline.TrackBindingTypeAttribute"/>
  17. /// <seealso cref="System.ComponentModel.DisplayNameAttribute"/>
  18. /// </remarks>
  19. ///
  20. /// <example>
  21. /// <code source="../../DocCodeExamples/TrackAssetExamples.cs" region="declare-trackAssetExample" title="TrackAssetExample"/>
  22. /// </example>
  23. [Serializable]
  24. [IgnoreOnPlayableTrack]
  25. public abstract partial class TrackAsset : PlayableAsset, IPropertyPreview, ICurvesOwner
  26. {
  27. // Internal caches used to avoid memory allocation during graph construction
  28. private struct TransientBuildData
  29. {
  30. public List<TrackAsset> trackList;
  31. public List<TimelineClip> clipList;
  32. public List<IMarker> markerList;
  33. public static TransientBuildData Create()
  34. {
  35. return new TransientBuildData()
  36. {
  37. trackList = new List<TrackAsset>(20),
  38. clipList = new List<TimelineClip>(500),
  39. markerList = new List<IMarker>(100),
  40. };
  41. }
  42. public void Clear()
  43. {
  44. trackList.Clear();
  45. clipList.Clear();
  46. markerList.Clear();
  47. }
  48. }
  49. private static TransientBuildData s_BuildData = TransientBuildData.Create();
  50. internal const string kDefaultCurvesName = "Track Parameters";
  51. internal static event Action<TimelineClip, GameObject, Playable> OnClipPlayableCreate;
  52. internal static event Action<TrackAsset, GameObject, Playable> OnTrackAnimationPlayableCreate;
  53. [SerializeField, HideInInspector] bool m_Locked;
  54. [SerializeField, HideInInspector] bool m_Muted;
  55. [SerializeField, HideInInspector] string m_CustomPlayableFullTypename = string.Empty;
  56. [SerializeField, HideInInspector] AnimationClip m_Curves;
  57. [SerializeField, HideInInspector] PlayableAsset m_Parent;
  58. [SerializeField, HideInInspector] List<ScriptableObject> m_Children;
  59. [NonSerialized] int m_ItemsHash;
  60. [NonSerialized] TimelineClip[] m_ClipsCache;
  61. DiscreteTime m_Start;
  62. DiscreteTime m_End;
  63. bool m_CacheSorted;
  64. bool? m_SupportsNotifications;
  65. static TrackAsset[] s_EmptyCache = new TrackAsset[0];
  66. IEnumerable<TrackAsset> m_ChildTrackCache;
  67. static Dictionary<Type, TrackBindingTypeAttribute> s_TrackBindingTypeAttributeCache = new Dictionary<Type, TrackBindingTypeAttribute>();
  68. [SerializeField, HideInInspector] protected internal List<TimelineClip> m_Clips = new List<TimelineClip>();
  69. [SerializeField, HideInInspector] MarkerList m_Markers = new MarkerList(0);
  70. #if UNITY_EDITOR
  71. internal int DirtyIndex { get; private set; }
  72. internal void MarkDirty()
  73. {
  74. DirtyIndex++;
  75. foreach (var clip in GetClips())
  76. {
  77. if (clip != null)
  78. clip.MarkDirty();
  79. }
  80. }
  81. #endif
  82. /// <summary>
  83. /// The start time, in seconds, of this track
  84. /// </summary>
  85. public double start
  86. {
  87. get
  88. {
  89. UpdateDuration();
  90. return (double)m_Start;
  91. }
  92. }
  93. /// <summary>
  94. /// The end time, in seconds, of this track
  95. /// </summary>
  96. public double end
  97. {
  98. get
  99. {
  100. UpdateDuration();
  101. return (double)m_End;
  102. }
  103. }
  104. /// <summary>
  105. /// The length, in seconds, of this track
  106. /// </summary>
  107. public sealed override double duration
  108. {
  109. get
  110. {
  111. UpdateDuration();
  112. return (double)(m_End - m_Start);
  113. }
  114. }
  115. /// <summary>
  116. /// Whether the track is muted or not.
  117. /// </summary>
  118. /// <remarks>
  119. /// A muted track is excluded from the generated PlayableGraph
  120. /// </remarks>
  121. public bool muted
  122. {
  123. get { return m_Muted; }
  124. set { m_Muted = value; }
  125. }
  126. /// <summary>
  127. /// The muted state of a track.
  128. /// </summary>
  129. /// <remarks>
  130. /// A track is also muted when one of its parent tracks are muted.
  131. /// </remarks>
  132. public bool mutedInHierarchy
  133. {
  134. get
  135. {
  136. if (muted)
  137. return true;
  138. TrackAsset p = this;
  139. while (p.parent as TrackAsset != null)
  140. {
  141. p = (TrackAsset)p.parent;
  142. if (p as GroupTrack != null)
  143. return p.mutedInHierarchy;
  144. }
  145. return false;
  146. }
  147. }
  148. /// <summary>
  149. /// The TimelineAsset that this track belongs to.
  150. /// </summary>
  151. public TimelineAsset timelineAsset
  152. {
  153. get
  154. {
  155. var node = this;
  156. while (node != null)
  157. {
  158. if (node.parent == null)
  159. return null;
  160. var seq = node.parent as TimelineAsset;
  161. if (seq != null)
  162. return seq;
  163. node = node.parent as TrackAsset;
  164. }
  165. return null;
  166. }
  167. }
  168. /// <summary>
  169. /// The owner of this track.
  170. /// </summary>
  171. /// <remarks>
  172. /// If this track is a subtrack, the parent is a TrackAsset. Otherwise the parent is a TimelineAsset.
  173. /// </remarks>
  174. public PlayableAsset parent
  175. {
  176. get { return m_Parent; }
  177. internal set { m_Parent = value; }
  178. }
  179. /// <summary>
  180. /// A list of clips owned by this track
  181. /// </summary>
  182. /// <returns>Returns an enumerable list of clips owned by the track.</returns>
  183. public IEnumerable<TimelineClip> GetClips()
  184. {
  185. return clips;
  186. }
  187. internal TimelineClip[] clips
  188. {
  189. get
  190. {
  191. if (m_Clips == null)
  192. m_Clips = new List<TimelineClip>();
  193. if (m_ClipsCache == null)
  194. {
  195. m_CacheSorted = false;
  196. m_ClipsCache = m_Clips.ToArray();
  197. }
  198. return m_ClipsCache;
  199. }
  200. }
  201. /// <summary>
  202. /// Whether this track is considered empty.
  203. /// </summary>
  204. /// <remarks>
  205. /// A track is considered empty when it does not contain a TimelineClip, Marker, or Curve.
  206. /// </remarks>
  207. /// <remarks>
  208. /// Empty tracks are not included in the playable graph.
  209. /// </remarks>
  210. public virtual bool isEmpty
  211. {
  212. get { return !hasClips && !hasCurves && GetMarkerCount() == 0; }
  213. }
  214. /// <summary>
  215. /// Whether this track contains any TimelineClip.
  216. /// </summary>
  217. public bool hasClips
  218. {
  219. get { return m_Clips != null && m_Clips.Count != 0; }
  220. }
  221. /// <summary>
  222. /// Whether this track contains animated properties for the attached PlayableAsset.
  223. /// </summary>
  224. /// <remarks>
  225. /// This property is false if the curves property is null or if it contains no information.
  226. /// </remarks>
  227. public bool hasCurves
  228. {
  229. get { return m_Curves != null && !m_Curves.empty; }
  230. }
  231. /// <summary>
  232. /// Returns whether this track is a subtrack
  233. /// </summary>
  234. public bool isSubTrack
  235. {
  236. get
  237. {
  238. var owner = parent as TrackAsset;
  239. return owner != null && owner.GetType() == GetType();
  240. }
  241. }
  242. /// <summary>
  243. /// Returns a description of the PlayableOutputs that will be created by this track.
  244. /// </summary>
  245. public override IEnumerable<PlayableBinding> outputs
  246. {
  247. get
  248. {
  249. TrackBindingTypeAttribute attribute;
  250. if (!s_TrackBindingTypeAttributeCache.TryGetValue(GetType(), out attribute))
  251. {
  252. attribute = (TrackBindingTypeAttribute)Attribute.GetCustomAttribute(GetType(), typeof(TrackBindingTypeAttribute));
  253. s_TrackBindingTypeAttributeCache.Add(GetType(), attribute);
  254. }
  255. var trackBindingType = attribute != null ? attribute.type : null;
  256. yield return ScriptPlayableBinding.Create(name, this, trackBindingType);
  257. }
  258. }
  259. /// <summary>
  260. /// The list of subtracks or child tracks attached to this track.
  261. /// </summary>
  262. /// <returns>Returns an enumerable list of child tracks owned directly by this track.</returns>
  263. /// <remarks>
  264. /// In the case of GroupTracks, this returns all tracks contained in the group. This will return the all subtracks or override tracks, if supported by the track.
  265. /// </remarks>
  266. public IEnumerable<TrackAsset> GetChildTracks()
  267. {
  268. UpdateChildTrackCache();
  269. return m_ChildTrackCache;
  270. }
  271. internal string customPlayableTypename
  272. {
  273. get { return m_CustomPlayableFullTypename; }
  274. set { m_CustomPlayableFullTypename = value; }
  275. }
  276. /// <summary>
  277. /// An animation clip storing animated properties of the attached PlayableAsset
  278. /// </summary>
  279. public AnimationClip curves
  280. {
  281. get { return m_Curves; }
  282. internal set { m_Curves = value; }
  283. }
  284. string ICurvesOwner.defaultCurvesName
  285. {
  286. get { return kDefaultCurvesName; }
  287. }
  288. Object ICurvesOwner.asset
  289. {
  290. get { return this; }
  291. }
  292. Object ICurvesOwner.assetOwner
  293. {
  294. get { return timelineAsset; }
  295. }
  296. TrackAsset ICurvesOwner.targetTrack
  297. {
  298. get { return this; }
  299. }
  300. // for UI where we need to detect 'null' objects
  301. internal List<ScriptableObject> subTracksObjects
  302. {
  303. get { return m_Children; }
  304. }
  305. /// <summary>
  306. /// The local locked state of the track.
  307. /// </summary>
  308. /// <remarks>
  309. /// Note that locking a track only affects operations in the Timeline Editor. It does not prevent other API calls from changing a track or it's clips.
  310. ///
  311. /// This returns or sets the local locked state of the track. A track may still be locked for editing because one or more of it's parent tracks in the hierarchy is locked. Use lockedInHierarchy to test if a track is locked because of it's own locked state or because of a parent tracks locked state.
  312. /// </remarks>
  313. public bool locked
  314. {
  315. get { return m_Locked; }
  316. set { m_Locked = value; }
  317. }
  318. /// <summary>
  319. /// The locked state of a track. (RO)
  320. /// </summary>
  321. /// <remarks>
  322. /// Note that locking a track only affects operations in the Timeline Editor. It does not prevent other API calls from changing a track or it's clips.
  323. ///
  324. /// This indicates whether a track is locked in the Timeline Editor because either it's locked property is enabled or a parent track is locked.
  325. /// </remarks>
  326. public bool lockedInHierarchy
  327. {
  328. get
  329. {
  330. if (locked)
  331. return true;
  332. TrackAsset p = this;
  333. while (p.parent as TrackAsset != null)
  334. {
  335. p = (TrackAsset)p.parent;
  336. if (p as GroupTrack != null)
  337. return p.lockedInHierarchy;
  338. }
  339. return false;
  340. }
  341. }
  342. /// <summary>
  343. /// Indicates if a track accepts markers that implement <see cref="UnityEngine.Playables.INotification"/>.
  344. /// </summary>
  345. /// <remarks>
  346. /// Only tracks with a bound object of type <see cref="UnityEngine.GameObject"/> or <see cref="UnityEngine.Component"/> can accept notifications.
  347. /// </remarks>
  348. public bool supportsNotifications
  349. {
  350. get
  351. {
  352. if (!m_SupportsNotifications.HasValue)
  353. {
  354. m_SupportsNotifications = NotificationUtilities.TrackTypeSupportsNotifications(GetType());
  355. }
  356. return m_SupportsNotifications.Value;
  357. }
  358. }
  359. void __internalAwake() //do not use OnEnable, since users will want it to initialize their class
  360. {
  361. if (m_Clips == null)
  362. m_Clips = new List<TimelineClip>();
  363. m_ChildTrackCache = null;
  364. if (m_Children == null)
  365. m_Children = new List<ScriptableObject>();
  366. #if UNITY_EDITOR
  367. // validate the array. DON'T remove Unity null objects, just actual null objects
  368. for (int i = m_Children.Count - 1; i >= 0; i--)
  369. {
  370. object o = m_Children[i];
  371. if (o == null)
  372. {
  373. Debug.LogWarning("Empty child track found while loading timeline. It will be removed.");
  374. m_Children.RemoveAt(i);
  375. }
  376. }
  377. #endif
  378. }
  379. /// <summary>
  380. /// Creates an AnimationClip to store animated properties for the attached PlayableAsset.
  381. /// </summary>
  382. /// <remarks>
  383. /// If curves already exists for this track, this method produces no result regardless of
  384. /// the value specified for curvesClipName.
  385. /// </remarks>
  386. /// <remarks>
  387. /// When used from the editor, this method attempts to save the created curves clip to the TimelineAsset.
  388. /// The TimelineAsset must already exist in the AssetDatabase to save the curves clip. If the TimelineAsset
  389. /// does not exist, the curves clip is still created but it is not saved.
  390. /// </remarks>
  391. /// <param name="curvesClipName">
  392. /// The name of the AnimationClip to create.
  393. /// This method does not ensure unique names. If you want a unique clip name, you must provide one.
  394. /// See ObjectNames.GetUniqueName for information on a method that creates unique names.
  395. /// </param>
  396. public void CreateCurves(string curvesClipName)
  397. {
  398. if (m_Curves != null)
  399. return;
  400. m_Curves = TimelineCreateUtilities.CreateAnimationClipForTrack(string.IsNullOrEmpty(curvesClipName) ? kDefaultCurvesName : curvesClipName, this, true);
  401. }
  402. /// <summary>
  403. /// Creates a mixer used to blend playables generated by clips on the track.
  404. /// </summary>
  405. /// <param name="graph">The graph to inject playables into</param>
  406. /// <param name="go">The GameObject that requested the graph.</param>
  407. /// <param name="inputCount">The number of playables from clips that will be inputs to the returned mixer</param>
  408. /// <returns>A handle to the [[Playable]] representing the mixer.</returns>
  409. /// <remarks>
  410. /// Override this method to provide a custom playable for mixing clips on a graph.
  411. /// </remarks>
  412. public virtual Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount)
  413. {
  414. return Playable.Create(graph, inputCount);
  415. }
  416. /// <summary>
  417. /// Overrides PlayableAsset.CreatePlayable(). Not used in Timeline.
  418. /// </summary>
  419. /// <param name="graph"><inheritdoc/></param>
  420. /// <param name="go"><inheritdoc/></param>
  421. /// <returns><inheritDoc/></returns>
  422. public sealed override Playable CreatePlayable(PlayableGraph graph, GameObject go)
  423. {
  424. return Playable.Null;
  425. }
  426. /// <summary>
  427. /// Creates a TimelineClip on this track.
  428. /// </summary>
  429. /// <returns>Returns a new TimelineClip that is attached to the track.</returns>
  430. /// <remarks>
  431. /// The type of the playable asset attached to the clip is determined by TrackClip attributes that decorate the TrackAsset derived class
  432. /// </remarks>
  433. public TimelineClip CreateDefaultClip()
  434. {
  435. var trackClipTypeAttributes = GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
  436. Type playableAssetType = null;
  437. foreach (var trackClipTypeAttribute in trackClipTypeAttributes)
  438. {
  439. var attribute = trackClipTypeAttribute as TrackClipTypeAttribute;
  440. if (attribute != null && typeof(IPlayableAsset).IsAssignableFrom(attribute.inspectedType) && typeof(ScriptableObject).IsAssignableFrom(attribute.inspectedType))
  441. {
  442. playableAssetType = attribute.inspectedType;
  443. break;
  444. }
  445. }
  446. if (playableAssetType == null)
  447. {
  448. Debug.LogWarning("Cannot create a default clip for type " + GetType());
  449. return null;
  450. }
  451. return CreateAndAddNewClipOfType(playableAssetType);
  452. }
  453. /// <summary>
  454. /// Creates a clip on the track with a playable asset attached, whose derived type is specified by T
  455. /// </summary>
  456. /// <typeparam name="T">A PlayableAsset derived type</typeparam>
  457. /// <returns>Returns a TimelineClip whose asset is of type T</returns>
  458. /// <remarks>
  459. /// Throws <exception cref="System.InvalidOperationException"/> if <typeparamref name="T"/> is not supported by the track.
  460. /// Supported types are determined by TrackClip attributes that decorate the TrackAsset derived class
  461. /// </remarks>
  462. public TimelineClip CreateClip<T>() where T : ScriptableObject, IPlayableAsset
  463. {
  464. return CreateClip(typeof(T));
  465. }
  466. /// <summary>
  467. /// Delete a clip from this track.
  468. /// </summary>
  469. /// <param name="clip">The clip to delete.</param>
  470. /// <returns>Returns true if the removal was successful</returns>
  471. /// <remarks>
  472. /// This method will delete a clip and any assets owned by the clip.
  473. /// </remarks>
  474. /// <exception>
  475. /// Throws <exception cref="System.InvalidOperationException"/> if <paramref name="clip"/> is not a child of the TrackAsset.
  476. /// </exception>
  477. public bool DeleteClip(TimelineClip clip)
  478. {
  479. if (!m_Clips.Contains(clip))
  480. throw new InvalidOperationException("Cannot delete clip since it is not a child of the TrackAsset.");
  481. return timelineAsset != null && timelineAsset.DeleteClip(clip);
  482. }
  483. /// <summary>
  484. /// Creates a marker of the requested type, at a specific time, and adds the marker to the current asset.
  485. /// </summary>
  486. /// <param name="type">The type of marker.</param>
  487. /// <param name="time">The time where the marker is created.</param>
  488. /// <returns>Returns the instance of the created marker.</returns>
  489. /// <remarks>
  490. /// All markers that implement IMarker and inherit from <see cref="UnityEngine.ScriptableObject"/> are supported.
  491. /// Markers that implement the INotification interface cannot be added to tracks that do not support notifications.
  492. /// CreateMarker will throw <exception cref="System.InvalidOperationException"/> with tracks that do not support notifications if <paramref name="type"/> implements the INotification interface.
  493. /// </remarks>
  494. /// <seealso cref="UnityEngine.Timeline.Marker"/>
  495. /// <seealso cref="UnityEngine.Timeline.TrackAsset.supportsNotifications"/>
  496. public IMarker CreateMarker(Type type, double time)
  497. {
  498. return m_Markers.CreateMarker(type, time, this);
  499. }
  500. /// <summary>
  501. /// Creates a marker of the requested type, at a specific time, and adds the marker to the current asset.
  502. /// </summary>
  503. /// <param name="time">The time where the marker is created.</param>
  504. /// <typeparam name="T">The type of marker to create.</typeparam>
  505. /// <returns>Returns the instance of the created marker.</returns>
  506. /// <remarks>
  507. /// All markers that implement IMarker and inherit from <see cref="UnityEngine.ScriptableObject"/> are supported.
  508. /// CreateMarker will throw <exception cref="System.InvalidOperationException"/> with tracks that do not support notifications if <typeparamref name="T"/> implements the INotification interface.
  509. /// </remarks>
  510. /// <seealso cref="UnityEngine.Timeline.Marker"/>
  511. /// <seealso cref="UnityEngine.Timeline.TrackAsset.supportsNotifications"/>
  512. public T CreateMarker<T>(double time) where T : ScriptableObject, IMarker
  513. {
  514. return (T)CreateMarker(typeof(T), time);
  515. }
  516. /// <summary>
  517. /// Removes a marker from the current asset.
  518. /// </summary>
  519. /// <param name="marker">The marker instance to be removed.</param>
  520. /// <returns>Returns true if the marker instance was successfully removed. Returns false otherwise.</returns>
  521. public bool DeleteMarker(IMarker marker)
  522. {
  523. return m_Markers.Remove(marker);
  524. }
  525. /// <summary>
  526. /// Returns an enumerable list of markers on the current asset.
  527. /// </summary>
  528. /// <returns>The list of markers on the asset.
  529. /// </returns>
  530. public IEnumerable<IMarker> GetMarkers()
  531. {
  532. return m_Markers.GetMarkers();
  533. }
  534. /// <summary>
  535. /// Returns the number of markers on the current asset.
  536. /// </summary>
  537. /// <returns>The number of markers.</returns>
  538. public int GetMarkerCount()
  539. {
  540. return m_Markers.Count;
  541. }
  542. /// <summary>
  543. /// Returns the marker at a given position, on the current asset.
  544. /// </summary>
  545. /// <param name="idx">The index of the marker to be returned.</param>
  546. /// <returns>The marker.</returns>
  547. /// <remarks>The ordering of the markers is not guaranteed.
  548. /// </remarks>
  549. public IMarker GetMarker(int idx)
  550. {
  551. return m_Markers[idx];
  552. }
  553. internal TimelineClip CreateClip(System.Type requestedType)
  554. {
  555. if (ValidateClipType(requestedType))
  556. return CreateAndAddNewClipOfType(requestedType);
  557. throw new InvalidOperationException("Clips of type " + requestedType + " are not permitted on tracks of type " + GetType());
  558. }
  559. internal TimelineClip CreateAndAddNewClipOfType(Type requestedType)
  560. {
  561. var newClip = CreateClipOfType(requestedType);
  562. AddClip(newClip);
  563. return newClip;
  564. }
  565. internal TimelineClip CreateClipOfType(Type requestedType)
  566. {
  567. if (!ValidateClipType(requestedType))
  568. throw new System.InvalidOperationException("Clips of type " + requestedType + " are not permitted on tracks of type " + GetType());
  569. var playableAsset = CreateInstance(requestedType);
  570. if (playableAsset == null)
  571. {
  572. throw new System.InvalidOperationException("Could not create an instance of the ScriptableObject type " + requestedType.Name);
  573. }
  574. playableAsset.name = requestedType.Name;
  575. TimelineCreateUtilities.SaveAssetIntoObject(playableAsset, this);
  576. TimelineUndo.RegisterCreatedObjectUndo(playableAsset, "Create Clip");
  577. return CreateClipFromAsset(playableAsset);
  578. }
  579. /// <summary>
  580. /// Creates a timeline clip from an existing playable asset.
  581. /// </summary>
  582. /// <param name="asset"></param>
  583. /// <returns></returns>
  584. internal TimelineClip CreateClipFromPlayableAsset(IPlayableAsset asset)
  585. {
  586. if (asset == null)
  587. throw new ArgumentNullException("asset");
  588. if ((asset as ScriptableObject) == null)
  589. throw new System.ArgumentException("CreateClipFromPlayableAsset " + " only supports ScriptableObject-derived Types");
  590. if (!ValidateClipType(asset.GetType()))
  591. throw new System.InvalidOperationException("Clips of type " + asset.GetType() + " are not permitted on tracks of type " + GetType());
  592. return CreateClipFromAsset(asset as ScriptableObject);
  593. }
  594. private TimelineClip CreateClipFromAsset(ScriptableObject playableAsset)
  595. {
  596. TimelineUndo.PushUndo(this, "Create Clip");
  597. var newClip = CreateNewClipContainerInternal();
  598. newClip.displayName = playableAsset.name;
  599. newClip.asset = playableAsset;
  600. IPlayableAsset iPlayableAsset = playableAsset as IPlayableAsset;
  601. if (iPlayableAsset != null)
  602. {
  603. var candidateDuration = iPlayableAsset.duration;
  604. if (!double.IsInfinity(candidateDuration) && candidateDuration > 0)
  605. newClip.duration = Math.Min(Math.Max(candidateDuration, TimelineClip.kMinDuration), TimelineClip.kMaxTimeValue);
  606. }
  607. try
  608. {
  609. OnCreateClip(newClip);
  610. }
  611. catch (Exception e)
  612. {
  613. Debug.LogError(e.Message, playableAsset);
  614. return null;
  615. }
  616. return newClip;
  617. }
  618. internal IEnumerable<ScriptableObject> GetMarkersRaw()
  619. {
  620. return m_Markers.GetRawMarkerList();
  621. }
  622. internal void ClearMarkers()
  623. {
  624. m_Markers.Clear();
  625. }
  626. internal void AddMarker(ScriptableObject e)
  627. {
  628. m_Markers.Add(e);
  629. }
  630. internal bool DeleteMarkerRaw(ScriptableObject marker)
  631. {
  632. return m_Markers.Remove(marker, timelineAsset, this);
  633. }
  634. int GetTimeRangeHash()
  635. {
  636. double start = double.MaxValue, end = double.MinValue;
  637. foreach (var marker in GetMarkers())
  638. {
  639. if (!(marker is INotification))
  640. {
  641. continue;
  642. }
  643. if (marker.time < start)
  644. start = marker.time;
  645. if (marker.time > end)
  646. end = marker.time;
  647. }
  648. return start.GetHashCode().CombineHash(end.GetHashCode());
  649. }
  650. internal void AddClip(TimelineClip newClip)
  651. {
  652. if (!m_Clips.Contains(newClip))
  653. {
  654. m_Clips.Add(newClip);
  655. m_ClipsCache = null;
  656. }
  657. }
  658. Playable CreateNotificationsPlayable(PlayableGraph graph, Playable mixerPlayable, GameObject go, Playable timelinePlayable)
  659. {
  660. s_BuildData.markerList.Clear();
  661. GatherNotificiations(s_BuildData.markerList);
  662. var notificationPlayable = NotificationUtilities.CreateNotificationsPlayable(graph, s_BuildData.markerList, go);
  663. if (notificationPlayable.IsValid())
  664. {
  665. notificationPlayable.GetBehaviour().timeSource = timelinePlayable;
  666. if (mixerPlayable.IsValid())
  667. {
  668. notificationPlayable.SetInputCount(1);
  669. graph.Connect(mixerPlayable, 0, notificationPlayable, 0);
  670. notificationPlayable.SetInputWeight(mixerPlayable, 1);
  671. }
  672. }
  673. return notificationPlayable;
  674. }
  675. internal Playable CreatePlayableGraph(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree, Playable timelinePlayable)
  676. {
  677. UpdateDuration();
  678. var mixerPlayable = Playable.Null;
  679. if (CanCompileClipsRecursive())
  680. mixerPlayable = OnCreateClipPlayableGraph(graph, go, tree);
  681. var notificationsPlayable = CreateNotificationsPlayable(graph, mixerPlayable, go, timelinePlayable);
  682. // clear the temporary build data to avoid holding references
  683. // case 1253974
  684. s_BuildData.Clear();
  685. if (!notificationsPlayable.IsValid() && !mixerPlayable.IsValid())
  686. {
  687. Debug.LogErrorFormat("Track {0} of type {1} has no notifications and returns an invalid mixer Playable", name,
  688. GetType().FullName);
  689. return Playable.Create(graph);
  690. }
  691. return notificationsPlayable.IsValid() ? notificationsPlayable : mixerPlayable;
  692. }
  693. internal virtual Playable CompileClips(PlayableGraph graph, GameObject go, IList<TimelineClip> timelineClips, IntervalTree<RuntimeElement> tree)
  694. {
  695. var blend = CreateTrackMixer(graph, go, timelineClips.Count);
  696. for (var c = 0; c < timelineClips.Count; c++)
  697. {
  698. var source = CreatePlayable(graph, go, timelineClips[c]);
  699. if (source.IsValid())
  700. {
  701. source.SetDuration(timelineClips[c].duration);
  702. var clip = new RuntimeClip(timelineClips[c], source, blend);
  703. tree.Add(clip);
  704. graph.Connect(source, 0, blend, c);
  705. blend.SetInputWeight(c, 0.0f);
  706. }
  707. }
  708. ConfigureTrackAnimation(tree, go, blend);
  709. return blend;
  710. }
  711. void GatherCompilableTracks(IList<TrackAsset> tracks)
  712. {
  713. if (!muted && CanCompileClips())
  714. tracks.Add(this);
  715. foreach (var c in GetChildTracks())
  716. {
  717. if (c != null)
  718. c.GatherCompilableTracks(tracks);
  719. }
  720. }
  721. void GatherNotificiations(List<IMarker> markers)
  722. {
  723. if (!muted && CanCompileNotifications())
  724. markers.AddRange(GetMarkers());
  725. foreach (var c in GetChildTracks())
  726. {
  727. if (c != null)
  728. c.GatherNotificiations(markers);
  729. }
  730. }
  731. internal virtual Playable OnCreateClipPlayableGraph(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree)
  732. {
  733. if (tree == null)
  734. throw new ArgumentException("IntervalTree argument cannot be null", "tree");
  735. if (go == null)
  736. throw new ArgumentException("GameObject argument cannot be null", "go");
  737. s_BuildData.Clear();
  738. GatherCompilableTracks(s_BuildData.trackList);
  739. // nothing to compile
  740. if (s_BuildData.trackList.Count == 0)
  741. return Playable.Null;
  742. // check if layers are supported
  743. Playable layerMixer = Playable.Null;
  744. ILayerable layerable = this as ILayerable;
  745. if (layerable != null)
  746. layerMixer = layerable.CreateLayerMixer(graph, go, s_BuildData.trackList.Count);
  747. if (layerMixer.IsValid())
  748. {
  749. for (int i = 0; i < s_BuildData.trackList.Count; i++)
  750. {
  751. var mixer = s_BuildData.trackList[i].CompileClips(graph, go, s_BuildData.trackList[i].clips, tree);
  752. if (mixer.IsValid())
  753. {
  754. graph.Connect(mixer, 0, layerMixer, i);
  755. layerMixer.SetInputWeight(i, 1.0f);
  756. }
  757. }
  758. return layerMixer;
  759. }
  760. // one track compiles. Add track mixer and clips
  761. if (s_BuildData.trackList.Count == 1)
  762. return s_BuildData.trackList[0].CompileClips(graph, go, s_BuildData.trackList[0].clips, tree);
  763. // no layer mixer provided. merge down all clips.
  764. for (int i = 0; i < s_BuildData.trackList.Count; i++)
  765. s_BuildData.clipList.AddRange(s_BuildData.trackList[i].clips);
  766. #if UNITY_EDITOR
  767. bool applyWarning = false;
  768. for (int i = 0; i < s_BuildData.trackList.Count; i++)
  769. applyWarning |= i > 0 && s_BuildData.trackList[i].hasCurves;
  770. if (applyWarning)
  771. Debug.LogWarning("A layered track contains animated fields, but no layer mixer has been provided. Animated fields on layers will be ignored. Override CreateLayerMixer in " + s_BuildData.trackList[0].GetType().Name + " and return a valid playable to support animated fields on layered tracks.");
  772. #endif
  773. // compile all the clips into a single mixer
  774. return CompileClips(graph, go, s_BuildData.clipList, tree);
  775. }
  776. internal void ConfigureTrackAnimation(IntervalTree<RuntimeElement> tree, GameObject go, Playable blend)
  777. {
  778. if (!hasCurves)
  779. return;
  780. blend.SetAnimatedProperties(m_Curves);
  781. tree.Add(new InfiniteRuntimeClip(blend));
  782. if (OnTrackAnimationPlayableCreate != null)
  783. OnTrackAnimationPlayableCreate.Invoke(this, go, blend);
  784. }
  785. // sorts clips by start time
  786. internal void SortClips()
  787. {
  788. var clipsAsArray = clips; // will alloc
  789. if (!m_CacheSorted)
  790. {
  791. Array.Sort(clips, (clip1, clip2) => clip1.start.CompareTo(clip2.start));
  792. m_CacheSorted = true;
  793. }
  794. }
  795. // clears the clips after a clone
  796. internal void ClearClipsInternal()
  797. {
  798. m_Clips = new List<TimelineClip>();
  799. m_ClipsCache = null;
  800. }
  801. internal void ClearSubTracksInternal()
  802. {
  803. m_Children = new List<ScriptableObject>();
  804. Invalidate();
  805. }
  806. // called by an owned clip when it moves
  807. internal void OnClipMove()
  808. {
  809. m_CacheSorted = false;
  810. }
  811. internal TimelineClip CreateNewClipContainerInternal()
  812. {
  813. var clipContainer = new TimelineClip(this);
  814. clipContainer.asset = null;
  815. // position clip at end of sequence
  816. var newClipStart = 0.0;
  817. for (var a = 0; a < m_Clips.Count - 1; a++)
  818. {
  819. var clipDuration = m_Clips[a].duration;
  820. if (double.IsInfinity(clipDuration))
  821. clipDuration = TimelineClip.kDefaultClipDurationInSeconds;
  822. newClipStart = Math.Max(newClipStart, m_Clips[a].start + clipDuration);
  823. }
  824. clipContainer.mixInCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);
  825. clipContainer.mixOutCurve = AnimationCurve.EaseInOut(0, 1, 1, 0);
  826. clipContainer.start = newClipStart;
  827. clipContainer.duration = TimelineClip.kDefaultClipDurationInSeconds;
  828. clipContainer.displayName = "untitled";
  829. return clipContainer;
  830. }
  831. internal void AddChild(TrackAsset child)
  832. {
  833. if (child == null)
  834. return;
  835. m_Children.Add(child);
  836. child.parent = this;
  837. Invalidate();
  838. }
  839. internal void MoveLastTrackBefore(TrackAsset asset)
  840. {
  841. if (m_Children == null || m_Children.Count < 2 || asset == null)
  842. return;
  843. var lastTrack = m_Children[m_Children.Count - 1];
  844. if (lastTrack == asset)
  845. return;
  846. for (int i = 0; i < m_Children.Count - 1; i++)
  847. {
  848. if (m_Children[i] == asset)
  849. {
  850. for (int j = m_Children.Count - 1; j > i; j--)
  851. m_Children[j] = m_Children[j - 1];
  852. m_Children[i] = lastTrack;
  853. Invalidate();
  854. break;
  855. }
  856. }
  857. }
  858. internal bool RemoveSubTrack(TrackAsset child)
  859. {
  860. if (m_Children.Remove(child))
  861. {
  862. Invalidate();
  863. child.parent = null;
  864. return true;
  865. }
  866. return false;
  867. }
  868. internal void RemoveClip(TimelineClip clip)
  869. {
  870. m_Clips.Remove(clip);
  871. m_ClipsCache = null;
  872. }
  873. // Is this track compilable for the sequence
  874. // calculate the time interval that this track will be evaluated in.
  875. internal virtual void GetEvaluationTime(out double outStart, out double outDuration)
  876. {
  877. outStart = double.PositiveInfinity;
  878. var outEnd = double.NegativeInfinity;
  879. if (hasCurves)
  880. {
  881. outStart = 0.0;
  882. outEnd = TimeUtility.GetAnimationClipLength(curves);
  883. }
  884. foreach (var clip in clips)
  885. {
  886. outStart = Math.Min(clip.start, outStart);
  887. outEnd = Math.Max(clip.end, outEnd);
  888. }
  889. if (HasNotifications())
  890. {
  891. var notificationDuration = GetNotificationDuration();
  892. outStart = Math.Min(notificationDuration, outStart);
  893. outEnd = Math.Max(notificationDuration, outEnd);
  894. }
  895. if (double.IsInfinity(outStart) || double.IsInfinity(outEnd))
  896. outStart = outDuration = 0.0;
  897. else
  898. outDuration = outEnd - outStart;
  899. }
  900. // calculate the time interval that the sequence will use to determine length.
  901. // by default this is the same as the evaluation, but subclasses can have different
  902. // behaviour
  903. internal virtual void GetSequenceTime(out double outStart, out double outDuration)
  904. {
  905. GetEvaluationTime(out outStart, out outDuration);
  906. }
  907. /// <summary>
  908. /// Called by the Timeline Editor to gather properties requiring preview.
  909. /// </summary>
  910. /// <param name="director">The PlayableDirector invoking the preview</param>
  911. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  912. public virtual void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  913. {
  914. // only push on game objects if there is a binding. Subtracks
  915. // will use objects on the stack
  916. var gameObject = GetGameObjectBinding(director);
  917. if (gameObject != null)
  918. driver.PushActiveGameObject(gameObject);
  919. if (hasCurves)
  920. driver.AddObjectProperties(this, m_Curves);
  921. foreach (var clip in clips)
  922. {
  923. if (clip.curves != null && clip.asset != null)
  924. driver.AddObjectProperties(clip.asset, clip.curves);
  925. IPropertyPreview modifier = clip.asset as IPropertyPreview;
  926. if (modifier != null)
  927. modifier.GatherProperties(director, driver);
  928. }
  929. foreach (var subtrack in GetChildTracks())
  930. {
  931. if (subtrack != null)
  932. subtrack.GatherProperties(director, driver);
  933. }
  934. if (gameObject != null)
  935. driver.PopActiveGameObject();
  936. }
  937. internal GameObject GetGameObjectBinding(PlayableDirector director)
  938. {
  939. if (director == null)
  940. return null;
  941. var binding = director.GetGenericBinding(this);
  942. var gameObject = binding as GameObject;
  943. if (gameObject != null)
  944. return gameObject;
  945. var comp = binding as Component;
  946. if (comp != null)
  947. return comp.gameObject;
  948. return null;
  949. }
  950. internal bool ValidateClipType(Type clipType)
  951. {
  952. var attrs = GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
  953. for (var c = 0; c < attrs.Length; ++c)
  954. {
  955. var attr = (TrackClipTypeAttribute)attrs[c];
  956. if (attr.inspectedType.IsAssignableFrom(clipType))
  957. return true;
  958. }
  959. // special case for playable tracks, they accept all clips (in the runtime)
  960. return typeof(PlayableTrack).IsAssignableFrom(GetType()) &&
  961. typeof(IPlayableAsset).IsAssignableFrom(clipType) &&
  962. typeof(ScriptableObject).IsAssignableFrom(clipType);
  963. }
  964. /// <summary>
  965. /// Called when a clip is created on a track.
  966. /// </summary>
  967. /// <param name="clip">The timeline clip added to this track</param>
  968. /// <remarks>Use this method to set default values on a timeline clip, or it's PlayableAsset.</remarks>
  969. protected virtual void OnCreateClip(TimelineClip clip) {}
  970. void UpdateDuration()
  971. {
  972. // check if something changed in the clips that require a re-calculation of the evaluation times.
  973. var itemsHash = CalculateItemsHash();
  974. if (itemsHash == m_ItemsHash)
  975. return;
  976. m_ItemsHash = itemsHash;
  977. double trackStart, trackDuration;
  978. GetSequenceTime(out trackStart, out trackDuration);
  979. m_Start = (DiscreteTime)trackStart;
  980. m_End = (DiscreteTime)(trackStart + trackDuration);
  981. // calculate the extrapolations time.
  982. // TODO Extrapolation time should probably be extracted from the SequenceClip so only a track is aware of it.
  983. this.CalculateExtrapolationTimes();
  984. }
  985. protected internal virtual int CalculateItemsHash()
  986. {
  987. return HashUtility.CombineHash(GetClipsHash(), GetAnimationClipHash(m_Curves), GetTimeRangeHash());
  988. }
  989. /// <summary>
  990. /// Constructs a Playable from a TimelineClip.
  991. /// </summary>
  992. /// <param name="graph">PlayableGraph that will own the playable.</param>
  993. /// <param name="gameObject">The GameObject that builds the PlayableGraph.</param>
  994. /// <param name="clip">The TimelineClip to construct a playable for.</param>
  995. /// <returns>A playable that will be set as an input to the Track Mixer playable, or Playable.Null if the clip does not have a valid PlayableAsset</returns>
  996. /// <exception cref="ArgumentException">Thrown if the specified PlayableGraph is not valid.</exception>
  997. /// <exception cref="ArgumentNullException">Thrown if the specified TimelineClip is not valid.</exception>
  998. /// <remarks>
  999. /// By default, this method invokes Playable.CreatePlayable, sets animated properties, and sets the speed of the created playable. Override this method to change this default implementation.
  1000. /// </remarks>
  1001. protected virtual Playable CreatePlayable(PlayableGraph graph, GameObject gameObject, TimelineClip clip)
  1002. {
  1003. if (!graph.IsValid())
  1004. throw new ArgumentException("graph must be a valid PlayableGraph");
  1005. if (clip == null)
  1006. throw new ArgumentNullException("clip");
  1007. var asset = clip.asset as IPlayableAsset;
  1008. if (asset != null)
  1009. {
  1010. var handle = asset.CreatePlayable(graph, gameObject);
  1011. if (handle.IsValid())
  1012. {
  1013. handle.SetAnimatedProperties(clip.curves);
  1014. handle.SetSpeed(clip.timeScale);
  1015. if (OnClipPlayableCreate != null)
  1016. OnClipPlayableCreate(clip, gameObject, handle);
  1017. }
  1018. return handle;
  1019. }
  1020. return Playable.Null;
  1021. }
  1022. internal void Invalidate()
  1023. {
  1024. m_ChildTrackCache = null;
  1025. var timeline = timelineAsset;
  1026. if (timeline != null)
  1027. {
  1028. timeline.Invalidate();
  1029. }
  1030. }
  1031. internal double GetNotificationDuration()
  1032. {
  1033. if (!supportsNotifications)
  1034. {
  1035. return 0;
  1036. }
  1037. var maxTime = 0.0;
  1038. foreach (var marker in GetMarkers())
  1039. {
  1040. if (!(marker is INotification))
  1041. {
  1042. continue;
  1043. }
  1044. maxTime = Math.Max(maxTime, marker.time);
  1045. }
  1046. return maxTime;
  1047. }
  1048. internal virtual bool CanCompileClips()
  1049. {
  1050. return hasClips || hasCurves;
  1051. }
  1052. internal bool IsCompilable()
  1053. {
  1054. var isContainer = typeof(GroupTrack).IsAssignableFrom(GetType());
  1055. if (isContainer)
  1056. return false;
  1057. var ret = !mutedInHierarchy && (CanCompileClips() || CanCompileNotifications());
  1058. if (!ret)
  1059. {
  1060. foreach (var t in GetChildTracks())
  1061. {
  1062. if (t.IsCompilable())
  1063. return true;
  1064. }
  1065. }
  1066. return ret;
  1067. }
  1068. private void UpdateChildTrackCache()
  1069. {
  1070. if (m_ChildTrackCache == null)
  1071. {
  1072. if (m_Children == null || m_Children.Count == 0)
  1073. m_ChildTrackCache = s_EmptyCache;
  1074. else
  1075. {
  1076. var childTracks = new List<TrackAsset>(m_Children.Count);
  1077. for (int i = 0; i < m_Children.Count; i++)
  1078. {
  1079. var subTrack = m_Children[i] as TrackAsset;
  1080. if (subTrack != null)
  1081. childTracks.Add(subTrack);
  1082. }
  1083. m_ChildTrackCache = childTracks;
  1084. }
  1085. }
  1086. }
  1087. internal virtual int Hash()
  1088. {
  1089. return clips.Length + (m_Markers.Count << 16);
  1090. }
  1091. int GetClipsHash()
  1092. {
  1093. var hash = 0;
  1094. foreach (var clip in m_Clips)
  1095. {
  1096. hash = hash.CombineHash(clip.Hash());
  1097. }
  1098. return hash;
  1099. }
  1100. /// <summary>
  1101. /// Gets the hash code for an AnimationClip.
  1102. /// </summary>
  1103. /// <param name="clip">The animation clip.</param>
  1104. /// <returns>A 32-bit signed integer that is the hash code for <paramref name="clip"/>. Returns 0 if <paramref name="clip"/> is null or empty.</returns>
  1105. protected static int GetAnimationClipHash(AnimationClip clip)
  1106. {
  1107. var hash = 0;
  1108. if (clip != null && !clip.empty)
  1109. hash = hash.CombineHash(clip.frameRate.GetHashCode())
  1110. .CombineHash(clip.length.GetHashCode());
  1111. return hash;
  1112. }
  1113. bool HasNotifications()
  1114. {
  1115. return m_Markers.HasNotifications();
  1116. }
  1117. bool CanCompileNotifications()
  1118. {
  1119. return supportsNotifications && m_Markers.HasNotifications();
  1120. }
  1121. bool CanCompileClipsRecursive()
  1122. {
  1123. if (CanCompileClips())
  1124. return true;
  1125. foreach (var track in GetChildTracks())
  1126. {
  1127. if (track.CanCompileClipsRecursive())
  1128. return true;
  1129. }
  1130. return false;
  1131. }
  1132. }
  1133. }