暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TrackExtensions.cs 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.Timeline;
  6. using UnityEngine.Playables;
  7. namespace UnityEditor.Timeline
  8. {
  9. /// <summary>
  10. /// Extension Methods for Tracks that require the Unity Editor, and may require the Timeline containing the Track to be currently loaded in the Timeline Editor Window.
  11. /// </summary>
  12. public static class TrackExtensions
  13. {
  14. static readonly double kMinOverlapTime = TimeUtility.kTimeEpsilon * 1000;
  15. /// <summary>
  16. /// Queries whether the children of the Track are currently visible in the Timeline Editor.
  17. /// </summary>
  18. /// <param name="track">The track asset to query.</param>
  19. /// <returns>True if the track is collapsed and false otherwise.</returns>
  20. public static bool IsCollapsed(this TrackAsset track)
  21. {
  22. return TimelineWindowViewPrefs.IsTrackCollapsed(track);
  23. }
  24. /// <summary>
  25. /// Sets whether the children of the Track are currently visible in the Timeline Editor.
  26. /// </summary>
  27. /// <param name="track">The track asset to collapsed state to modify.</param>
  28. /// <param name="collapsed">`true` to collapse children, false otherwise.</param>
  29. /// <remarks> The track collapsed state is not serialized inside the asset and is lost from one checkout of the project to another. </remarks>>
  30. public static void SetCollapsed(this TrackAsset track, bool collapsed)
  31. {
  32. TimelineWindowViewPrefs.SetTrackCollapsed(track, collapsed);
  33. }
  34. /// <summary>
  35. /// Queries whether any parent of the track is collapsed, rendering the track not visible to the user.
  36. /// </summary>
  37. /// <param name="track">The track asset to query.</param>
  38. /// <returns>True if all parents are not collapsed, false otherwise.</returns>
  39. public static bool IsVisibleInHierarchy(this TrackAsset track)
  40. {
  41. var t = track;
  42. while ((t = t.parent as TrackAsset) != null)
  43. {
  44. if (t.IsCollapsed())
  45. return false;
  46. }
  47. return true;
  48. }
  49. internal static AnimationClip GetOrCreateClip(this AnimationTrack track)
  50. {
  51. if (track.infiniteClip == null && !track.inClipMode)
  52. track.CreateInfiniteClip(AnimationTrackRecorder.GetUniqueRecordedClipName(track, AnimationTrackRecorder.kRecordClipDefaultName));
  53. return track.infiniteClip;
  54. }
  55. internal static TimelineClip CreateClip(this TrackAsset track, double time)
  56. {
  57. var attr = track.GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
  58. if (attr.Length == 0)
  59. return null;
  60. if (TimelineWindow.instance.state == null)
  61. return null;
  62. if (attr.Length == 1)
  63. {
  64. var clipClass = (TrackClipTypeAttribute)attr[0];
  65. var clip = TimelineHelpers.CreateClipOnTrack(clipClass.inspectedType, track, time);
  66. return clip;
  67. }
  68. return null;
  69. }
  70. static bool Overlaps(TimelineClip blendOut, TimelineClip blendIn)
  71. {
  72. if (blendIn == blendOut)
  73. return false;
  74. if (Math.Abs(blendIn.start - blendOut.start) < TimeUtility.kTimeEpsilon)
  75. {
  76. return blendIn.duration >= blendOut.duration;
  77. }
  78. return blendIn.start >= blendOut.start && blendIn.start < blendOut.end;
  79. }
  80. internal static void ComputeBlendsFromOverlaps(this TrackAsset asset)
  81. {
  82. ComputeBlendsFromOverlaps(asset.clips);
  83. }
  84. internal static void ComputeBlendsFromOverlaps(TimelineClip[] clips)
  85. {
  86. foreach (var clip in clips)
  87. {
  88. clip.blendInDuration = -1;
  89. clip.blendOutDuration = -1;
  90. }
  91. Array.Sort(clips, (c1, c2) =>
  92. Math.Abs(c1.start - c2.start) < TimeUtility.kTimeEpsilon ? c1.duration.CompareTo(c2.duration) : c1.start.CompareTo(c2.start));
  93. for (var i = 0; i < clips.Length; i++)
  94. {
  95. var clip = clips[i];
  96. if (!clip.SupportsBlending())
  97. continue;
  98. var blendIn = clip;
  99. TimelineClip blendOut = null;
  100. var blendOutCandidate = clips[Math.Max(i - 1, 0)];
  101. if (Overlaps(blendOutCandidate, blendIn))
  102. blendOut = blendOutCandidate;
  103. if (blendOut != null)
  104. {
  105. UpdateClipIntersection(blendOut, blendIn);
  106. }
  107. }
  108. }
  109. static void UpdateClipIntersection(TimelineClip blendOutClip, TimelineClip blendInClip)
  110. {
  111. if (!blendOutClip.SupportsBlending() || !blendInClip.SupportsBlending())
  112. return;
  113. if (blendInClip.start - blendOutClip.start < blendOutClip.duration - blendInClip.duration)
  114. return;
  115. double duration = Math.Max(0, blendOutClip.start + blendOutClip.duration - blendInClip.start);
  116. duration = duration <= kMinOverlapTime ? 0 : duration;
  117. blendOutClip.blendOutDuration = duration;
  118. blendInClip.blendInDuration = duration;
  119. var blendInMode = blendInClip.blendInCurveMode;
  120. var blendOutMode = blendOutClip.blendOutCurveMode;
  121. if (blendInMode == TimelineClip.BlendCurveMode.Manual && blendOutMode == TimelineClip.BlendCurveMode.Auto)
  122. {
  123. blendOutClip.mixOutCurve = CurveEditUtility.CreateMatchingCurve(blendInClip.mixInCurve);
  124. }
  125. else if (blendInMode == TimelineClip.BlendCurveMode.Auto && blendOutMode == TimelineClip.BlendCurveMode.Manual)
  126. {
  127. blendInClip.mixInCurve = CurveEditUtility.CreateMatchingCurve(blendOutClip.mixOutCurve);
  128. }
  129. else if (blendInMode == TimelineClip.BlendCurveMode.Auto && blendOutMode == TimelineClip.BlendCurveMode.Auto)
  130. {
  131. blendInClip.mixInCurve = null; // resets to default curves
  132. blendOutClip.mixOutCurve = null;
  133. }
  134. }
  135. static void RecursiveSubtrackClone(TrackAsset source, TrackAsset duplicate, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset assetOwner)
  136. {
  137. var subtracks = source.GetChildTracks();
  138. foreach (var sub in subtracks)
  139. {
  140. var newSub = TimelineHelpers.Clone(duplicate, sub, sourceTable, destTable, assetOwner);
  141. duplicate.AddChild(newSub);
  142. RecursiveSubtrackClone(sub, newSub, sourceTable, destTable, assetOwner);
  143. // Call the custom editor on Create
  144. var customEditor = CustomTimelineEditorCache.GetTrackEditor(newSub);
  145. customEditor.OnCreate_Safe(newSub, sub);
  146. // registration has to happen AFTER recursion
  147. TimelineCreateUtilities.SaveAssetIntoObject(newSub, assetOwner);
  148. TimelineUndo.RegisterCreatedObjectUndo(newSub, L10n.Tr("Duplicate"));
  149. }
  150. }
  151. internal static TrackAsset Duplicate(this TrackAsset track, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable,
  152. TimelineAsset destinationTimeline = null)
  153. {
  154. if (track == null)
  155. return null;
  156. // if the destination is us, clear to avoid bad parenting (case 919421)
  157. if (destinationTimeline == track.timelineAsset)
  158. destinationTimeline = null;
  159. var timelineParent = track.parent as TimelineAsset;
  160. var trackParent = track.parent as TrackAsset;
  161. if (timelineParent == null && trackParent == null)
  162. {
  163. Debug.LogWarning("Cannot duplicate track because it is not parented to known type");
  164. return null;
  165. }
  166. // Determine who the final parent is. If we are pasting into another track, it's always the timeline.
  167. // Otherwise it's the original parent
  168. PlayableAsset finalParent = destinationTimeline != null ? destinationTimeline : track.parent;
  169. // grab the list of tracks to generate a name from (923360) to get the list of names
  170. // no need to do this part recursively
  171. var finalTrackParent = finalParent as TrackAsset;
  172. var finalTimelineAsset = finalParent as TimelineAsset;
  173. var otherTracks = (finalTimelineAsset != null) ? finalTimelineAsset.trackObjects : finalTrackParent.subTracksObjects;
  174. // Important to create the new objects before pushing the original undo, or redo breaks the
  175. // sequence
  176. var newTrack = TimelineHelpers.Clone(finalParent, track, sourceTable, destTable, finalParent);
  177. newTrack.name = TimelineCreateUtilities.GenerateUniqueActorName(otherTracks, newTrack.name);
  178. RecursiveSubtrackClone(track, newTrack, sourceTable, destTable, finalParent);
  179. TimelineCreateUtilities.SaveAssetIntoObject(newTrack, finalParent);
  180. TimelineUndo.RegisterCreatedObjectUndo(newTrack, L10n.Tr("Duplicate"));
  181. UndoExtensions.RegisterPlayableAsset(finalParent, L10n.Tr("Duplicate"));
  182. if (destinationTimeline != null) // other timeline
  183. destinationTimeline.AddTrackInternal(newTrack);
  184. else if (timelineParent != null) // this timeline, no parent
  185. ReparentTracks(new List<TrackAsset> { newTrack }, timelineParent, timelineParent.GetRootTracks().Last(), false);
  186. else // this timeline, with parent
  187. trackParent.AddChild(newTrack);
  188. // Call the custom editor. this check prevents the call when copying to the clipboard
  189. if (destinationTimeline == null || destinationTimeline == TimelineEditor.inspectedAsset)
  190. {
  191. var customEditor = CustomTimelineEditorCache.GetTrackEditor(newTrack);
  192. customEditor.OnCreate_Safe(newTrack, track);
  193. }
  194. return newTrack;
  195. }
  196. // Reparents a list of tracks to a new parent
  197. // the new parent cannot be null (has to be track asset or sequence)
  198. // the insertAfter can be null (will not reorder)
  199. internal static bool ReparentTracks(List<TrackAsset> tracksToMove, PlayableAsset targetParent,
  200. TrackAsset insertMarker = null, bool insertBefore = false)
  201. {
  202. var targetParentTrack = targetParent as TrackAsset;
  203. var targetSequenceTrack = targetParent as TimelineAsset;
  204. if (tracksToMove == null || tracksToMove.Count == 0 || (targetParentTrack == null && targetSequenceTrack == null))
  205. return false;
  206. // invalid parent type on a track
  207. if (targetParentTrack != null && tracksToMove.Any(x => !TimelineCreateUtilities.ValidateParentTrack(targetParentTrack, x.GetType())))
  208. return false;
  209. // no valid tracks means this is simply a rearrangement
  210. var validTracks = tracksToMove.Where(x => x.parent != targetParent).ToList();
  211. if (insertMarker == null && !validTracks.Any())
  212. return false;
  213. var parents = validTracks.Select(x => x.parent).Where(x => x != null).Distinct().ToList();
  214. // push the current state of the tracks that will change
  215. foreach (var p in parents)
  216. {
  217. UndoExtensions.RegisterPlayableAsset(p, "Reparent");
  218. }
  219. UndoExtensions.RegisterTracks(validTracks, "Reparent");
  220. UndoExtensions.RegisterPlayableAsset(targetParent, "Reparent");
  221. // need to reparent tracks first, before moving them.
  222. foreach (var t in validTracks)
  223. {
  224. if (t.parent != targetParent)
  225. {
  226. TrackAsset toMoveParent = t.parent as TrackAsset;
  227. TimelineAsset toMoveTimeline = t.parent as TimelineAsset;
  228. if (toMoveTimeline != null)
  229. {
  230. toMoveTimeline.RemoveTrack(t);
  231. }
  232. else if (toMoveParent != null)
  233. {
  234. toMoveParent.RemoveSubTrack(t);
  235. }
  236. if (targetParentTrack != null)
  237. {
  238. targetParentTrack.AddChild(t);
  239. targetParentTrack.SetCollapsed(false);
  240. }
  241. else
  242. {
  243. targetSequenceTrack.AddTrackInternal(t);
  244. }
  245. }
  246. }
  247. if (insertMarker != null)
  248. {
  249. // re-ordering track. This is using internal APIs, so invalidation of the tracks must be done manually to avoid
  250. // cache mismatches
  251. var children = targetParentTrack != null ? targetParentTrack.subTracksObjects : targetSequenceTrack.trackObjects;
  252. TimelineUtility.ReorderTracks(children, tracksToMove, insertMarker, insertBefore);
  253. if (targetParentTrack != null)
  254. targetParentTrack.Invalidate();
  255. if (insertMarker.timelineAsset != null)
  256. insertMarker.timelineAsset.Invalidate();
  257. }
  258. return true;
  259. }
  260. internal static IEnumerable<TrackAsset> FilterTracks(IEnumerable<TrackAsset> tracks)
  261. {
  262. var nTracks = tracks.Count();
  263. // Duplicate is recursive. If should not have parent and child in the list
  264. var hash = new HashSet<TrackAsset>(tracks);
  265. var take = new Dictionary<TrackAsset, bool>(nTracks);
  266. foreach (var track in tracks)
  267. {
  268. var parent = track.parent as TrackAsset;
  269. var foundParent = false;
  270. // go up the hierarchy
  271. while (parent != null && !foundParent)
  272. {
  273. if (hash.Contains(parent))
  274. {
  275. foundParent = true;
  276. }
  277. parent = parent.parent as TrackAsset;
  278. }
  279. take[track] = !foundParent;
  280. }
  281. foreach (var track in tracks)
  282. {
  283. if (take[track])
  284. yield return track;
  285. }
  286. }
  287. internal static bool GetShowMarkers(this TrackAsset track)
  288. {
  289. return TimelineWindowViewPrefs.IsShowMarkers(track);
  290. }
  291. internal static void SetShowMarkers(this TrackAsset track, bool collapsed)
  292. {
  293. TimelineWindowViewPrefs.SetTrackShowMarkers(track, collapsed);
  294. }
  295. internal static bool GetShowInlineCurves(this TrackAsset track)
  296. {
  297. return TimelineWindowViewPrefs.GetShowInlineCurves(track);
  298. }
  299. internal static void SetShowInlineCurves(this TrackAsset track, bool inlineOn)
  300. {
  301. TimelineWindowViewPrefs.SetShowInlineCurves(track, inlineOn);
  302. }
  303. internal static bool ShouldShowInfiniteClipEditor(this AnimationTrack track)
  304. {
  305. return track != null && !track.inClipMode && track.infiniteClip != null;
  306. }
  307. // Special method to remove a track that is in a broken state. i.e. the script won't load
  308. internal static bool RemoveBrokenTrack(PlayableAsset parent, ScriptableObject track)
  309. {
  310. var parentTrack = parent as TrackAsset;
  311. var parentTimeline = parent as TimelineAsset;
  312. if (parentTrack == null && parentTimeline == null)
  313. throw new ArgumentException("parent is not a valid parent type", "parent");
  314. // this object must be a Unity null, but not actually null;
  315. object trackAsObject = track;
  316. if (trackAsObject == null || track as TrackAsset != null) // yes, this is correct
  317. throw new ArgumentException("track is not in a broken state");
  318. // this belongs to a parent track
  319. if (parentTrack != null)
  320. {
  321. int index = parentTrack.subTracksObjects.FindIndex(t => t.GetInstanceID() == track.GetInstanceID());
  322. if (index >= 0)
  323. {
  324. UndoExtensions.RegisterTrack(parentTrack, L10n.Tr("Remove Track"));
  325. parentTrack.subTracksObjects.RemoveAt(index);
  326. parentTrack.Invalidate();
  327. Undo.DestroyObjectImmediate(track);
  328. return true;
  329. }
  330. }
  331. else if (parentTimeline != null)
  332. {
  333. int index = parentTimeline.trackObjects.FindIndex(t => t.GetInstanceID() == track.GetInstanceID());
  334. if (index >= 0)
  335. {
  336. UndoExtensions.RegisterPlayableAsset(parentTimeline, L10n.Tr("Remove Track"));
  337. parentTimeline.trackObjects.RemoveAt(index);
  338. parentTimeline.Invalidate();
  339. Undo.DestroyObjectImmediate(track);
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. // Find the gap at the given time
  346. // return true if there is a gap, false if there is an intersection
  347. // endGap will be Infinity if the gap has no end
  348. internal static bool GetGapAtTime(this TrackAsset track, double time, out double startGap, out double endGap)
  349. {
  350. startGap = 0;
  351. endGap = Double.PositiveInfinity;
  352. if (track == null || !track.GetClips().Any())
  353. {
  354. return false;
  355. }
  356. var discreteTime = new DiscreteTime(time);
  357. track.SortClips();
  358. var sortedByStartTime = track.clips;
  359. for (int i = 0; i < sortedByStartTime.Length; i++)
  360. {
  361. var clip = sortedByStartTime[i];
  362. // intersection
  363. if (discreteTime >= new DiscreteTime(clip.start) && discreteTime < new DiscreteTime(clip.end))
  364. {
  365. endGap = time;
  366. startGap = time;
  367. return false;
  368. }
  369. if (clip.end < time)
  370. {
  371. startGap = clip.end;
  372. }
  373. if (clip.start > time)
  374. {
  375. endGap = clip.start;
  376. break;
  377. }
  378. }
  379. if (endGap - startGap < TimelineClip.kMinDuration)
  380. {
  381. startGap = time;
  382. endGap = time;
  383. return false;
  384. }
  385. return true;
  386. }
  387. internal static bool IsCompatibleWithClip(this TrackAsset track, TimelineClip clip)
  388. {
  389. if (track == null || clip == null || clip.asset == null)
  390. return false;
  391. return TypeUtility.GetPlayableAssetsHandledByTrack(track.GetType()).Contains(clip.asset.GetType());
  392. }
  393. // Get a flattened list of all child tracks
  394. static void GetFlattenedChildTracks(this TrackAsset asset, List<TrackAsset> list)
  395. {
  396. if (asset == null || list == null)
  397. return;
  398. foreach (var track in asset.GetChildTracks())
  399. {
  400. list.Add(track);
  401. GetFlattenedChildTracks(track, list);
  402. }
  403. }
  404. internal static IEnumerable<TrackAsset> GetFlattenedChildTracks(this TrackAsset asset)
  405. {
  406. if (asset == null || !asset.GetChildTracks().Any())
  407. return Enumerable.Empty<TrackAsset>();
  408. var flattenedChildTracks = new List<TrackAsset>();
  409. GetFlattenedChildTracks(asset, flattenedChildTracks);
  410. return flattenedChildTracks;
  411. }
  412. internal static void ArmForRecord(this TrackAsset track)
  413. {
  414. TimelineWindow.instance.state.ArmForRecord(track);
  415. }
  416. internal static void UnarmForRecord(this TrackAsset track)
  417. {
  418. TimelineWindow.instance.state.UnarmForRecord(track);
  419. }
  420. internal static void SetShowTrackMarkers(this TrackAsset track, bool showMarkers)
  421. {
  422. var currentValue = track.GetShowMarkers();
  423. if (currentValue != showMarkers)
  424. {
  425. TimelineUndo.PushUndo(TimelineWindow.instance.state.editSequence.viewModel, L10n.Tr("Toggle Show Markers"));
  426. track.SetShowMarkers(showMarkers);
  427. if (!showMarkers)
  428. {
  429. foreach (var marker in track.GetMarkers())
  430. {
  431. SelectionManager.Remove(marker);
  432. }
  433. }
  434. }
  435. }
  436. internal static IEnumerable<TrackAsset> RemoveTimelineMarkerTrackFromList(this IEnumerable<TrackAsset> tracks, TimelineAsset asset)
  437. {
  438. return tracks.Where(t => t != asset.markerTrack);
  439. }
  440. internal static bool ContainsTimelineMarkerTrack(this IEnumerable<TrackAsset> tracks, TimelineAsset asset)
  441. {
  442. return tracks.Contains(asset.markerTrack);
  443. }
  444. internal static void SetNameWithUndo(this TrackAsset track, string newName)
  445. {
  446. UndoExtensions.RegisterTrack(track, L10n.Tr("Rename Track"));
  447. track.name = newName;
  448. }
  449. }
  450. }