2
0

AnimationWindow.cs 75 KB

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