TimelineAsset.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Playables;
  4. namespace UnityEngine.Timeline
  5. {
  6. /// <summary>
  7. /// A PlayableAsset that represents a timeline.
  8. /// </summary>
  9. [ExcludeFromPreset]
  10. [Serializable]
  11. public partial class TimelineAsset : PlayableAsset, ISerializationCallbackReceiver, ITimelineClipAsset, IPropertyPreview
  12. {
  13. /// <summary>
  14. /// How the duration of the timeline is determined.
  15. /// </summary>
  16. public enum DurationMode
  17. {
  18. /// <summary>
  19. /// The duration of the timeline is determined based on the clips present.
  20. /// </summary>
  21. BasedOnClips,
  22. /// <summary>
  23. /// The duration of the timeline is a fixed length.
  24. /// </summary>
  25. FixedLength
  26. }
  27. /// <summary>
  28. /// Properties of the timeline that are used by the editor
  29. /// </summary>
  30. [Serializable]
  31. public class EditorSettings
  32. {
  33. internal static readonly float kMinFps = (float)TimeUtility.kFrameRateEpsilon;
  34. internal static readonly float kMaxFps = 1000.0f;
  35. internal static readonly float kDefaultFps = 60.0f;
  36. [HideInInspector, SerializeField] float m_Framerate = kDefaultFps;
  37. [HideInInspector, SerializeField] bool m_ScenePreview = true;
  38. /// <summary>
  39. /// The frames per second used for snapping and time ruler display
  40. /// </summary>
  41. public float fps
  42. {
  43. get
  44. {
  45. return m_Framerate;
  46. }
  47. set
  48. {
  49. m_Framerate = GetValidFramerate(value);
  50. }
  51. }
  52. /// <summary>
  53. /// Set to false to ignore scene preview when this timeline is played by the Timeline window.
  54. /// </summary>
  55. /// <remarks>
  56. /// When set to false, this setting will
  57. /// - Disable scene preview when this timeline is played by the Timeline window.
  58. /// - Disable recording for all recordable tracks.
  59. /// - Disable play range in the Timeline window.
  60. /// - `Stop()` is not called on the `PlayableDirector` when switching between different `TimelineAsset`s in the TimelineWindow.
  61. ///
  62. /// `scenePreview` will only be applied if the asset is the master timeline.
  63. /// </remarks>
  64. /// <seealso cref="UnityEngine.Timeline.TimelineAsset"/>
  65. public bool scenePreview
  66. {
  67. get => m_ScenePreview;
  68. set => m_ScenePreview = value;
  69. }
  70. }
  71. [HideInInspector, SerializeField] List<ScriptableObject> m_Tracks;
  72. [HideInInspector, SerializeField] double m_FixedDuration; // only applied if duration mode is Fixed
  73. [HideInInspector, NonSerialized] TrackAsset[] m_CacheOutputTracks;
  74. [HideInInspector, NonSerialized] List<TrackAsset> m_CacheRootTracks;
  75. [HideInInspector, NonSerialized] List<TrackAsset> m_CacheFlattenedTracks;
  76. [HideInInspector, SerializeField] EditorSettings m_EditorSettings = new EditorSettings();
  77. [SerializeField] DurationMode m_DurationMode;
  78. [HideInInspector, SerializeField] MarkerTrack m_MarkerTrack;
  79. /// <summary>
  80. /// Settings used by timeline for editing purposes
  81. /// </summary>
  82. public EditorSettings editorSettings
  83. {
  84. get { return m_EditorSettings; }
  85. }
  86. /// <summary>
  87. /// The length, in seconds, of the timeline
  88. /// </summary>
  89. public override double duration
  90. {
  91. get
  92. {
  93. // @todo cache this value when rebuilt
  94. if (m_DurationMode == DurationMode.BasedOnClips)
  95. {
  96. //avoid having no clip evaluated at the end by removing a tick from the total duration
  97. var discreteDuration = CalculateItemsDuration();
  98. if (discreteDuration <= 0)
  99. return 0.0;
  100. return (double)discreteDuration.OneTickBefore();
  101. }
  102. return m_FixedDuration;
  103. }
  104. }
  105. /// <summary>
  106. /// The length of the timeline when durationMode is set to fixed length.
  107. /// </summary>
  108. public double fixedDuration
  109. {
  110. get
  111. {
  112. DiscreteTime discreteDuration = (DiscreteTime)m_FixedDuration;
  113. if (discreteDuration <= 0)
  114. return 0.0;
  115. //avoid having no clip evaluated at the end by removing a tick from the total duration
  116. return (double)discreteDuration.OneTickBefore();
  117. }
  118. set { m_FixedDuration = Math.Max(0.0, value); }
  119. }
  120. /// <summary>
  121. /// The mode used to determine the duration of the Timeline
  122. /// </summary>
  123. public DurationMode durationMode
  124. {
  125. get { return m_DurationMode; }
  126. set { m_DurationMode = value; }
  127. }
  128. /// <summary>
  129. /// A description of the PlayableOutputs that will be created by the timeline when instantiated.
  130. /// </summary>
  131. /// <remarks>
  132. /// Each track will create an PlayableOutput
  133. /// </remarks>
  134. public override IEnumerable<PlayableBinding> outputs
  135. {
  136. get
  137. {
  138. foreach (var outputTracks in GetOutputTracks())
  139. foreach (var output in outputTracks.outputs)
  140. yield return output;
  141. }
  142. }
  143. /// <summary>
  144. /// The capabilities supported by all clips in the timeline.
  145. /// </summary>
  146. public ClipCaps clipCaps
  147. {
  148. get
  149. {
  150. var caps = ClipCaps.All;
  151. foreach (var track in GetRootTracks())
  152. {
  153. foreach (var clip in track.clips)
  154. caps &= clip.clipCaps;
  155. }
  156. return caps;
  157. }
  158. }
  159. /// <summary>
  160. /// Returns the the number of output tracks in the Timeline.
  161. /// </summary>
  162. /// <remarks>
  163. /// An output track is a track the generates a PlayableOutput. In general, an output track is any track that is not a GroupTrack, a subtrack, or override track.
  164. /// </remarks>
  165. public int outputTrackCount
  166. {
  167. get
  168. {
  169. UpdateOutputTrackCache(); // updates the cache if necessary
  170. return m_CacheOutputTracks.Length;
  171. }
  172. }
  173. /// <summary>
  174. /// Returns the number of tracks at the root level of the timeline.
  175. /// </summary>
  176. /// <remarks>
  177. /// A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group
  178. /// </remarks>
  179. public int rootTrackCount
  180. {
  181. get
  182. {
  183. UpdateRootTrackCache();
  184. return m_CacheRootTracks.Count;
  185. }
  186. }
  187. void OnValidate()
  188. {
  189. editorSettings.fps = GetValidFramerate(editorSettings.fps);
  190. }
  191. internal static float GetValidFramerate(float framerate)
  192. {
  193. return Mathf.Clamp(framerate, EditorSettings.kMinFps, EditorSettings.kMaxFps);
  194. }
  195. /// <summary>
  196. /// Retrieves at root track at the specified index.
  197. /// </summary>
  198. /// <param name="index">Index of the root track to get. Must be between 0 and rootTrackCount</param>
  199. /// <remarks>
  200. /// A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group.
  201. /// </remarks>
  202. /// <returns>Root track at the specified index.</returns>
  203. public TrackAsset GetRootTrack(int index)
  204. {
  205. UpdateRootTrackCache();
  206. return m_CacheRootTracks[index];
  207. }
  208. /// <summary>
  209. /// Get an enumerable list of all root tracks.
  210. /// </summary>
  211. /// <returns>An IEnumerable of all root tracks.</returns>
  212. /// <remarks>A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group.</remarks>
  213. public IEnumerable<TrackAsset> GetRootTracks()
  214. {
  215. UpdateRootTrackCache();
  216. return m_CacheRootTracks;
  217. }
  218. /// <summary>
  219. /// Retrives the output track from the given index.
  220. /// </summary>
  221. /// <param name="index">Index of the output track to retrieve. Must be between 0 and outputTrackCount</param>
  222. /// <returns>The output track from the given index</returns>
  223. public TrackAsset GetOutputTrack(int index)
  224. {
  225. UpdateOutputTrackCache();
  226. return m_CacheOutputTracks[index];
  227. }
  228. /// <summary>
  229. /// Gets a list of all output tracks in the Timeline.
  230. /// </summary>
  231. /// <returns>An IEnumerable of all output tracks</returns>
  232. /// <remarks>
  233. /// An output track is a track the generates a PlayableOutput. In general, an output track is any track that is not a GroupTrack or subtrack.
  234. /// </remarks>
  235. public IEnumerable<TrackAsset> GetOutputTracks()
  236. {
  237. UpdateOutputTrackCache();
  238. return m_CacheOutputTracks;
  239. }
  240. void UpdateRootTrackCache()
  241. {
  242. if (m_CacheRootTracks == null)
  243. {
  244. if (m_Tracks == null)
  245. m_CacheRootTracks = new List<TrackAsset>();
  246. else
  247. {
  248. m_CacheRootTracks = new List<TrackAsset>(m_Tracks.Count);
  249. if (markerTrack != null)
  250. {
  251. m_CacheRootTracks.Add(markerTrack);
  252. }
  253. foreach (var t in m_Tracks)
  254. {
  255. var trackAsset = t as TrackAsset;
  256. if (trackAsset != null)
  257. m_CacheRootTracks.Add(trackAsset);
  258. }
  259. }
  260. }
  261. }
  262. void UpdateOutputTrackCache()
  263. {
  264. if (m_CacheOutputTracks == null)
  265. {
  266. var outputTracks = new List<TrackAsset>();
  267. foreach (var flattenedTrack in flattenedTracks)
  268. {
  269. if (flattenedTrack != null && flattenedTrack.GetType() != typeof(GroupTrack) && !flattenedTrack.isSubTrack)
  270. outputTracks.Add(flattenedTrack);
  271. }
  272. m_CacheOutputTracks = outputTracks.ToArray();
  273. }
  274. }
  275. internal IEnumerable<TrackAsset> flattenedTracks
  276. {
  277. get
  278. {
  279. if (m_CacheFlattenedTracks == null)
  280. {
  281. m_CacheFlattenedTracks = new List<TrackAsset>(m_Tracks.Count * 2);
  282. UpdateRootTrackCache();
  283. m_CacheFlattenedTracks.AddRange(m_CacheRootTracks);
  284. for (int i = 0; i < m_CacheRootTracks.Count; i++)
  285. {
  286. AddSubTracksRecursive(m_CacheRootTracks[i], ref m_CacheFlattenedTracks);
  287. }
  288. }
  289. return m_CacheFlattenedTracks;
  290. }
  291. }
  292. /// <summary>
  293. /// Gets the marker track for this TimelineAsset.
  294. /// </summary>
  295. /// <returns>Returns the marker track.</returns>
  296. /// <remarks>
  297. /// Use <see cref="TrackAsset.GetMarkers"/> to get a list of the markers on the returned track.
  298. /// </remarks>
  299. public MarkerTrack markerTrack
  300. {
  301. get { return m_MarkerTrack; }
  302. }
  303. // access to the track list as scriptable object
  304. internal List<ScriptableObject> trackObjects
  305. {
  306. get { return m_Tracks; }
  307. }
  308. internal void AddTrackInternal(TrackAsset track)
  309. {
  310. m_Tracks.Add(track);
  311. track.parent = this;
  312. Invalidate();
  313. }
  314. internal void RemoveTrack(TrackAsset track)
  315. {
  316. m_Tracks.Remove(track);
  317. Invalidate();
  318. var parentTrack = track.parent as TrackAsset;
  319. if (parentTrack != null)
  320. {
  321. parentTrack.RemoveSubTrack(track);
  322. }
  323. }
  324. /// <summary>
  325. /// Creates an instance of the timeline
  326. /// </summary>
  327. /// <param name="graph">PlayableGraph that will own the playable</param>
  328. /// <param name="go">The gameobject that triggered the graph build</param>
  329. /// <returns>The Root Playable of the Timeline</returns>
  330. public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
  331. {
  332. bool autoRebalanceTree = false;
  333. #if UNITY_EDITOR
  334. autoRebalanceTree = true;
  335. #endif
  336. // only create outputs if we are not nested
  337. bool createOutputs = graph.GetPlayableCount() == 0;
  338. var timeline = TimelinePlayable.Create(graph, GetOutputTracks(), go, autoRebalanceTree, createOutputs);
  339. timeline.SetPropagateSetTime(true);
  340. return timeline.IsValid() ? timeline : Playable.Null;
  341. }
  342. /// <summary>
  343. /// Called before Unity serializes this object.
  344. /// </summary>
  345. void ISerializationCallbackReceiver.OnBeforeSerialize()
  346. {
  347. m_Version = k_LatestVersion;
  348. }
  349. /// <summary>
  350. /// Called after Unity deserializes this object.
  351. /// </summary>
  352. void ISerializationCallbackReceiver.OnAfterDeserialize()
  353. {
  354. // resets cache on an Undo
  355. Invalidate(); // resets cache on an Undo
  356. if (m_Version < k_LatestVersion)
  357. {
  358. UpgradeToLatestVersion();
  359. }
  360. }
  361. void __internalAwake()
  362. {
  363. if (m_Tracks == null)
  364. m_Tracks = new List<ScriptableObject>();
  365. #if UNITY_EDITOR
  366. // case 1280331 -- embedding the timeline asset inside a prefab will create a temporary non-persistent version of an asset
  367. // setting the track parents to this will change persistent tracks
  368. if (!UnityEditor.EditorUtility.IsPersistent(this))
  369. return;
  370. #endif
  371. // validate the array. DON'T remove Unity null objects, just actual null objects
  372. for (int i = m_Tracks.Count - 1; i >= 0; i--)
  373. {
  374. TrackAsset asset = m_Tracks[i] as TrackAsset;
  375. if (asset != null)
  376. asset.parent = this;
  377. #if UNITY_EDITOR
  378. object o = m_Tracks[i];
  379. if (o == null)
  380. {
  381. Debug.LogWarning("Empty track found while loading timeline. It will be removed.");
  382. m_Tracks.RemoveAt(i);
  383. }
  384. #endif
  385. }
  386. }
  387. /// <summary>
  388. /// Called by the Timeline Editor to gather properties requiring preview.
  389. /// </summary>
  390. /// <param name="director">The PlayableDirector invoking the preview</param>
  391. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  392. public void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  393. {
  394. var outputTracks = GetOutputTracks();
  395. foreach (var track in outputTracks)
  396. {
  397. if (!track.mutedInHierarchy)
  398. track.GatherProperties(director, driver);
  399. }
  400. }
  401. /// <summary>
  402. /// Creates a marker track for the TimelineAsset.
  403. /// </summary>
  404. /// In the editor, the marker track appears under the Timeline ruler.
  405. /// <remarks>
  406. /// This track is always bound to the GameObject that contains the PlayableDirector component for the current timeline.
  407. /// The marker track is created the first time this method is called. If the marker track is already created, this method does nothing.
  408. /// </remarks>
  409. public void CreateMarkerTrack()
  410. {
  411. if (m_MarkerTrack == null)
  412. {
  413. m_MarkerTrack = CreateInstance<MarkerTrack>();
  414. TimelineCreateUtilities.SaveAssetIntoObject(m_MarkerTrack, this);
  415. m_MarkerTrack.parent = this;
  416. m_MarkerTrack.name = "Markers"; // This name will show up in the bindings list if it contains signals
  417. Invalidate();
  418. }
  419. }
  420. // Invalidates the asset, call this if changing the asset data
  421. internal void Invalidate()
  422. {
  423. m_CacheRootTracks = null;
  424. m_CacheOutputTracks = null;
  425. m_CacheFlattenedTracks = null;
  426. }
  427. internal void UpdateFixedDurationWithItemsDuration()
  428. {
  429. m_FixedDuration = (double)CalculateItemsDuration();
  430. }
  431. DiscreteTime CalculateItemsDuration()
  432. {
  433. var discreteDuration = new DiscreteTime(0);
  434. foreach (var track in flattenedTracks)
  435. {
  436. if (track.muted)
  437. continue;
  438. discreteDuration = DiscreteTime.Max(discreteDuration, (DiscreteTime)track.end);
  439. }
  440. if (discreteDuration <= 0)
  441. return new DiscreteTime(0);
  442. return discreteDuration;
  443. }
  444. static void AddSubTracksRecursive(TrackAsset track, ref List<TrackAsset> allTracks)
  445. {
  446. if (track == null)
  447. return;
  448. allTracks.AddRange(track.GetChildTracks());
  449. foreach (TrackAsset subTrack in track.GetChildTracks())
  450. {
  451. AddSubTracksRecursive(subTrack, ref allTracks);
  452. }
  453. }
  454. }
  455. }