AnimationWindow.cs 65 KB

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