AnimationWindow.cs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. using BansheeEngine;
  8. namespace BansheeEditor
  9. {
  10. /** @addtogroup Windows
  11. * @{
  12. */
  13. /// <summary>
  14. /// Displays animation curve editor window. Allows the user to manipulate keyframes of animation curves, add/remove
  15. /// curves from an animation clip, and manipulate animation events.
  16. /// </summary>
  17. [DefaultSize(900, 500), UndoRedoLocal]
  18. internal class AnimationWindow : EditorWindow
  19. {
  20. private const int FIELD_DISPLAY_WIDTH = 300;
  21. private SceneObject selectedSO;
  22. #region Overrides
  23. /// <summary>
  24. /// Opens the animation window.
  25. /// </summary>
  26. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  27. private static void OpenGameWindow()
  28. {
  29. OpenWindow<AnimationWindow>();
  30. }
  31. /// <inheritdoc/>
  32. protected override LocString GetDisplayName()
  33. {
  34. return new LocEdString("Animation");
  35. }
  36. private void OnInitialize()
  37. {
  38. Selection.OnSelectionChanged += OnSelectionChanged;
  39. UpdateSelectedSO(true);
  40. }
  41. private void OnEditorUpdate()
  42. {
  43. if (selectedSO == null)
  44. return;
  45. guiCurveEditor.HandleDragAndZoomInput();
  46. if (state == State.Playback)
  47. {
  48. Animation animation = selectedSO.GetComponent<Animation>();
  49. if (animation != null)
  50. {
  51. float time = animation.EditorGetTime();
  52. int frameIdx = (int)(time * fps);
  53. SetCurrentFrame(frameIdx);
  54. animation.UpdateFloatProperties();
  55. }
  56. }
  57. else if (state == State.Recording)
  58. {
  59. if (!delayRecord)
  60. {
  61. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  62. if (RecordState(time))
  63. {
  64. ApplyClipChanges();
  65. guiCurveEditor.Redraw();
  66. }
  67. }
  68. }
  69. delayRecord = false;
  70. }
  71. private void OnDestroy()
  72. {
  73. SwitchState(State.Empty);
  74. Selection.OnSelectionChanged -= OnSelectionChanged;
  75. if (selectedSO != null)
  76. {
  77. EditorInput.OnPointerPressed -= OnPointerPressed;
  78. EditorInput.OnPointerDoubleClick -= OnPointerDoubleClicked;
  79. EditorInput.OnPointerMoved -= OnPointerMoved;
  80. EditorInput.OnPointerReleased -= OnPointerReleased;
  81. EditorInput.OnButtonUp -= OnButtonUp;
  82. }
  83. }
  84. /// <inheritdoc/>
  85. protected override void WindowResized(int width, int height)
  86. {
  87. if (selectedSO == null)
  88. return;
  89. ResizeGUI(width, height);
  90. }
  91. #endregion
  92. #region GUI
  93. private GUIToggle playButton;
  94. private GUIToggle recordButton;
  95. private GUIButton prevFrameButton;
  96. private GUIIntField frameInputField;
  97. private GUIButton nextFrameButton;
  98. private GUIButton addKeyframeButton;
  99. private GUIButton addEventButton;
  100. private GUIButton optionsButton;
  101. private GUIButton addPropertyBtn;
  102. private GUIButton delPropertyBtn;
  103. private GUILayout buttonLayout;
  104. private int buttonLayoutHeight;
  105. private GUIAnimFieldDisplay guiFieldDisplay;
  106. private GUICurveEditor guiCurveEditor;
  107. /// <summary>
  108. /// Recreates the entire curve editor GUI depending on the currently selected scene object.
  109. /// </summary>
  110. private void RebuildGUI()
  111. {
  112. GUI.Clear();
  113. guiCurveEditor = null;
  114. guiFieldDisplay = null;
  115. if (selectedSO == null)
  116. {
  117. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  118. GUILayoutY vertLayout = GUI.AddLayoutY();
  119. vertLayout.AddFlexibleSpace();
  120. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  121. vertLayout.AddFlexibleSpace();
  122. horzLayout.AddFlexibleSpace();
  123. horzLayout.AddElement(warningLbl);
  124. horzLayout.AddFlexibleSpace();
  125. return;
  126. }
  127. // Top button row
  128. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  129. new LocEdString("Play"));
  130. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  131. new LocEdString("Record"));
  132. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  133. new LocEdString("Previous frame"));
  134. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  135. new LocEdString("Next frame"));
  136. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  137. new LocEdString("Add keyframe"));
  138. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  139. new LocEdString("Add event"));
  140. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  141. new LocEdString("Options"));
  142. playButton = new GUIToggle(playIcon, EditorStyles.Button);
  143. recordButton = new GUIToggle(recordIcon, EditorStyles.Button);
  144. prevFrameButton = new GUIButton(prevFrameIcon);
  145. frameInputField = new GUIIntField();
  146. nextFrameButton = new GUIButton(nextFrameIcon);
  147. addKeyframeButton = new GUIButton(addKeyframeIcon);
  148. addEventButton = new GUIButton(addEventIcon);
  149. optionsButton = new GUIButton(optionsIcon);
  150. playButton.OnToggled += x =>
  151. {
  152. if(x)
  153. SwitchState(State.Playback);
  154. else
  155. SwitchState(State.Normal);
  156. };
  157. recordButton.OnToggled += x =>
  158. {
  159. if (x)
  160. SwitchState(State.Recording);
  161. else
  162. SwitchState(State.Normal);
  163. };
  164. prevFrameButton.OnClick += () =>
  165. {
  166. SetCurrentFrame(currentFrameIdx - 1);
  167. switch (state)
  168. {
  169. case State.Recording:
  170. case State.Normal:
  171. PreviewFrame(currentFrameIdx);
  172. break;
  173. default:
  174. SwitchState(State.Normal);
  175. break;
  176. }
  177. };
  178. frameInputField.OnChanged += x =>
  179. {
  180. SetCurrentFrame(x);
  181. switch (state)
  182. {
  183. case State.Recording:
  184. case State.Normal:
  185. PreviewFrame(currentFrameIdx);
  186. break;
  187. default:
  188. SwitchState(State.Normal);
  189. break;
  190. }
  191. };
  192. nextFrameButton.OnClick += () =>
  193. {
  194. SetCurrentFrame(currentFrameIdx + 1);
  195. switch (state)
  196. {
  197. case State.Recording:
  198. case State.Normal:
  199. PreviewFrame(currentFrameIdx);
  200. break;
  201. default:
  202. SwitchState(State.Normal);
  203. break;
  204. }
  205. };
  206. addKeyframeButton.OnClick += () =>
  207. {
  208. SwitchState(State.Normal);
  209. guiCurveEditor.AddKeyFrameAtMarker();
  210. };
  211. addEventButton.OnClick += () =>
  212. {
  213. SwitchState(State.Normal);
  214. guiCurveEditor.AddEventAtMarker();
  215. };
  216. optionsButton.OnClick += () =>
  217. {
  218. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  219. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(GUI, openPosition);
  220. dropDown.Initialize(this);
  221. };
  222. // Property buttons
  223. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  224. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  225. addPropertyBtn.OnClick += () =>
  226. {
  227. Action openPropertyWindow = () =>
  228. {
  229. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  230. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(GUI, windowPos);
  231. fieldSelection.OnFieldSelected += OnFieldAdded;
  232. };
  233. if (clipInfo.clip == null)
  234. {
  235. LocEdString title = new LocEdString("Warning");
  236. LocEdString message =
  237. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  238. " a new animation clip?");
  239. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  240. {
  241. if (type == DialogBox.ResultType.Yes)
  242. {
  243. string clipSavePath;
  244. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.asset", out clipSavePath))
  245. {
  246. SwitchState(State.Empty);
  247. clipSavePath = Path.ChangeExtension(clipSavePath, ".asset");
  248. AnimationClip newClip = new AnimationClip();
  249. ProjectLibrary.Create(newClip, clipSavePath);
  250. LoadAnimClip(newClip);
  251. Animation animation = selectedSO.GetComponent<Animation>();
  252. if (animation == null)
  253. animation = selectedSO.AddComponent<Animation>();
  254. animation.DefaultClip = newClip;
  255. EditorApplication.SetSceneDirty();
  256. SwitchState(State.Normal);
  257. openPropertyWindow();
  258. }
  259. }
  260. });
  261. }
  262. else
  263. {
  264. if (clipInfo.isImported)
  265. {
  266. LocEdString title = new LocEdString("Warning");
  267. LocEdString message =
  268. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  269. " are imported from an external file.");
  270. DialogBox.Open(title, message, DialogBox.Type.OK);
  271. }
  272. else
  273. {
  274. SwitchState(State.Normal);
  275. openPropertyWindow();
  276. }
  277. }
  278. };
  279. delPropertyBtn.OnClick += () =>
  280. {
  281. if (clipInfo.clip == null)
  282. return;
  283. SwitchState(State.Normal);
  284. if (clipInfo.isImported)
  285. {
  286. LocEdString title = new LocEdString("Warning");
  287. LocEdString message =
  288. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  289. " are imported from an external file.");
  290. DialogBox.Open(title, message, DialogBox.Type.OK);
  291. }
  292. else
  293. {
  294. LocEdString title = new LocEdString("Warning");
  295. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  296. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  297. {
  298. if (x == DialogBox.ResultType.Yes)
  299. {
  300. RemoveSelectedFields();
  301. ApplyClipChanges();
  302. }
  303. });
  304. }
  305. };
  306. GUIPanel mainPanel = GUI.AddPanel();
  307. GUIPanel backgroundPanel = GUI.AddPanel(1);
  308. GUILayout mainLayout = mainPanel.AddLayoutY();
  309. buttonLayout = mainLayout.AddLayoutX();
  310. buttonLayout.AddSpace(5);
  311. buttonLayout.AddElement(playButton);
  312. buttonLayout.AddElement(recordButton);
  313. buttonLayout.AddSpace(5);
  314. buttonLayout.AddElement(prevFrameButton);
  315. buttonLayout.AddElement(frameInputField);
  316. buttonLayout.AddElement(nextFrameButton);
  317. buttonLayout.AddSpace(5);
  318. buttonLayout.AddElement(addKeyframeButton);
  319. buttonLayout.AddElement(addEventButton);
  320. buttonLayout.AddSpace(5);
  321. buttonLayout.AddElement(optionsButton);
  322. buttonLayout.AddFlexibleSpace();
  323. buttonLayoutHeight = playButton.Bounds.height;
  324. GUITexture buttonBackground = new GUITexture(null, EditorStyles.HeaderBackground);
  325. buttonBackground.Bounds = new Rect2I(0, 0, Width, buttonLayoutHeight);
  326. backgroundPanel.AddElement(buttonBackground);
  327. GUILayout contentLayout = mainLayout.AddLayoutX();
  328. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  329. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  330. Height - buttonLayoutHeight * 2, selectedSO);
  331. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  332. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  333. bottomButtonLayout.AddElement(addPropertyBtn);
  334. bottomButtonLayout.AddElement(delPropertyBtn);
  335. GUITexture separator = new GUITexture(null, EditorStyles.Separator, GUIOption.FixedWidth(3));
  336. contentLayout.AddElement(separator);
  337. GUILayout curveLayout = contentLayout.AddLayoutY();
  338. Vector2I curveEditorSize = GetCurveEditorSize();
  339. guiCurveEditor = new GUICurveEditor(curveLayout, curveEditorSize.x, curveEditorSize.y, true);
  340. guiCurveEditor.SetEventSceneObject(selectedSO);
  341. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  342. guiCurveEditor.OnEventAdded += () =>
  343. {
  344. OnEventsChanged();
  345. RecordClipState();
  346. };
  347. guiCurveEditor.OnEventModified += () =>
  348. {
  349. EditorApplication.SetProjectDirty();
  350. RecordClipState();
  351. };
  352. guiCurveEditor.OnEventDeleted += () =>
  353. {
  354. OnEventsChanged();
  355. RecordClipState();
  356. };
  357. guiCurveEditor.OnCurveModified += () =>
  358. {
  359. RecordClipState();
  360. SwitchState(State.Normal);
  361. ApplyClipChanges();
  362. PreviewFrame(currentFrameIdx);
  363. EditorApplication.SetProjectDirty();
  364. };
  365. guiCurveEditor.OnClicked += () =>
  366. {
  367. if(state != State.Recording)
  368. SwitchState(State.Normal);
  369. };
  370. guiCurveEditor.Redraw();
  371. }
  372. /// <summary>
  373. /// Resizes GUI elements so they fit within the provided boundaries.
  374. /// </summary>
  375. /// <param name="width">Width of the GUI bounds, in pixels.</param>
  376. /// <param name="height">Height of the GUI bounds, in pixels.</param>
  377. private void ResizeGUI(int width, int height)
  378. {
  379. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  380. Vector2I curveEditorSize = GetCurveEditorSize();
  381. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  382. guiCurveEditor.Redraw();
  383. }
  384. #endregion
  385. #region Curve save/load
  386. private EditorAnimClipInfo clipInfo;
  387. /// <summary>
  388. /// Refreshes the contents of the curve and property display by loading animation curves from the provided
  389. /// animation clip.
  390. /// </summary>
  391. /// <param name="clip">Clip containing the animation to load.</param>
  392. private void LoadAnimClip(AnimationClip clip)
  393. {
  394. EditorPersistentData persistentData = EditorApplication.PersistentData;
  395. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  396. {
  397. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  398. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  399. // within the editor.
  400. if (clipInfo.isImported)
  401. {
  402. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  403. newClipInfo.events = clipInfo.events;
  404. }
  405. }
  406. else
  407. clipInfo = EditorAnimClipInfo.Create(clip);
  408. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  409. AnimFieldInfo[] fieldInfos = new AnimFieldInfo[clipInfo.curves.Count];
  410. int idx = 0;
  411. foreach (var curve in clipInfo.curves)
  412. fieldInfos[idx++] = new AnimFieldInfo(curve.Key, curve.Value);
  413. guiFieldDisplay.SetFields(fieldInfos);
  414. guiCurveEditor.Events = clipInfo.events;
  415. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  416. SetCurrentFrame(0);
  417. FPS = clipInfo.sampleRate;
  418. }
  419. /// <summary>
  420. /// Applies any changes made to the animation curves and events to the actual animation clip resource.
  421. /// </summary>
  422. private void ApplyClipChanges()
  423. {
  424. if (clipInfo == null)
  425. return;
  426. EditorAnimClipTangents unused;
  427. clipInfo.Apply(out unused);
  428. }
  429. /// <summary>
  430. /// Checks if the currently selected object has changed, and rebuilds the GUI and loads the animation clip if needed.
  431. /// </summary>
  432. /// <param name="force">If true the GUI rebuild and animation clip load will be forced regardless if the active
  433. /// scene object changed.</param>
  434. private void UpdateSelectedSO(bool force)
  435. {
  436. SceneObject so = Selection.SceneObject;
  437. if (selectedSO != so || force)
  438. {
  439. if (selectedSO != null && so == null)
  440. {
  441. EditorInput.OnPointerPressed -= OnPointerPressed;
  442. EditorInput.OnPointerDoubleClick -= OnPointerDoubleClicked;
  443. EditorInput.OnPointerMoved -= OnPointerMoved;
  444. EditorInput.OnPointerReleased -= OnPointerReleased;
  445. EditorInput.OnButtonUp -= OnButtonUp;
  446. }
  447. else if (selectedSO == null && so != null)
  448. {
  449. EditorInput.OnPointerPressed += OnPointerPressed;
  450. EditorInput.OnPointerDoubleClick += OnPointerDoubleClicked;
  451. EditorInput.OnPointerMoved += OnPointerMoved;
  452. EditorInput.OnPointerReleased += OnPointerReleased;
  453. EditorInput.OnButtonUp += OnButtonUp;
  454. }
  455. SwitchState(State.Empty);
  456. selectedSO = so;
  457. selectedFields.Clear();
  458. clipInfo = null;
  459. UndoRedo.Clear();
  460. RebuildGUI();
  461. // Load existing clip if one exists
  462. if (selectedSO != null)
  463. {
  464. Animation animation = selectedSO.GetComponent<Animation>();
  465. if (animation != null)
  466. {
  467. AnimationClip clip = animation.DefaultClip.Value;
  468. if (clip != null)
  469. LoadAnimClip(clip);
  470. }
  471. }
  472. if(clipInfo == null)
  473. clipInfo = new EditorAnimClipInfo();
  474. SwitchState(State.Normal);
  475. currentClipState = CreateClipState();
  476. if (selectedSO != null)
  477. {
  478. // Select first curve by default
  479. foreach (var KVP in clipInfo.curves)
  480. {
  481. SelectField(KVP.Key, false);
  482. break;
  483. }
  484. UpdateDisplayedCurves(true);
  485. }
  486. }
  487. }
  488. /// <summary>
  489. /// Stops animation preview on the selected object and resets it back to its non-animated state.
  490. /// </summary>
  491. private void ClearSO()
  492. {
  493. if (selectedSO != null)
  494. {
  495. Animation animation = selectedSO.GetComponent<Animation>();
  496. if (animation != null)
  497. animation.EditorStop();
  498. // Reset generic curves to their initial values
  499. UpdateGenericCurves(0.0f);
  500. }
  501. }
  502. #endregion
  503. #region Undo/Redo
  504. private AnimationClipState currentClipState;
  505. /// <summary>
  506. /// Records current clip state for undo/redo purposes.
  507. /// </summary>
  508. private void RecordClipState()
  509. {
  510. AnimationClipState clipState = CreateClipState();
  511. AnimationUndo undoCommand = new AnimationUndo(currentClipState, clipState);
  512. UndoRedo.RegisterCommand(undoCommand);
  513. currentClipState = clipState;
  514. }
  515. /// <summary>
  516. /// Records current clip state for undo/redo purposes.
  517. /// </summary>
  518. private AnimationClipState CreateClipState()
  519. {
  520. AnimationClipState clipState = new AnimationClipState();
  521. clipState.events = new AnimationEvent[clipInfo.events.Length];
  522. for (int i = 0; i < clipState.events.Length; i++)
  523. clipState.events[i] = new AnimationEvent(clipInfo.events[i].name, clipInfo.events[i].time);
  524. foreach (var curveField in clipInfo.curves)
  525. {
  526. AnimationCurveState[] curveData = new AnimationCurveState[curveField.Value.curveInfos.Length];
  527. for (int i = 0; i < curveData.Length; i++)
  528. {
  529. curveData[i] = new AnimationCurveState();
  530. TangentMode[] tangentModes = curveField.Value.curveInfos[i].curve.TangentModes;
  531. int numTangentModes = tangentModes.Length;
  532. curveData[i].tangentModes = new TangentMode[numTangentModes];
  533. Array.Copy(tangentModes, curveData[i].tangentModes, numTangentModes);
  534. KeyFrame[] keyFrames = curveField.Value.curveInfos[i].curve.KeyFrames;
  535. int numKeyframes = keyFrames.Length;
  536. curveData[i].keyFrames = new KeyFrame[numKeyframes];
  537. Array.Copy(keyFrames, curveData[i].keyFrames, numKeyframes);
  538. }
  539. clipState.curves[curveField.Key] = curveData;
  540. }
  541. return clipState;
  542. }
  543. /// <summary>
  544. /// Updates the current animation fields from the keyframes and events in the provided state.
  545. /// </summary>
  546. /// <param name="animationClipState">Saved state of an animation clip.</param>
  547. internal void ApplyClipState(AnimationClipState animationClipState)
  548. {
  549. if (state == State.Empty)
  550. return;
  551. SwitchState(State.Normal);
  552. AnimationEvent[] events = animationClipState.events;
  553. clipInfo.events = new AnimationEvent[events.Length];
  554. for(int i = 0; i < events.Length; i++)
  555. clipInfo.events[i] = new AnimationEvent(events[i].name, events[i].time);
  556. foreach (var KVP in animationClipState.curves)
  557. {
  558. FieldAnimCurves fieldCurves;
  559. if (!clipInfo.curves.TryGetValue(KVP.Key, out fieldCurves))
  560. continue;
  561. for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
  562. {
  563. AnimationCurve curve = new AnimationCurve(KVP.Value[i].keyFrames);
  564. fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, KVP.Value[i].tangentModes);
  565. }
  566. clipInfo.curves[KVP.Key] = fieldCurves;
  567. }
  568. // Clear all keyframes from curves not in the stored state
  569. foreach (var currentKVP in clipInfo.curves)
  570. {
  571. bool found = false;
  572. foreach (var stateKVP in animationClipState.curves)
  573. {
  574. if (currentKVP.Key == stateKVP.Key)
  575. {
  576. found = true;
  577. break;
  578. }
  579. }
  580. if (found)
  581. continue;
  582. FieldAnimCurves fieldCurves = currentKVP.Value;
  583. for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
  584. {
  585. AnimationCurve curve = new AnimationCurve(new KeyFrame[0]);
  586. fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, new TangentMode[0]);
  587. }
  588. }
  589. currentClipState = animationClipState;
  590. UpdateDisplayedCurves();
  591. ApplyClipChanges();
  592. PreviewFrame(currentFrameIdx);
  593. EditorApplication.SetProjectDirty();
  594. }
  595. #endregion
  596. #region Record/Playback
  597. /// <summary>
  598. /// Possible states the animation window can be in.
  599. /// </summary>
  600. private enum State
  601. {
  602. Empty,
  603. Normal,
  604. Recording,
  605. Playback
  606. }
  607. private State state = State.Empty;
  608. private bool delayRecord = false;
  609. /// <summary>
  610. /// Transitions the window into a different state. Caller must validate state transitions.
  611. /// </summary>
  612. /// <param name="state">New state to transition to.</param>
  613. private void SwitchState(State state)
  614. {
  615. switch (this.state)
  616. {
  617. case State.Normal:
  618. {
  619. switch (state)
  620. {
  621. case State.Playback:
  622. StartPlayback();
  623. break;
  624. case State.Recording:
  625. StartRecord();
  626. break;
  627. case State.Empty:
  628. ClearSO();
  629. break;
  630. }
  631. }
  632. break;
  633. case State.Playback:
  634. {
  635. switch (state)
  636. {
  637. case State.Normal:
  638. EndPlayback();
  639. PreviewFrame(currentFrameIdx);
  640. break;
  641. case State.Recording:
  642. EndPlayback();
  643. StartRecord();
  644. break;
  645. case State.Empty:
  646. EndPlayback();
  647. ClearSO();
  648. break;
  649. }
  650. }
  651. break;
  652. case State.Recording:
  653. {
  654. switch (state)
  655. {
  656. case State.Normal:
  657. EndRecord();
  658. PreviewFrame(currentFrameIdx);
  659. break;
  660. case State.Playback:
  661. EndRecord();
  662. StartPlayback();
  663. break;
  664. case State.Empty:
  665. EndRecord();
  666. ClearSO();
  667. break;
  668. }
  669. }
  670. break;
  671. case State.Empty:
  672. {
  673. switch (state)
  674. {
  675. case State.Normal:
  676. PreviewFrame(currentFrameIdx);
  677. break;
  678. case State.Playback:
  679. StartPlayback();
  680. break;
  681. case State.Recording:
  682. StartRecord();
  683. break;
  684. }
  685. }
  686. break;
  687. }
  688. this.state = state;
  689. }
  690. /// <summary>
  691. /// Plays back the animation on the currently selected object.
  692. /// </summary>
  693. private void StartPlayback()
  694. {
  695. EditorAnimClipTangents unused;
  696. clipInfo.Apply(out unused);
  697. Animation animation = selectedSO.GetComponent<Animation>();
  698. if (animation != null && clipInfo.clip != null)
  699. {
  700. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  701. animation.EditorPlay(clipInfo.clip, time);
  702. }
  703. playButton.Value = true;
  704. }
  705. /// <summary>
  706. /// Ends playback started with <see cref="StartPlayback"/>
  707. /// </summary>
  708. private void EndPlayback()
  709. {
  710. PreviewFrame(currentFrameIdx);
  711. playButton.Value = false;
  712. }
  713. /// <summary>
  714. /// Updates the visible animation to display the provided frame.
  715. /// </summary>
  716. /// <param name="frameIdx">Index of the animation frame to display.</param>
  717. private void PreviewFrame(int frameIdx)
  718. {
  719. if (selectedSO == null)
  720. return;
  721. float time = guiCurveEditor.GetTimeForFrame(frameIdx);
  722. Animation animation = selectedSO.GetComponent<Animation>();
  723. if (animation != null && clipInfo.clip != null)
  724. animation.EditorPlay(clipInfo.clip, time, true);
  725. UpdateGenericCurves(time);
  726. }
  727. /// <summary>
  728. /// Start recording modifications made to the selected scene object.
  729. /// </summary>
  730. private void StartRecord()
  731. {
  732. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  733. if (RecordState(time))
  734. {
  735. ApplyClipChanges();
  736. guiCurveEditor.Redraw();
  737. }
  738. recordButton.Value = true;
  739. }
  740. /// <summary>
  741. /// Stops recording modifications made to the selected scene object.
  742. /// </summary>
  743. private void EndRecord()
  744. {
  745. recordButton.Value = false;
  746. }
  747. /// <summary>
  748. /// Updates the states of all properties controlled by curves to the value of the curves at the provided time.
  749. /// </summary>
  750. /// <param name="time">Time at which to evaluate the curves controlling the properties.</param>
  751. private void UpdateGenericCurves(float time)
  752. {
  753. foreach (var KVP in clipInfo.curves)
  754. {
  755. FieldAnimCurves curves;
  756. if (!clipInfo.curves.TryGetValue(KVP.Key, out curves))
  757. continue;
  758. string suffix;
  759. SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
  760. if (property == null)
  761. continue;
  762. float DoOnComponent(int index)
  763. {
  764. EdAnimationCurve curve = curves.curveInfos[index].curve;
  765. return curve.Evaluate(time);
  766. }
  767. ForEachPropertyComponentSet(property, DoOnComponent);
  768. }
  769. }
  770. /// <summary>
  771. /// Iterates over all curve path fields and records their current state. If the state differs from the current
  772. /// curve values, new keyframes are added.
  773. /// </summary>
  774. /// <param name="time">Time for which to record the state, in seconds.</param>
  775. /// <returns>True if any changes were recorded, false otherwise.</returns>
  776. private bool RecordState(float time)
  777. {
  778. bool changesMade = false;
  779. foreach (var KVP in clipInfo.curves)
  780. {
  781. if (RecordState(KVP.Key, time))
  782. changesMade = true;
  783. }
  784. return changesMade;
  785. }
  786. /// <summary>
  787. /// Records the state of the provided property and adds it as a keyframe to the related animation curve (or updates
  788. /// an existing keyframe if the value is different).
  789. /// </summary>
  790. /// <param name="path">Path to the property whose state to record.</param>
  791. /// <param name="time">Time for which to record the state, in seconds.</param>
  792. /// <returns>True if any changes were recorded, false otherwise.</returns>
  793. private bool RecordState(string path, float time)
  794. {
  795. FieldAnimCurves curves;
  796. if (!clipInfo.curves.TryGetValue(path, out curves))
  797. return false;
  798. string suffix;
  799. SerializableProperty property = Animation.FindProperty(selectedSO, path, out suffix);
  800. if (property == null)
  801. return false;
  802. bool changesMade = false;
  803. void DoOnComponent(float value, int index)
  804. {
  805. EdAnimationCurve curve = curves.curveInfos[index].curve;
  806. float curveVal = curve.Evaluate(time);
  807. if (!MathEx.ApproxEquals(value, curveVal, 0.001f))
  808. {
  809. curve.AddOrUpdateKeyframe(time, value);
  810. curve.Apply();
  811. changesMade = true;
  812. }
  813. }
  814. ForEachPropertyComponentGet(property, DoOnComponent);
  815. return changesMade;
  816. }
  817. #endregion
  818. #region Curve display
  819. private int currentFrameIdx;
  820. private int fps = 1;
  821. /// <summary>
  822. /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
  823. /// placed.
  824. /// </summary>
  825. internal int FPS
  826. {
  827. get { return fps; }
  828. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  829. }
  830. /// <summary>
  831. /// Changes the currently selected frame in the curve display.
  832. /// </summary>
  833. /// <param name="frameIdx">Index of the frame to select.</param>
  834. private void SetCurrentFrame(int frameIdx)
  835. {
  836. currentFrameIdx = Math.Max(0, frameIdx);
  837. frameInputField.Value = currentFrameIdx;
  838. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  839. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  840. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  841. foreach (var kvp in clipInfo.curves)
  842. {
  843. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  844. fieldValue.path = kvp.Key;
  845. switch (kvp.Value.type)
  846. {
  847. case SerializableProperty.FieldType.Vector2:
  848. {
  849. Vector2 value = new Vector2();
  850. for (int i = 0; i < 2; i++)
  851. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  852. fieldValue.value = value;
  853. }
  854. break;
  855. case SerializableProperty.FieldType.Vector3:
  856. {
  857. Vector3 value = new Vector3();
  858. for (int i = 0; i < 3; i++)
  859. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  860. fieldValue.value = value;
  861. }
  862. break;
  863. case SerializableProperty.FieldType.Vector4:
  864. {
  865. Vector4 value = new Vector4();
  866. for (int i = 0; i < 4; i++)
  867. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  868. fieldValue.value = value;
  869. }
  870. break;
  871. case SerializableProperty.FieldType.Color:
  872. {
  873. Color value = new Color();
  874. for (int i = 0; i < 4; i++)
  875. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  876. fieldValue.value = value;
  877. }
  878. break;
  879. case SerializableProperty.FieldType.Bool:
  880. case SerializableProperty.FieldType.Int:
  881. case SerializableProperty.FieldType.Float:
  882. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  883. break;
  884. }
  885. values.Add(fieldValue);
  886. }
  887. guiFieldDisplay.SetDisplayValues(values.ToArray());
  888. }
  889. /// <summary>
  890. /// Returns a list of all animation curves that should be displayed in the curve display.
  891. /// </summary>
  892. /// <returns>Array of curves to display.</returns>
  893. private EdCurveDrawInfo[] GetDisplayedCurves()
  894. {
  895. List<EdCurveDrawInfo> curvesToDisplay = new List<EdCurveDrawInfo>();
  896. if (clipInfo == null)
  897. return curvesToDisplay.ToArray();
  898. for (int i = 0; i < selectedFields.Count; i++)
  899. {
  900. EdCurveDrawInfo[] curveInfos;
  901. if (TryGetCurve(selectedFields[i], out curveInfos))
  902. curvesToDisplay.AddRange(curveInfos);
  903. }
  904. return curvesToDisplay.ToArray();
  905. }
  906. /// <summary>
  907. /// Calculates an unique color for each animation curve.
  908. /// </summary>
  909. private void UpdateCurveColors()
  910. {
  911. int globalCurveIdx = 0;
  912. foreach (var curveGroup in clipInfo.curves)
  913. {
  914. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  915. curveGroup.Value.curveInfos[i].color = EditorAnimClipInfo.GetUniqueColor(globalCurveIdx++);
  916. }
  917. }
  918. /// <summary>
  919. /// Updates the curve display with currently selected curves.
  920. /// </summary>
  921. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  922. /// be kept as is.</param>
  923. private void UpdateDisplayedCurves(bool resetTime = false)
  924. {
  925. EdCurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  926. guiCurveEditor.SetCurves(curvesToDisplay);
  927. guiCurveEditor.CenterAndResize(resetTime);
  928. }
  929. #endregion
  930. #region Field display
  931. private List<string> selectedFields = new List<string>();
  932. /// <summary>
  933. /// Registers a new animation curve field.
  934. /// </summary>
  935. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  936. /// <param name="type">Type of the field (float, vector, etc.)</param>
  937. private void AddNewField(string path, SerializableProperty.FieldType type)
  938. {
  939. bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path);
  940. switch (type)
  941. {
  942. case SerializableProperty.FieldType.Vector4:
  943. {
  944. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  945. fieldCurves.type = type;
  946. fieldCurves.isPropertyCurve = isPropertyCurve;
  947. fieldCurves.curveInfos = new EdCurveDrawInfo[4];
  948. string[] subPaths = { ".x", ".y", ".z", ".w" };
  949. for (int i = 0; i < subPaths.Length; i++)
  950. {
  951. string subFieldPath = path + subPaths[i];
  952. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  953. selectedFields.Add(subFieldPath);
  954. }
  955. clipInfo.curves[path] = fieldCurves;
  956. }
  957. break;
  958. case SerializableProperty.FieldType.Vector3:
  959. {
  960. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  961. fieldCurves.type = type;
  962. fieldCurves.isPropertyCurve = isPropertyCurve;
  963. fieldCurves.curveInfos = new EdCurveDrawInfo[3];
  964. string[] subPaths = { ".x", ".y", ".z" };
  965. for (int i = 0; i < subPaths.Length; i++)
  966. {
  967. string subFieldPath = path + subPaths[i];
  968. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  969. selectedFields.Add(subFieldPath);
  970. }
  971. clipInfo.curves[path] = fieldCurves;
  972. }
  973. break;
  974. case SerializableProperty.FieldType.Vector2:
  975. {
  976. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  977. fieldCurves.type = type;
  978. fieldCurves.isPropertyCurve = isPropertyCurve;
  979. fieldCurves.curveInfos = new EdCurveDrawInfo[2];
  980. string[] subPaths = { ".x", ".y" };
  981. for (int i = 0; i < subPaths.Length; i++)
  982. {
  983. string subFieldPath = path + subPaths[i];
  984. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  985. selectedFields.Add(subFieldPath);
  986. }
  987. clipInfo.curves[path] = fieldCurves;
  988. }
  989. break;
  990. case SerializableProperty.FieldType.Color:
  991. {
  992. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  993. fieldCurves.type = type;
  994. fieldCurves.isPropertyCurve = isPropertyCurve;
  995. fieldCurves.curveInfos = new EdCurveDrawInfo[4];
  996. string[] subPaths = { ".r", ".g", ".b", ".a" };
  997. for (int i = 0; i < subPaths.Length; i++)
  998. {
  999. string subFieldPath = path + subPaths[i];
  1000. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1001. selectedFields.Add(subFieldPath);
  1002. }
  1003. clipInfo.curves[path] = fieldCurves;
  1004. }
  1005. break;
  1006. default: // Primitive type
  1007. {
  1008. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1009. fieldCurves.type = type;
  1010. fieldCurves.isPropertyCurve = isPropertyCurve;
  1011. fieldCurves.curveInfos = new EdCurveDrawInfo[1];
  1012. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  1013. selectedFields.Add(path);
  1014. clipInfo.curves[path] = fieldCurves;
  1015. }
  1016. break;
  1017. }
  1018. UpdateCurveColors();
  1019. UpdateDisplayedFields();
  1020. EditorApplication.SetProjectDirty();
  1021. UpdateDisplayedCurves();
  1022. }
  1023. /// <summary>
  1024. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  1025. /// </summary>
  1026. /// <param name="path">Path of the field to display.</param>
  1027. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  1028. /// only the provided field will be shown.</param>
  1029. private void SelectField(string path, bool additive)
  1030. {
  1031. if (!additive)
  1032. selectedFields.Clear();
  1033. if (!string.IsNullOrEmpty(path))
  1034. {
  1035. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  1036. selectedFields.Add(path);
  1037. }
  1038. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  1039. UpdateDisplayedCurves();
  1040. }
  1041. /// <summary>
  1042. /// Deletes all currently selecting fields, removing them their curves permanently.
  1043. /// </summary>
  1044. private void RemoveSelectedFields()
  1045. {
  1046. for (int i = 0; i < selectedFields.Count; i++)
  1047. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  1048. UpdateCurveColors();
  1049. UpdateDisplayedFields();
  1050. selectedFields.Clear();
  1051. EditorApplication.SetProjectDirty();
  1052. UpdateDisplayedCurves();
  1053. }
  1054. /// <summary>
  1055. /// Updates the GUI element displaying the current animation curve fields.
  1056. /// </summary>
  1057. private void UpdateDisplayedFields()
  1058. {
  1059. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  1060. foreach (var KVP in clipInfo.curves)
  1061. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value));
  1062. guiFieldDisplay.SetFields(existingFields.ToArray());
  1063. }
  1064. #endregion
  1065. #region Helpers
  1066. /// <summary>
  1067. /// Returns the size of the curve editor GUI element.
  1068. /// </summary>
  1069. /// <returns>Width/height of the curve editor, in pixels.</returns>
  1070. private Vector2I GetCurveEditorSize()
  1071. {
  1072. Vector2I output = new Vector2I();
  1073. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH);
  1074. output.y = Math.Max(0, Height - buttonLayoutHeight);
  1075. return output;
  1076. }
  1077. /// <summary>
  1078. /// Attempts to find a curve field at the specified path.
  1079. /// </summary>
  1080. /// <param name="path">Path of the curve field to look for.</param>
  1081. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  1082. /// if it is a complex type, like a vector).</param>
  1083. /// <returns>True if the curve field was found, false otherwise.</returns>
  1084. private bool TryGetCurve(string path, out EdCurveDrawInfo[] curveInfos)
  1085. {
  1086. int index = path.LastIndexOf(".");
  1087. string parentPath;
  1088. string subPathSuffix = null;
  1089. if (index == -1)
  1090. {
  1091. parentPath = path;
  1092. }
  1093. else
  1094. {
  1095. parentPath = path.Substring(0, index);
  1096. subPathSuffix = path.Substring(index, path.Length - index);
  1097. }
  1098. FieldAnimCurves fieldCurves;
  1099. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1100. {
  1101. if (!string.IsNullOrEmpty(subPathSuffix))
  1102. {
  1103. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1104. {
  1105. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1106. return true;
  1107. }
  1108. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1109. {
  1110. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1111. return true;
  1112. }
  1113. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1114. {
  1115. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1116. return true;
  1117. }
  1118. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1119. {
  1120. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1121. return true;
  1122. }
  1123. }
  1124. else
  1125. {
  1126. curveInfos = fieldCurves.curveInfos;
  1127. return true;
  1128. }
  1129. }
  1130. curveInfos = new EdCurveDrawInfo[0];
  1131. return false;
  1132. }
  1133. /// <summary>
  1134. /// Checks if one curve field path a parent of the other.
  1135. /// </summary>
  1136. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1137. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1138. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1139. private bool IsPathParent(string child, string parent)
  1140. {
  1141. string[] childEntries = child.Split('/', '.');
  1142. string[] parentEntries = parent.Split('/', '.');
  1143. if (parentEntries.Length >= child.Length)
  1144. return false;
  1145. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1146. for (int i = 0; i < compareLength; i++)
  1147. {
  1148. if (childEntries[i] != parentEntries[i])
  1149. return false;
  1150. }
  1151. return true;
  1152. }
  1153. /// <summary>
  1154. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1155. /// path.
  1156. /// </summary>
  1157. /// <param name="path">Path to check.</param>
  1158. /// <returns>Path without sub-elements.</returns>
  1159. private string GetSubPathParent(string path)
  1160. {
  1161. int index = path.LastIndexOf(".");
  1162. if (index == -1)
  1163. return path;
  1164. return path.Substring(0, index);
  1165. }
  1166. /// <summary>
  1167. /// Iterates over all components of a property and calls the provided action for every component with the current
  1168. /// value of the property. Only works with floating point (any dimension), integer, color and boolean property
  1169. /// types. Since reported values are always floating point booleans are encoded as -1.0f for false and 1.0f for
  1170. /// true, and integers are converted to floating point.
  1171. /// </summary>
  1172. /// <param name="property">Property whose components to iterate over.</param>
  1173. /// <param name="action">
  1174. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1175. /// and the sequential index of the component.
  1176. /// </param>
  1177. private void ForEachPropertyComponentGet(SerializableProperty property, Action<float, int> action)
  1178. {
  1179. switch (property.Type)
  1180. {
  1181. case SerializableProperty.FieldType.Vector2:
  1182. {
  1183. Vector2 value = property.GetValue<Vector2>();
  1184. for (int i = 0; i < 2; i++)
  1185. action(value[i], i);
  1186. }
  1187. break;
  1188. case SerializableProperty.FieldType.Vector3:
  1189. {
  1190. Vector3 value = property.GetValue<Vector3>();
  1191. for (int i = 0; i < 3; i++)
  1192. action(value[i], i);
  1193. }
  1194. break;
  1195. case SerializableProperty.FieldType.Vector4:
  1196. {
  1197. if (property.InternalType == typeof(Vector4))
  1198. {
  1199. Vector4 value = property.GetValue<Vector4>();
  1200. for (int i = 0; i < 4; i++)
  1201. action(value[i], i);
  1202. }
  1203. else if (property.InternalType == typeof(Quaternion))
  1204. {
  1205. Quaternion value = property.GetValue<Quaternion>();
  1206. for (int i = 0; i < 4; i++)
  1207. action(value[i], i);
  1208. }
  1209. }
  1210. break;
  1211. case SerializableProperty.FieldType.Color:
  1212. {
  1213. Color value = property.GetValue<Color>();
  1214. for (int i = 0; i < 4; i++)
  1215. action(value[i], i);
  1216. }
  1217. break;
  1218. case SerializableProperty.FieldType.Bool:
  1219. {
  1220. bool value = property.GetValue<bool>();
  1221. action(value ? 1.0f : -1.0f, 0);
  1222. }
  1223. break;
  1224. case SerializableProperty.FieldType.Int:
  1225. {
  1226. int value = property.GetValue<int>();
  1227. action(value, 0);
  1228. }
  1229. break;
  1230. case SerializableProperty.FieldType.Float:
  1231. {
  1232. float value = property.GetValue<float>();
  1233. action(value, 0);
  1234. }
  1235. break;
  1236. }
  1237. }
  1238. /// <summary>
  1239. /// Iterates over all components of a property, calls the provided action which returns a new value to be
  1240. /// assigned to the property component. Only works with floating point (any dimension), integer, color and boolean
  1241. /// property types. Since reported values are always floating point booleans are encoded as -1.0f for false and
  1242. /// 1.0f for true, and integers are converted to floating point.
  1243. /// </summary>
  1244. /// <param name="property">Property whose components to iterate over.</param>
  1245. /// <param name="action">
  1246. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1247. /// and the sequential index of the component.
  1248. /// </param>
  1249. private void ForEachPropertyComponentSet(SerializableProperty property, Func<int, float> action)
  1250. {
  1251. switch (property.Type)
  1252. {
  1253. case SerializableProperty.FieldType.Vector2:
  1254. {
  1255. Vector2 value = new Vector2();
  1256. for (int i = 0; i < 2; i++)
  1257. value[i] = action(i);
  1258. property.SetValue(value);
  1259. }
  1260. break;
  1261. case SerializableProperty.FieldType.Vector3:
  1262. {
  1263. Vector3 value = new Vector3();
  1264. for (int i = 0; i < 3; i++)
  1265. value[i] = action(i);
  1266. property.SetValue(value);
  1267. }
  1268. break;
  1269. case SerializableProperty.FieldType.Vector4:
  1270. {
  1271. if (property.InternalType == typeof(Vector4))
  1272. {
  1273. Vector4 value = new Vector4();
  1274. for (int i = 0; i < 4; i++)
  1275. value[i] = action(i);
  1276. property.SetValue(value);
  1277. }
  1278. else if (property.InternalType == typeof(Quaternion))
  1279. {
  1280. Quaternion value = new Quaternion();
  1281. for (int i = 0; i < 4; i++)
  1282. value[i] = action(i);
  1283. property.SetValue(value);
  1284. }
  1285. }
  1286. break;
  1287. case SerializableProperty.FieldType.Color:
  1288. {
  1289. Color value = new Color();
  1290. for (int i = 0; i < 4; i++)
  1291. value[i] = action(i);
  1292. property.SetValue(value);
  1293. }
  1294. break;
  1295. case SerializableProperty.FieldType.Bool:
  1296. {
  1297. bool value = action(0) > 0.0f ? true : false;
  1298. property.SetValue(value);
  1299. }
  1300. break;
  1301. case SerializableProperty.FieldType.Int:
  1302. {
  1303. int value = (int)action(0);
  1304. property.SetValue(value);
  1305. }
  1306. break;
  1307. case SerializableProperty.FieldType.Float:
  1308. {
  1309. float value = action(0);
  1310. property.SetValue(value);
  1311. }
  1312. break;
  1313. }
  1314. }
  1315. #endregion
  1316. #region Input callbacks
  1317. /// <summary>
  1318. /// Triggered when the user presses a mouse button.
  1319. /// </summary>
  1320. /// <param name="ev">Information about the mouse press event.</param>
  1321. private void OnPointerPressed(PointerEvent ev)
  1322. {
  1323. guiCurveEditor.OnPointerPressed(ev);
  1324. }
  1325. /// <summary>
  1326. /// Triggered when the user double clicks the left mouse button.
  1327. /// </summary>
  1328. /// <param name="ev">Information about the mouse event.</param>
  1329. private void OnPointerDoubleClicked(PointerEvent ev)
  1330. {
  1331. guiCurveEditor.OnPointerDoubleClicked(ev);
  1332. }
  1333. /// <summary>
  1334. /// Triggered when the user moves the mouse.
  1335. /// </summary>
  1336. /// <param name="ev">Information about the mouse move event.</param>
  1337. private void OnPointerMoved(PointerEvent ev)
  1338. {
  1339. guiCurveEditor.OnPointerMoved(ev);
  1340. }
  1341. /// <summary>
  1342. /// Triggered when the user releases a mouse button.
  1343. /// </summary>
  1344. /// <param name="ev">Information about the mouse release event.</param>
  1345. private void OnPointerReleased(PointerEvent ev)
  1346. {
  1347. guiCurveEditor.OnPointerReleased(ev);
  1348. }
  1349. /// <summary>
  1350. /// Triggered when the user releases a keyboard button.
  1351. /// </summary>
  1352. /// <param name="ev">Information about the keyboard release event.</param>
  1353. private void OnButtonUp(ButtonEvent ev)
  1354. {
  1355. guiCurveEditor.OnButtonUp(ev);
  1356. }
  1357. #endregion
  1358. #region General callbacks
  1359. /// <summary>
  1360. /// Triggered by the field selector, when user selects a new curve field.
  1361. /// </summary>
  1362. /// <param name="path">Path of the selected curve field.</param>
  1363. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1364. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1365. {
  1366. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1367. string pathNoRoot = path.TrimStart('/');
  1368. int separatorIdx = pathNoRoot.IndexOf("/");
  1369. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1370. return;
  1371. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1372. AddNewField(pathNoRoot, type);
  1373. RecordState(pathNoRoot, 0.0f);
  1374. ApplyClipChanges();
  1375. }
  1376. /// <summary>
  1377. /// Triggered when the user selects a new curve field.
  1378. /// </summary>
  1379. /// <param name="path">Path of the selected curve field.</param>
  1380. private void OnFieldSelected(string path)
  1381. {
  1382. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1383. SelectField(path, additive);
  1384. }
  1385. /// <summary>
  1386. /// Triggered when the user selects a new scene object or a resource.
  1387. /// </summary>
  1388. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1389. /// <param name="resourcePaths">Newly selected resources.</param>
  1390. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1391. {
  1392. // While recording allow other objects to be selected so the user can modify them
  1393. if (state == State.Recording)
  1394. return;
  1395. UpdateSelectedSO(false);
  1396. }
  1397. /// <summary>
  1398. /// Triggered when the user selects a new frame in the curve display.
  1399. /// </summary>
  1400. /// <param name="frameIdx">Index of the selected frame.</param>
  1401. private void OnFrameSelected(int frameIdx)
  1402. {
  1403. SetCurrentFrame(frameIdx);
  1404. PreviewFrame(currentFrameIdx);
  1405. // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
  1406. // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
  1407. // animation to be evaluated synchronously when PreviewFrame is called.
  1408. delayRecord = true;
  1409. }
  1410. /// <summary>
  1411. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1412. /// </summary>
  1413. private void OnEventsChanged()
  1414. {
  1415. clipInfo.events = guiCurveEditor.Events;
  1416. EditorApplication.SetProjectDirty();
  1417. }
  1418. #endregion
  1419. }
  1420. /// <summary>
  1421. /// Drop down window that displays options used by the animation window.
  1422. /// </summary>
  1423. [DefaultSize(100, 50)]
  1424. internal class AnimationOptions : DropDownWindow
  1425. {
  1426. /// <summary>
  1427. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1428. /// use.
  1429. /// </summary>
  1430. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1431. internal void Initialize(AnimationWindow parent)
  1432. {
  1433. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1434. fpsField.Value = parent.FPS;
  1435. fpsField.OnChanged += x => { parent.FPS = x; };
  1436. GUILayoutY vertLayout = GUI.AddLayoutY();
  1437. vertLayout.AddFlexibleSpace();
  1438. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1439. contentLayout.AddFlexibleSpace();
  1440. contentLayout.AddElement(fpsField);
  1441. contentLayout.AddFlexibleSpace();
  1442. vertLayout.AddFlexibleSpace();
  1443. }
  1444. }
  1445. /// <summary>
  1446. /// Raw data representing a single animation curve.
  1447. /// </summary>
  1448. class AnimationCurveState
  1449. {
  1450. public KeyFrame[] keyFrames;
  1451. public TangentMode[] tangentModes;
  1452. }
  1453. /// <summary>
  1454. /// Raw data representing a single animation clip state.
  1455. /// </summary>
  1456. class AnimationClipState
  1457. {
  1458. public Dictionary<string, AnimationCurveState[]> curves = new Dictionary<string, AnimationCurveState[]>();
  1459. public AnimationEvent[] events;
  1460. }
  1461. /// <summary>
  1462. /// Undo command used in the AnimationWindow.
  1463. /// </summary>
  1464. internal class AnimationUndo : UndoableCommand
  1465. {
  1466. private AnimationClipState prevClipState;
  1467. private AnimationClipState clipState;
  1468. public AnimationUndo(AnimationClipState prevClipState, AnimationClipState clipState)
  1469. {
  1470. this.prevClipState = prevClipState;
  1471. this.clipState = clipState;
  1472. }
  1473. /// <inheritdoc/>
  1474. protected override void Commit()
  1475. {
  1476. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1477. window?.ApplyClipState(clipState);
  1478. }
  1479. /// <inheritdoc/>
  1480. protected override void Revert()
  1481. {
  1482. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1483. window?.ApplyClipState(prevClipState);
  1484. }
  1485. }
  1486. /** @} */
  1487. }