AnimationWindow.cs 74 KB

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