AnimationWindow.cs 75 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. /// Initializes the currently selected scene object. This should be called whenever the selected scene object
  662. /// changes.
  663. /// </summary>
  664. private void InitializeSO()
  665. {
  666. if (selectedSO != null)
  667. soState = new SerializedSceneObject(selectedSO, true);
  668. }
  669. /// <summary>
  670. /// Clears a selected scene object. This must be called on every scene object <see cref="InitializeSO"/> has been called
  671. /// on, after operations on it are done.
  672. /// </summary>
  673. private void ClearSO()
  674. {
  675. if (selectedSO != null)
  676. {
  677. Animation animation = selectedSO.GetComponent<Animation>();
  678. if (animation != null)
  679. animation.EditorStop();
  680. }
  681. if (soState != null)
  682. {
  683. soState.Restore();
  684. soState = null;
  685. }
  686. }
  687. #endregion
  688. #region Undo/Redo
  689. private AnimationClipState currentClipState;
  690. /// <summary>
  691. /// Records current clip state for undo/redo purposes.
  692. /// </summary>
  693. internal void RecordClipState()
  694. {
  695. AnimationClipState clipState = CreateClipState();
  696. AnimationUndo undoCommand = new AnimationUndo(currentClipState, clipState);
  697. UndoRedo.RegisterCommand(undoCommand);
  698. currentClipState = clipState;
  699. }
  700. /// <summary>
  701. /// Records current clip state for undo/redo purposes.
  702. /// </summary>
  703. internal AnimationClipState CreateClipState()
  704. {
  705. AnimationClipState clipState = new AnimationClipState();
  706. clipState.events = new AnimationEvent[clipInfo.events.Length];
  707. for (int i = 0; i < clipState.events.Length; i++)
  708. clipState.events[i] = new AnimationEvent(clipInfo.events[i].name, clipInfo.events[i].time);
  709. foreach (var curveField in clipInfo.curves)
  710. {
  711. AnimationCurveState[] curveData = new AnimationCurveState[curveField.Value.curveInfos.Length];
  712. for (int i = 0; i < curveData.Length; i++)
  713. {
  714. curveData[i] = new AnimationCurveState();
  715. TangentMode[] tangentModes = curveField.Value.curveInfos[i].curve.TangentModes;
  716. int numTangentModes = tangentModes.Length;
  717. curveData[i].tangentModes = new TangentMode[numTangentModes];
  718. Array.Copy(tangentModes, curveData[i].tangentModes, numTangentModes);
  719. KeyFrame[] keyFrames = curveField.Value.curveInfos[i].curve.KeyFrames;
  720. int numKeyframes = keyFrames.Length;
  721. curveData[i].keyFrames = new KeyFrame[numKeyframes];
  722. Array.Copy(keyFrames, curveData[i].keyFrames, numKeyframes);
  723. }
  724. clipState.curves[curveField.Key] = curveData;
  725. }
  726. return clipState;
  727. }
  728. /// <summary>
  729. /// Updates the current animation fields from the keyframes and events in the provided state.
  730. /// </summary>
  731. /// <param name="animationClipState">Saved state of an animation clip.</param>
  732. internal void ApplyClipState(AnimationClipState animationClipState)
  733. {
  734. if (state == State.Empty)
  735. return;
  736. SwitchState(State.Normal);
  737. AnimationEvent[] events = animationClipState.events;
  738. clipInfo.events = new AnimationEvent[events.Length];
  739. for(int i = 0; i < events.Length; i++)
  740. clipInfo.events[i] = new AnimationEvent(events[i].name, events[i].time);
  741. foreach (var KVP in animationClipState.curves)
  742. {
  743. FieldAnimCurves fieldCurves;
  744. if (!clipInfo.curves.TryGetValue(KVP.Key, out fieldCurves))
  745. continue;
  746. for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
  747. {
  748. AnimationCurve curve = new AnimationCurve(KVP.Value[i].keyFrames);
  749. fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, KVP.Value[i].tangentModes);
  750. }
  751. clipInfo.curves[KVP.Key] = fieldCurves;
  752. }
  753. // Clear all keyframes from curves not in the stored state
  754. foreach (var currentKVP in clipInfo.curves)
  755. {
  756. bool found = false;
  757. foreach (var stateKVP in animationClipState.curves)
  758. {
  759. if (currentKVP.Key == stateKVP.Key)
  760. {
  761. found = true;
  762. break;
  763. }
  764. }
  765. if (found)
  766. continue;
  767. FieldAnimCurves fieldCurves = currentKVP.Value;
  768. for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
  769. {
  770. AnimationCurve curve = new AnimationCurve(new KeyFrame[0]);
  771. fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, new TangentMode[0]);
  772. }
  773. }
  774. currentClipState = animationClipState;
  775. UpdateDisplayedCurves();
  776. ApplyClipChanges();
  777. PreviewFrame(currentFrameIdx);
  778. EditorApplication.SetProjectDirty();
  779. }
  780. #endregion
  781. #region Record/Playback
  782. /// <summary>
  783. /// Possible states the animation window can be in.
  784. /// </summary>
  785. private enum State
  786. {
  787. Empty,
  788. Normal,
  789. Recording,
  790. Playback
  791. }
  792. private State state = State.Empty;
  793. private SerializedSceneObject soState;
  794. private bool delayRecord = false;
  795. /// <summary>
  796. /// Transitions the window into a different state. Caller must validate state transitions.
  797. /// </summary>
  798. /// <param name="state">New state to transition to.</param>
  799. private void SwitchState(State state)
  800. {
  801. switch (this.state)
  802. {
  803. case State.Normal:
  804. {
  805. switch (state)
  806. {
  807. case State.Playback:
  808. StartPlayback();
  809. break;
  810. case State.Recording:
  811. StartRecord();
  812. break;
  813. case State.Empty:
  814. ClearSO();
  815. break;
  816. }
  817. }
  818. break;
  819. case State.Playback:
  820. {
  821. switch (state)
  822. {
  823. case State.Normal:
  824. EndPlayback();
  825. PreviewFrame(currentFrameIdx);
  826. break;
  827. case State.Recording:
  828. EndPlayback();
  829. StartRecord();
  830. break;
  831. case State.Empty:
  832. EndPlayback();
  833. ClearSO();
  834. break;
  835. }
  836. }
  837. break;
  838. case State.Recording:
  839. {
  840. switch (state)
  841. {
  842. case State.Normal:
  843. EndRecord();
  844. PreviewFrame(currentFrameIdx);
  845. break;
  846. case State.Playback:
  847. EndRecord();
  848. StartPlayback();
  849. break;
  850. case State.Empty:
  851. EndRecord();
  852. ClearSO();
  853. break;
  854. }
  855. }
  856. break;
  857. case State.Empty:
  858. {
  859. switch (state)
  860. {
  861. case State.Normal:
  862. InitializeSO();
  863. PreviewFrame(currentFrameIdx);
  864. break;
  865. case State.Playback:
  866. InitializeSO();
  867. StartPlayback();
  868. break;
  869. case State.Recording:
  870. InitializeSO();
  871. StartRecord();
  872. break;
  873. }
  874. }
  875. break;
  876. }
  877. this.state = state;
  878. }
  879. /// <summary>
  880. /// Plays back the animation on the currently selected object.
  881. /// </summary>
  882. private void StartPlayback()
  883. {
  884. EditorAnimClipTangents unused;
  885. clipInfo.Apply(out unused);
  886. Animation animation = selectedSO.GetComponent<Animation>();
  887. if (animation != null && clipInfo.clip != null)
  888. {
  889. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  890. animation.EditorPlay(clipInfo.clip, time);
  891. }
  892. playButton.Value = true;
  893. }
  894. /// <summary>
  895. /// Ends playback started with <see cref="StartPlayback"/>
  896. /// </summary>
  897. private void EndPlayback()
  898. {
  899. PreviewFrame(currentFrameIdx);
  900. playButton.Value = false;
  901. }
  902. /// <summary>
  903. /// Updates the visible animation to display the provided frame.
  904. /// </summary>
  905. /// <param name="frameIdx">Index of the animation frame to display.</param>
  906. private void PreviewFrame(int frameIdx)
  907. {
  908. if (selectedSO == null)
  909. return;
  910. Animation animation = selectedSO.GetComponent<Animation>();
  911. if (animation != null && clipInfo.clip != null)
  912. {
  913. float time = guiCurveEditor.GetTimeForFrame(frameIdx);
  914. animation.EditorPlay(clipInfo.clip, time, true);
  915. }
  916. }
  917. /// <summary>
  918. /// Start recording modifications made to the selected scene object.
  919. /// </summary>
  920. private void StartRecord()
  921. {
  922. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  923. if (RecordState(time))
  924. {
  925. ApplyClipChanges();
  926. guiCurveEditor.Redraw();
  927. }
  928. recordButton.Value = true;
  929. }
  930. /// <summary>
  931. /// Stops recording modifications made to the selected scene object.
  932. /// </summary>
  933. private void EndRecord()
  934. {
  935. recordButton.Value = false;
  936. }
  937. /// <summary>
  938. /// Iterates over all curve path fields and records their current state. If the state differs from the current
  939. /// curve values, new keyframes are added.
  940. /// </summary>
  941. /// <param name="time">Time for which to record the state, in seconds.</param>
  942. /// <returns>True if any changes were recorded, false otherwise.</returns>
  943. private bool RecordState(float time)
  944. {
  945. Action<EdAnimationCurve, float, float> addOrUpdateKeyframe = (curve, keyTime, keyValue) =>
  946. {
  947. KeyFrame[] keyframes = curve.KeyFrames;
  948. int keyframeIdx = -1;
  949. for (int i = 0; i < keyframes.Length; i++)
  950. {
  951. if (MathEx.ApproxEquals(keyframes[i].time, time))
  952. {
  953. keyframeIdx = i;
  954. break;
  955. }
  956. }
  957. if (keyframeIdx != -1)
  958. curve.UpdateKeyframe(keyframeIdx, keyTime, keyValue);
  959. else
  960. curve.AddKeyframe(keyTime, keyValue);
  961. curve.Apply();
  962. };
  963. bool changesMade = false;
  964. foreach (var KVP in clipInfo.curves)
  965. {
  966. string suffix;
  967. SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
  968. if (property == null)
  969. continue;
  970. switch (KVP.Value.type)
  971. {
  972. case SerializableProperty.FieldType.Vector2:
  973. {
  974. Vector2 value = property.GetValue<Vector2>();
  975. for (int i = 0; i < 2; i++)
  976. {
  977. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  978. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  979. {
  980. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  981. changesMade = true;
  982. }
  983. }
  984. }
  985. break;
  986. case SerializableProperty.FieldType.Vector3:
  987. {
  988. Vector3 value = property.GetValue<Vector3>();
  989. for (int i = 0; i < 3; i++)
  990. {
  991. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  992. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  993. {
  994. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  995. changesMade = true;
  996. }
  997. }
  998. }
  999. break;
  1000. case SerializableProperty.FieldType.Vector4:
  1001. {
  1002. if (property.InternalType == typeof(Vector4))
  1003. {
  1004. Vector4 value = property.GetValue<Vector4>();
  1005. for (int i = 0; i < 4; i++)
  1006. {
  1007. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  1008. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  1009. {
  1010. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  1011. changesMade = true;
  1012. }
  1013. }
  1014. }
  1015. else if (property.InternalType == typeof(Quaternion))
  1016. {
  1017. Quaternion value = property.GetValue<Quaternion>();
  1018. for (int i = 0; i < 4; i++)
  1019. {
  1020. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  1021. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  1022. {
  1023. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  1024. changesMade = true;
  1025. }
  1026. }
  1027. }
  1028. }
  1029. break;
  1030. case SerializableProperty.FieldType.Color:
  1031. {
  1032. Color value = property.GetValue<Color>();
  1033. for (int i = 0; i < 4; i++)
  1034. {
  1035. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  1036. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  1037. {
  1038. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  1039. changesMade = true;
  1040. }
  1041. }
  1042. }
  1043. break;
  1044. case SerializableProperty.FieldType.Bool:
  1045. {
  1046. bool value = property.GetValue<bool>();
  1047. bool curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time) > 0.0f;
  1048. if (value != curveVal)
  1049. {
  1050. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value ? 1.0f : -1.0f);
  1051. changesMade = true;
  1052. }
  1053. }
  1054. break;
  1055. case SerializableProperty.FieldType.Int:
  1056. {
  1057. int value = property.GetValue<int>();
  1058. int curveVal = (int)KVP.Value.curveInfos[0].curve.Evaluate(time);
  1059. if (value != curveVal)
  1060. {
  1061. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value);
  1062. changesMade = true;
  1063. }
  1064. }
  1065. break;
  1066. case SerializableProperty.FieldType.Float:
  1067. {
  1068. float value = property.GetValue<float>();
  1069. float curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time);
  1070. if (!MathEx.ApproxEquals(value, curveVal, 0.001f))
  1071. {
  1072. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value);
  1073. changesMade = true;
  1074. }
  1075. }
  1076. break;
  1077. }
  1078. }
  1079. return changesMade;
  1080. }
  1081. #endregion
  1082. #region Curve display
  1083. private int currentFrameIdx;
  1084. private int fps = 1;
  1085. /// <summary>
  1086. /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
  1087. /// placed.
  1088. /// </summary>
  1089. internal int FPS
  1090. {
  1091. get { return fps; }
  1092. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  1093. }
  1094. /// <summary>
  1095. /// Changes the currently selected frame in the curve display.
  1096. /// </summary>
  1097. /// <param name="frameIdx">Index of the frame to select.</param>
  1098. private void SetCurrentFrame(int frameIdx)
  1099. {
  1100. currentFrameIdx = Math.Max(0, frameIdx);
  1101. frameInputField.Value = currentFrameIdx;
  1102. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  1103. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  1104. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  1105. foreach (var kvp in clipInfo.curves)
  1106. {
  1107. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  1108. fieldValue.path = kvp.Key;
  1109. switch (kvp.Value.type)
  1110. {
  1111. case SerializableProperty.FieldType.Vector2:
  1112. {
  1113. Vector2 value = new Vector2();
  1114. for (int i = 0; i < 2; i++)
  1115. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1116. fieldValue.value = value;
  1117. }
  1118. break;
  1119. case SerializableProperty.FieldType.Vector3:
  1120. {
  1121. Vector3 value = new Vector3();
  1122. for (int i = 0; i < 3; i++)
  1123. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1124. fieldValue.value = value;
  1125. }
  1126. break;
  1127. case SerializableProperty.FieldType.Vector4:
  1128. {
  1129. Vector4 value = new Vector4();
  1130. for (int i = 0; i < 4; i++)
  1131. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1132. fieldValue.value = value;
  1133. }
  1134. break;
  1135. case SerializableProperty.FieldType.Color:
  1136. {
  1137. Color value = new Color();
  1138. for (int i = 0; i < 4; i++)
  1139. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1140. fieldValue.value = value;
  1141. }
  1142. break;
  1143. case SerializableProperty.FieldType.Bool:
  1144. case SerializableProperty.FieldType.Int:
  1145. case SerializableProperty.FieldType.Float:
  1146. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  1147. break;
  1148. }
  1149. values.Add(fieldValue);
  1150. }
  1151. guiFieldDisplay.SetDisplayValues(values.ToArray());
  1152. }
  1153. /// <summary>
  1154. /// Returns a list of all animation curves that should be displayed in the curve display.
  1155. /// </summary>
  1156. /// <returns>Array of curves to display.</returns>
  1157. private CurveDrawInfo[] GetDisplayedCurves()
  1158. {
  1159. List<CurveDrawInfo> curvesToDisplay = new List<CurveDrawInfo>();
  1160. if (clipInfo == null)
  1161. return curvesToDisplay.ToArray();
  1162. for (int i = 0; i < selectedFields.Count; i++)
  1163. {
  1164. CurveDrawInfo[] curveInfos;
  1165. if (TryGetCurve(selectedFields[i], out curveInfos))
  1166. curvesToDisplay.AddRange(curveInfos);
  1167. }
  1168. return curvesToDisplay.ToArray();
  1169. }
  1170. /// <summary>
  1171. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1172. /// </summary>
  1173. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1174. private Vector2 GetOptimalRange()
  1175. {
  1176. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1177. float xRange;
  1178. float yRange;
  1179. CalculateRange(curvesToDisplay, out xRange, out yRange);
  1180. // Add padding to y range
  1181. yRange *= 1.05f;
  1182. // Don't allow zero range
  1183. if (xRange == 0.0f)
  1184. xRange = 60.0f;
  1185. if (yRange == 0.0f)
  1186. yRange = 10.0f;
  1187. return new Vector2(xRange, yRange);
  1188. }
  1189. /// <summary>
  1190. /// Calculates an unique color for each animation curve.
  1191. /// </summary>
  1192. private void UpdateCurveColors()
  1193. {
  1194. int globalCurveIdx = 0;
  1195. foreach (var curveGroup in clipInfo.curves)
  1196. {
  1197. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  1198. curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
  1199. }
  1200. }
  1201. /// <summary>
  1202. /// Updates the curve display with currently selected curves.
  1203. /// </summary>
  1204. /// <param name="allowReduce">Normally the curve display will expand if newly selected curves cover a larger area
  1205. /// than currently available, but the area won't be reduced if the selected curves cover
  1206. /// a smaller area. Set this to true to allow the area to be reduced.</param>
  1207. private void UpdateDisplayedCurves(bool allowReduce = false)
  1208. {
  1209. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1210. guiCurveEditor.SetCurves(curvesToDisplay);
  1211. Vector2 newRange = GetOptimalRange();
  1212. if (!allowReduce)
  1213. {
  1214. // Don't reduce visible range
  1215. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  1216. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  1217. }
  1218. guiCurveEditor.Range = newRange;
  1219. UpdateScrollBarSize();
  1220. }
  1221. #endregion
  1222. #region Field display
  1223. private List<string> selectedFields = new List<string>();
  1224. /// <summary>
  1225. /// Registers a new animation curve field.
  1226. /// </summary>
  1227. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  1228. /// <param name="type">Type of the field (float, vector, etc.)</param>
  1229. private void AddNewField(string path, SerializableProperty.FieldType type)
  1230. {
  1231. bool noSelection = selectedFields.Count == 0;
  1232. bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path);
  1233. switch (type)
  1234. {
  1235. case SerializableProperty.FieldType.Vector4:
  1236. {
  1237. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1238. fieldCurves.type = type;
  1239. fieldCurves.isPropertyCurve = isPropertyCurve;
  1240. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1241. string[] subPaths = { ".x", ".y", ".z", ".w" };
  1242. for (int i = 0; i < subPaths.Length; i++)
  1243. {
  1244. string subFieldPath = path + subPaths[i];
  1245. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1246. selectedFields.Add(subFieldPath);
  1247. }
  1248. clipInfo.curves[path] = fieldCurves;
  1249. }
  1250. break;
  1251. case SerializableProperty.FieldType.Vector3:
  1252. {
  1253. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1254. fieldCurves.type = type;
  1255. fieldCurves.isPropertyCurve = isPropertyCurve;
  1256. fieldCurves.curveInfos = new CurveDrawInfo[3];
  1257. string[] subPaths = { ".x", ".y", ".z" };
  1258. for (int i = 0; i < subPaths.Length; i++)
  1259. {
  1260. string subFieldPath = path + subPaths[i];
  1261. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1262. selectedFields.Add(subFieldPath);
  1263. }
  1264. clipInfo.curves[path] = fieldCurves;
  1265. }
  1266. break;
  1267. case SerializableProperty.FieldType.Vector2:
  1268. {
  1269. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1270. fieldCurves.type = type;
  1271. fieldCurves.isPropertyCurve = isPropertyCurve;
  1272. fieldCurves.curveInfos = new CurveDrawInfo[2];
  1273. string[] subPaths = { ".x", ".y" };
  1274. for (int i = 0; i < subPaths.Length; i++)
  1275. {
  1276. string subFieldPath = path + subPaths[i];
  1277. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1278. selectedFields.Add(subFieldPath);
  1279. }
  1280. clipInfo.curves[path] = fieldCurves;
  1281. }
  1282. break;
  1283. case SerializableProperty.FieldType.Color:
  1284. {
  1285. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1286. fieldCurves.type = type;
  1287. fieldCurves.isPropertyCurve = isPropertyCurve;
  1288. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1289. string[] subPaths = { ".r", ".g", ".b", ".a" };
  1290. for (int i = 0; i < subPaths.Length; i++)
  1291. {
  1292. string subFieldPath = path + subPaths[i];
  1293. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1294. selectedFields.Add(subFieldPath);
  1295. }
  1296. clipInfo.curves[path] = fieldCurves;
  1297. }
  1298. break;
  1299. default: // Primitive type
  1300. {
  1301. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1302. fieldCurves.type = type;
  1303. fieldCurves.isPropertyCurve = isPropertyCurve;
  1304. fieldCurves.curveInfos = new CurveDrawInfo[1];
  1305. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  1306. selectedFields.Add(path);
  1307. clipInfo.curves[path] = fieldCurves;
  1308. }
  1309. break;
  1310. }
  1311. UpdateCurveColors();
  1312. UpdateDisplayedFields();
  1313. EditorApplication.SetProjectDirty();
  1314. UpdateDisplayedCurves(noSelection);
  1315. }
  1316. /// <summary>
  1317. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  1318. /// </summary>
  1319. /// <param name="path">Path of the field to display.</param>
  1320. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  1321. /// only the provided field will be shown.</param>
  1322. private void SelectField(string path, bool additive)
  1323. {
  1324. if (!additive)
  1325. selectedFields.Clear();
  1326. bool noSelection = selectedFields.Count == 0;
  1327. if (!string.IsNullOrEmpty(path))
  1328. {
  1329. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  1330. selectedFields.Add(path);
  1331. }
  1332. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  1333. UpdateDisplayedCurves(noSelection);
  1334. }
  1335. /// <summary>
  1336. /// Deletes all currently selecting fields, removing them their curves permanently.
  1337. /// </summary>
  1338. private void RemoveSelectedFields()
  1339. {
  1340. for (int i = 0; i < selectedFields.Count; i++)
  1341. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  1342. UpdateCurveColors();
  1343. UpdateDisplayedFields();
  1344. selectedFields.Clear();
  1345. EditorApplication.SetProjectDirty();
  1346. UpdateDisplayedCurves();
  1347. }
  1348. /// <summary>
  1349. /// Updates the GUI element displaying the current animation curve fields.
  1350. /// </summary>
  1351. private void UpdateDisplayedFields()
  1352. {
  1353. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  1354. foreach (var KVP in clipInfo.curves)
  1355. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value));
  1356. guiFieldDisplay.SetFields(existingFields.ToArray());
  1357. }
  1358. #endregion
  1359. #region Helpers
  1360. /// <summary>
  1361. /// Returns the size of the curve editor GUI element.
  1362. /// </summary>
  1363. /// <returns>Width/height of the curve editor, in pixels.</returns>
  1364. private Vector2I GetCurveEditorSize()
  1365. {
  1366. Vector2I output = new Vector2I();
  1367. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  1368. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  1369. return output;
  1370. }
  1371. /// <summary>
  1372. /// Calculates the total range covered by a set of curves.
  1373. /// </summary>
  1374. /// <param name="curveInfos">Curves to calculate range for.</param>
  1375. /// <param name="xRange">Maximum time value present in the curves.</param>
  1376. /// <param name="yRange">Maximum absolute curve value present in the curves.</param>
  1377. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xRange, out float yRange)
  1378. {
  1379. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  1380. // tangents
  1381. xRange = 0.0f;
  1382. yRange = 0.0f;
  1383. foreach (var curveInfo in curveInfos)
  1384. {
  1385. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  1386. foreach (var key in keyframes)
  1387. {
  1388. xRange = Math.Max(xRange, key.time);
  1389. yRange = Math.Max(yRange, Math.Abs(key.value));
  1390. }
  1391. }
  1392. }
  1393. /// <summary>
  1394. /// Attempts to find a curve field at the specified path.
  1395. /// </summary>
  1396. /// <param name="path">Path of the curve field to look for.</param>
  1397. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  1398. /// if it is a complex type, like a vector).</param>
  1399. /// <returns>True if the curve field was found, false otherwise.</returns>
  1400. private bool TryGetCurve(string path, out CurveDrawInfo[] curveInfos)
  1401. {
  1402. int index = path.LastIndexOf(".");
  1403. string parentPath;
  1404. string subPathSuffix = null;
  1405. if (index == -1)
  1406. {
  1407. parentPath = path;
  1408. }
  1409. else
  1410. {
  1411. parentPath = path.Substring(0, index);
  1412. subPathSuffix = path.Substring(index, path.Length - index);
  1413. }
  1414. FieldAnimCurves fieldCurves;
  1415. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1416. {
  1417. if (!string.IsNullOrEmpty(subPathSuffix))
  1418. {
  1419. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1420. {
  1421. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1422. return true;
  1423. }
  1424. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1425. {
  1426. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1427. return true;
  1428. }
  1429. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1430. {
  1431. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1432. return true;
  1433. }
  1434. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1435. {
  1436. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1437. return true;
  1438. }
  1439. }
  1440. else
  1441. {
  1442. curveInfos = fieldCurves.curveInfos;
  1443. return true;
  1444. }
  1445. }
  1446. curveInfos = new CurveDrawInfo[0];
  1447. return false;
  1448. }
  1449. /// <summary>
  1450. /// Checks if one curve field path a parent of the other.
  1451. /// </summary>
  1452. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1453. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1454. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1455. private bool IsPathParent(string child, string parent)
  1456. {
  1457. string[] childEntries = child.Split('/', '.');
  1458. string[] parentEntries = parent.Split('/', '.');
  1459. if (parentEntries.Length >= child.Length)
  1460. return false;
  1461. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1462. for (int i = 0; i < compareLength; i++)
  1463. {
  1464. if (childEntries[i] != parentEntries[i])
  1465. return false;
  1466. }
  1467. return true;
  1468. }
  1469. /// <summary>
  1470. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1471. /// path.
  1472. /// </summary>
  1473. /// <param name="path">Path to check.</param>
  1474. /// <returns>Path without sub-elements.</returns>
  1475. private string GetSubPathParent(string path)
  1476. {
  1477. int index = path.LastIndexOf(".");
  1478. if (index == -1)
  1479. return path;
  1480. return path.Substring(0, index);
  1481. }
  1482. #endregion
  1483. #region Input callbacks
  1484. /// <summary>
  1485. /// Triggered when the user presses a mouse button.
  1486. /// </summary>
  1487. /// <param name="ev">Information about the mouse press event.</param>
  1488. private void OnPointerPressed(PointerEvent ev)
  1489. {
  1490. guiCurveEditor.OnPointerPressed(ev);
  1491. if (ev.button == PointerButton.Middle)
  1492. {
  1493. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1494. Vector2 curvePos;
  1495. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  1496. {
  1497. dragStartPos = windowPos;
  1498. isButtonHeld = true;
  1499. }
  1500. }
  1501. }
  1502. /// <summary>
  1503. /// Triggered when the user moves the mouse.
  1504. /// </summary>
  1505. /// <param name="ev">Information about the mouse move event.</param>
  1506. private void OnPointerMoved(PointerEvent ev)
  1507. {
  1508. guiCurveEditor.OnPointerMoved(ev);
  1509. if (isButtonHeld)
  1510. {
  1511. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1512. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1513. if (distance >= DRAG_START_DISTANCE)
  1514. {
  1515. isDragInProgress = true;
  1516. Cursor.Hide();
  1517. Rect2I clipRect;
  1518. clipRect.x = ev.ScreenPos.x - 2;
  1519. clipRect.y = ev.ScreenPos.y - 2;
  1520. clipRect.width = 4;
  1521. clipRect.height = 4;
  1522. Cursor.ClipToRect(clipRect);
  1523. }
  1524. }
  1525. }
  1526. /// <summary>
  1527. /// Triggered when the user releases a mouse button.
  1528. /// </summary>
  1529. /// <param name="ev">Information about the mouse release event.</param>
  1530. private void OnPointerReleased(PointerEvent ev)
  1531. {
  1532. if (isDragInProgress)
  1533. {
  1534. Cursor.Show();
  1535. Cursor.ClipDisable();
  1536. }
  1537. isButtonHeld = false;
  1538. isDragInProgress = false;
  1539. guiCurveEditor.OnPointerReleased(ev);
  1540. }
  1541. /// <summary>
  1542. /// Triggered when the user releases a keyboard button.
  1543. /// </summary>
  1544. /// <param name="ev">Information about the keyboard release event.</param>
  1545. private void OnButtonUp(ButtonEvent ev)
  1546. {
  1547. guiCurveEditor.OnButtonUp(ev);
  1548. }
  1549. #endregion
  1550. #region General callbacks
  1551. /// <summary>
  1552. /// Triggered by the field selector, when user selects a new curve field.
  1553. /// </summary>
  1554. /// <param name="path">Path of the selected curve field.</param>
  1555. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1556. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1557. {
  1558. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1559. string pathNoRoot = path.TrimStart('/');
  1560. int separatorIdx = pathNoRoot.IndexOf("/");
  1561. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1562. return;
  1563. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1564. AddNewField(pathNoRoot, type);
  1565. ApplyClipChanges();
  1566. }
  1567. /// <summary>
  1568. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1569. /// </summary>
  1570. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1571. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1572. private void OnHorzScrollOrResize(float position, float size)
  1573. {
  1574. SetHorzScrollbarProperties(position, size);
  1575. }
  1576. /// <summary>
  1577. /// Triggered when the user moves or resizes the vertical scrollbar.
  1578. /// </summary>
  1579. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1580. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1581. private void OnVertScrollOrResize(float position, float size)
  1582. {
  1583. SetVertScrollbarProperties(position, size);
  1584. }
  1585. /// <summary>
  1586. /// Triggered when the user selects a new curve field.
  1587. /// </summary>
  1588. /// <param name="path">Path of the selected curve field.</param>
  1589. private void OnFieldSelected(string path)
  1590. {
  1591. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1592. SelectField(path, additive);
  1593. }
  1594. /// <summary>
  1595. /// Triggered when the user selects a new scene object or a resource.
  1596. /// </summary>
  1597. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1598. /// <param name="resourcePaths">Newly selected resources.</param>
  1599. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1600. {
  1601. // While recording allow other objects to be selected so the user can modify them
  1602. if (state == State.Recording)
  1603. return;
  1604. UpdateSelectedSO(false);
  1605. }
  1606. /// <summary>
  1607. /// Triggered when the user selects a new frame in the curve display.
  1608. /// </summary>
  1609. /// <param name="frameIdx">Index of the selected frame.</param>
  1610. private void OnFrameSelected(int frameIdx)
  1611. {
  1612. SetCurrentFrame(frameIdx);
  1613. PreviewFrame(currentFrameIdx);
  1614. // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
  1615. // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
  1616. // animation to be evaluated synchronously when PreviewFrame is called.
  1617. delayRecord = true;
  1618. }
  1619. /// <summary>
  1620. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1621. /// </summary>
  1622. private void OnEventsChanged()
  1623. {
  1624. clipInfo.events = guiCurveEditor.Events;
  1625. EditorApplication.SetProjectDirty();
  1626. }
  1627. #endregion
  1628. }
  1629. /// <summary>
  1630. /// Drop down window that displays options used by the animation window.
  1631. /// </summary>
  1632. [DefaultSize(100, 50)]
  1633. internal class AnimationOptions : DropDownWindow
  1634. {
  1635. /// <summary>
  1636. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1637. /// use.
  1638. /// </summary>
  1639. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1640. internal void Initialize(AnimationWindow parent)
  1641. {
  1642. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1643. fpsField.Value = parent.FPS;
  1644. fpsField.OnChanged += x => { parent.FPS = x; };
  1645. GUILayoutY vertLayout = GUI.AddLayoutY();
  1646. vertLayout.AddFlexibleSpace();
  1647. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1648. contentLayout.AddFlexibleSpace();
  1649. contentLayout.AddElement(fpsField);
  1650. contentLayout.AddFlexibleSpace();
  1651. vertLayout.AddFlexibleSpace();
  1652. }
  1653. }
  1654. /// <summary>
  1655. /// Raw data representing a single animation curve.
  1656. /// </summary>
  1657. class AnimationCurveState
  1658. {
  1659. public KeyFrame[] keyFrames;
  1660. public TangentMode[] tangentModes;
  1661. }
  1662. /// <summary>
  1663. /// Raw data representing a single animation clip state.
  1664. /// </summary>
  1665. class AnimationClipState
  1666. {
  1667. public Dictionary<string, AnimationCurveState[]> curves = new Dictionary<string, AnimationCurveState[]>();
  1668. public AnimationEvent[] events;
  1669. }
  1670. /// <summary>
  1671. /// Undo command used in the AnimationWindow.
  1672. /// </summary>
  1673. internal class AnimationUndo : UndoableCommand
  1674. {
  1675. private AnimationClipState prevClipState;
  1676. private AnimationClipState clipState;
  1677. public AnimationUndo(AnimationClipState prevClipState, AnimationClipState clipState)
  1678. {
  1679. this.prevClipState = prevClipState;
  1680. this.clipState = clipState;
  1681. }
  1682. /// <inheritdoc/>
  1683. protected override void Commit()
  1684. {
  1685. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1686. window?.ApplyClipState(clipState);
  1687. }
  1688. /// <inheritdoc/>
  1689. protected override void Revert()
  1690. {
  1691. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1692. window?.ApplyClipState(prevClipState);
  1693. }
  1694. }
  1695. /** @} */
  1696. }