TrackAsset.cs 45 KB

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