AnimationWindow.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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.Text;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /** @addtogroup Windows
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays animation curve editor window.
  14. /// </summary>
  15. [DefaultSize(900, 500)]
  16. internal class AnimationWindow : EditorWindow
  17. {
  18. private const int FIELD_DISPLAY_WIDTH = 300;
  19. private const int DRAG_START_DISTANCE = 3;
  20. private const float DRAG_SCALE = 3.0f;
  21. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  22. private SceneObject selectedSO;
  23. /// <summary>
  24. /// Scene object for which are we currently changing the animation for.
  25. /// </summary>
  26. internal SceneObject SelectedSO
  27. {
  28. get { return selectedSO; }
  29. }
  30. #region Overrides
  31. /// <summary>
  32. /// Opens the animation window.
  33. /// </summary>
  34. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  35. private static void OpenGameWindow()
  36. {
  37. OpenWindow<AnimationWindow>();
  38. }
  39. /// <inheritdoc/>
  40. protected override LocString GetDisplayName()
  41. {
  42. return new LocEdString("Animation");
  43. }
  44. private void OnInitialize()
  45. {
  46. Selection.OnSelectionChanged += OnSelectionChanged;
  47. UpdateSelectedSO(true);
  48. }
  49. private void OnEditorUpdate()
  50. {
  51. if (selectedSO == null)
  52. return;
  53. HandleDragAndZoomInput();
  54. }
  55. private void OnDestroy()
  56. {
  57. Selection.OnSelectionChanged -= OnSelectionChanged;
  58. if (selectedSO != null)
  59. {
  60. EditorInput.OnPointerPressed -= OnPointerPressed;
  61. EditorInput.OnPointerMoved -= OnPointerMoved;
  62. EditorInput.OnPointerReleased -= OnPointerReleased;
  63. EditorInput.OnButtonUp -= OnButtonUp;
  64. }
  65. }
  66. protected override void WindowResized(int width, int height)
  67. {
  68. if (selectedSO == null)
  69. return;
  70. ResizeGUI(width, height);
  71. }
  72. #endregion
  73. #region GUI
  74. private GUIButton playButton;
  75. private GUIButton recordButton;
  76. private GUIButton prevFrameButton;
  77. private GUIIntField frameInputField;
  78. private GUIButton nextFrameButton;
  79. private GUIButton addKeyframeButton;
  80. private GUIButton addEventButton;
  81. private GUIButton optionsButton;
  82. private GUIButton addPropertyBtn;
  83. private GUIButton delPropertyBtn;
  84. private GUILayout buttonLayout;
  85. private int buttonLayoutHeight;
  86. private int scrollBarWidth;
  87. private int scrollBarHeight;
  88. private GUIResizeableScrollBarH horzScrollBar;
  89. private GUIResizeableScrollBarV vertScrollBar;
  90. private GUIPanel editorPanel;
  91. private GUIAnimFieldDisplay guiFieldDisplay;
  92. private GUICurveEditor guiCurveEditor;
  93. private void RebuildGUI()
  94. {
  95. GUI.Clear();
  96. guiCurveEditor = null;
  97. guiFieldDisplay = null;
  98. if (selectedSO == null)
  99. {
  100. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  101. GUILayoutY vertLayout = GUI.AddLayoutY();
  102. vertLayout.AddFlexibleSpace();
  103. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  104. vertLayout.AddFlexibleSpace();
  105. horzLayout.AddFlexibleSpace();
  106. horzLayout.AddElement(warningLbl);
  107. horzLayout.AddFlexibleSpace();
  108. return;
  109. }
  110. // Top button row
  111. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  112. new LocEdString("Play"));
  113. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  114. new LocEdString("Record"));
  115. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  116. new LocEdString("Previous frame"));
  117. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  118. new LocEdString("Next frame"));
  119. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  120. new LocEdString("Add keyframe"));
  121. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  122. new LocEdString("Add event"));
  123. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  124. new LocEdString("Options"));
  125. playButton = new GUIButton(playIcon);
  126. recordButton = new GUIButton(recordIcon);
  127. prevFrameButton = new GUIButton(prevFrameIcon);
  128. frameInputField = new GUIIntField();
  129. nextFrameButton = new GUIButton(nextFrameIcon);
  130. addKeyframeButton = new GUIButton(addKeyframeIcon);
  131. addEventButton = new GUIButton(addEventIcon);
  132. optionsButton = new GUIButton(optionsIcon);
  133. playButton.OnClick += () =>
  134. {
  135. // TODO
  136. // - Record current state of the scene object hierarchy
  137. // - Evaluate all curves manually and update them
  138. // - On end, restore original values of the scene object hierarchy
  139. };
  140. recordButton.OnClick += () =>
  141. {
  142. // TODO
  143. // - Every frame read back current values of all the current curve's properties and assign it to the current frame
  144. };
  145. prevFrameButton.OnClick += () =>
  146. {
  147. SetCurrentFrame(currentFrameIdx - 1);
  148. };
  149. frameInputField.OnChanged += SetCurrentFrame;
  150. nextFrameButton.OnClick += () =>
  151. {
  152. SetCurrentFrame(currentFrameIdx + 1);
  153. };
  154. addKeyframeButton.OnClick += () =>
  155. {
  156. guiCurveEditor.AddKeyFrameAtMarker();
  157. };
  158. addEventButton.OnClick += () =>
  159. {
  160. guiCurveEditor.AddEventAtMarker();
  161. };
  162. optionsButton.OnClick += () =>
  163. {
  164. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  165. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
  166. dropDown.Initialize(this);
  167. };
  168. // Property buttons
  169. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  170. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  171. addPropertyBtn.OnClick += () =>
  172. {
  173. Action openPropertyWindow = () =>
  174. {
  175. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  176. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
  177. fieldSelection.OnFieldSelected += OnFieldAdded;
  178. };
  179. if (clipInfo.clip == null)
  180. {
  181. LocEdString title = new LocEdString("Warning");
  182. LocEdString message =
  183. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  184. " a new animation clip?");
  185. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  186. {
  187. if (type == DialogBox.ResultType.Yes)
  188. {
  189. string[] clipSavePaths;
  190. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out clipSavePaths))
  191. {
  192. if (clipSavePaths.Length > 0)
  193. {
  194. AnimationClip newClip = new AnimationClip();
  195. ProjectLibrary.Create(newClip, clipSavePaths[0]);
  196. LoadAnimClip(newClip);
  197. Animation animation = selectedSO.GetComponent<Animation>();
  198. if (animation == null)
  199. animation = selectedSO.AddComponent<Animation>();
  200. animation.DefaultClip = newClip;
  201. EditorApplication.SetSceneDirty();
  202. openPropertyWindow();
  203. }
  204. }
  205. }
  206. });
  207. }
  208. else
  209. {
  210. if (clipInfo.isImported)
  211. {
  212. LocEdString title = new LocEdString("Warning");
  213. LocEdString message =
  214. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  215. " are imported from an external file.");
  216. DialogBox.Open(title, message, DialogBox.Type.OK);
  217. }
  218. else
  219. openPropertyWindow();
  220. }
  221. };
  222. delPropertyBtn.OnClick += () =>
  223. {
  224. if (clipInfo.clip == null)
  225. return;
  226. if (clipInfo.isImported)
  227. {
  228. LocEdString title = new LocEdString("Warning");
  229. LocEdString message =
  230. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  231. " are imported from an external file.");
  232. DialogBox.Open(title, message, DialogBox.Type.OK);
  233. }
  234. else
  235. {
  236. LocEdString title = new LocEdString("Warning");
  237. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  238. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  239. {
  240. if (x == DialogBox.ResultType.Yes)
  241. {
  242. RemoveSelectedFields();
  243. }
  244. });
  245. }
  246. };
  247. GUILayout mainLayout = GUI.AddLayoutY();
  248. buttonLayout = mainLayout.AddLayoutX();
  249. buttonLayout.AddSpace(5);
  250. buttonLayout.AddElement(playButton);
  251. buttonLayout.AddElement(recordButton);
  252. buttonLayout.AddSpace(5);
  253. buttonLayout.AddElement(prevFrameButton);
  254. buttonLayout.AddElement(frameInputField);
  255. buttonLayout.AddElement(nextFrameButton);
  256. buttonLayout.AddSpace(5);
  257. buttonLayout.AddElement(addKeyframeButton);
  258. buttonLayout.AddElement(addEventButton);
  259. buttonLayout.AddSpace(5);
  260. buttonLayout.AddElement(optionsButton);
  261. buttonLayout.AddFlexibleSpace();
  262. buttonLayoutHeight = playButton.Bounds.height;
  263. GUILayout contentLayout = mainLayout.AddLayoutX();
  264. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  265. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  266. Height - buttonLayoutHeight * 2, selectedSO);
  267. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  268. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  269. bottomButtonLayout.AddElement(addPropertyBtn);
  270. bottomButtonLayout.AddElement(delPropertyBtn);
  271. horzScrollBar = new GUIResizeableScrollBarH();
  272. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  273. vertScrollBar = new GUIResizeableScrollBarV();
  274. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  275. GUILayout curveLayout = contentLayout.AddLayoutY();
  276. GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
  277. GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
  278. horzScrollBarLayout.AddElement(horzScrollBar);
  279. horzScrollBarLayout.AddFlexibleSpace();
  280. editorPanel = curveLayoutHorz.AddPanel();
  281. curveLayoutHorz.AddElement(vertScrollBar);
  282. curveLayoutHorz.AddFlexibleSpace();
  283. scrollBarHeight = horzScrollBar.Bounds.height;
  284. scrollBarWidth = vertScrollBar.Bounds.width;
  285. Vector2I curveEditorSize = GetCurveEditorSize();
  286. guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
  287. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  288. guiCurveEditor.OnEventAdded += OnEventsChanged;
  289. guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
  290. guiCurveEditor.OnEventDeleted += OnEventsChanged;
  291. guiCurveEditor.OnCurveModified += EditorApplication.SetProjectDirty;
  292. guiCurveEditor.Redraw();
  293. horzScrollBar.SetWidth(curveEditorSize.x);
  294. vertScrollBar.SetHeight(curveEditorSize.y);
  295. UpdateScrollBarSize();
  296. }
  297. private void ResizeGUI(int width, int height)
  298. {
  299. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  300. Vector2I curveEditorSize = GetCurveEditorSize();
  301. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  302. guiCurveEditor.Redraw();
  303. horzScrollBar.SetWidth(curveEditorSize.x);
  304. vertScrollBar.SetHeight(curveEditorSize.y);
  305. UpdateScrollBarSize();
  306. UpdateScrollBarPosition();
  307. }
  308. #endregion
  309. #region Scroll, drag, zoom
  310. private Vector2I dragStartPos;
  311. private bool isButtonHeld;
  312. private bool isDragInProgress;
  313. private float zoomAmount;
  314. private void HandleDragAndZoomInput()
  315. {
  316. // Handle middle mouse dragging
  317. if (isDragInProgress)
  318. {
  319. float lengthPerPixel = guiCurveEditor.Range.x / guiCurveEditor.Width;
  320. float heightPerPixel = guiCurveEditor.Range.y / guiCurveEditor.Height;
  321. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  322. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  323. Vector2 offset = guiCurveEditor.Offset;
  324. offset.x = Math.Max(0.0f, offset.x + dragX);
  325. offset.y -= dragY;
  326. guiCurveEditor.Offset = offset;
  327. UpdateScrollBarSize();
  328. UpdateScrollBarPosition();
  329. }
  330. // Handle zoom in/out
  331. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  332. if (scroll != 0.0f)
  333. {
  334. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  335. Vector2 curvePos;
  336. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  337. {
  338. float zoom = scroll * ZOOM_SCALE;
  339. Zoom(curvePos, zoom);
  340. }
  341. }
  342. }
  343. private void SetVertScrollbarProperties(float position, float size)
  344. {
  345. Vector2 visibleRange = guiCurveEditor.Range;
  346. Vector2 totalRange = GetTotalRange();
  347. visibleRange.y = totalRange.y*size;
  348. guiCurveEditor.Range = visibleRange;
  349. float scrollableRange = totalRange.y - visibleRange.y;
  350. Vector2 offset = guiCurveEditor.Offset;
  351. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  352. guiCurveEditor.Offset = offset;
  353. }
  354. private void SetHorzScrollbarProperties(float position, float size)
  355. {
  356. Vector2 visibleRange = guiCurveEditor.Range;
  357. Vector2 totalRange = GetTotalRange();
  358. visibleRange.x = totalRange.x * size;
  359. guiCurveEditor.Range = visibleRange;
  360. float scrollableRange = totalRange.x - visibleRange.x;
  361. Vector2 offset = guiCurveEditor.Offset;
  362. offset.x = scrollableRange * position;
  363. guiCurveEditor.Offset = offset;
  364. }
  365. private void UpdateScrollBarSize()
  366. {
  367. Vector2 visibleRange = guiCurveEditor.Range;
  368. Vector2 totalRange = GetTotalRange();
  369. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  370. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  371. }
  372. private void UpdateScrollBarPosition()
  373. {
  374. Vector2 visibleRange = guiCurveEditor.Range;
  375. Vector2 totalRange = GetTotalRange();
  376. Vector2 scrollableRange = totalRange - visibleRange;
  377. Vector2 offset = guiCurveEditor.Offset;
  378. if (scrollableRange.x > 0.0f)
  379. horzScrollBar.Position = offset.x / scrollableRange.x;
  380. else
  381. horzScrollBar.Position = 0.0f;
  382. if (scrollableRange.y > 0.0f)
  383. {
  384. float pos = offset.y/scrollableRange.y;
  385. float sign = MathEx.Sign(pos);
  386. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  387. pos = (1.0f - pos) /2.0f;
  388. vertScrollBar.Position = pos;
  389. }
  390. else
  391. vertScrollBar.Position = 0.0f;
  392. }
  393. private Vector2 GetZoomedRange()
  394. {
  395. float zoomLevel = MathEx.Pow(2, zoomAmount);
  396. Vector2 optimalRange = GetOptimalRange();
  397. return optimalRange / zoomLevel;
  398. }
  399. private Vector2 GetTotalRange()
  400. {
  401. // Return optimal range (that covers the visible curve)
  402. Vector2 optimalRange = GetOptimalRange();
  403. // Increase range in case user zoomed out
  404. Vector2 zoomedRange = GetZoomedRange();
  405. return Vector2.Max(optimalRange, zoomedRange);
  406. }
  407. private void Zoom(Vector2 curvePos, float amount)
  408. {
  409. // Increase or decrease the visible range depending on zoom level
  410. Vector2 oldZoomedRange = GetZoomedRange();
  411. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  412. Vector2 zoomedRange = GetZoomedRange();
  413. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  414. Vector2 currentRange = guiCurveEditor.Range;
  415. Vector2 newRange = currentRange + zoomedDiff;
  416. guiCurveEditor.Range = newRange;
  417. // When zooming, make sure to focus on the point provided, so adjust the offset
  418. Vector2 rangeScale = newRange;
  419. rangeScale.x /= currentRange.x;
  420. rangeScale.y /= currentRange.y;
  421. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  422. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  423. Vector2 diff = newCurvePos - relativeCurvePos;
  424. guiCurveEditor.Offset -= diff;
  425. UpdateScrollBarSize();
  426. UpdateScrollBarPosition();
  427. }
  428. #endregion
  429. #region Curve save/load
  430. private EditorAnimClipInfo clipInfo;
  431. private void LoadAnimClip(AnimationClip clip)
  432. {
  433. EditorPersistentData persistentData = EditorApplication.PersistentData;
  434. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  435. {
  436. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  437. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  438. // within the editor.
  439. if (clipInfo.isImported)
  440. {
  441. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  442. newClipInfo.events = clipInfo.events;
  443. }
  444. }
  445. else
  446. clipInfo = EditorAnimClipInfo.Create(clip);
  447. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  448. foreach (var curve in clipInfo.curves)
  449. guiFieldDisplay.AddField(new AnimFieldInfo(curve.Key, curve.Value, !clipInfo.isImported));
  450. guiCurveEditor.Events = clipInfo.events;
  451. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  452. SetCurrentFrame(0);
  453. FPS = clipInfo.sampleRate;
  454. }
  455. private void UpdateSelectedSO(bool force)
  456. {
  457. SceneObject so = Selection.SceneObject;
  458. if (selectedSO != so || force)
  459. {
  460. if (selectedSO != null && so == null)
  461. {
  462. EditorInput.OnPointerPressed -= OnPointerPressed;
  463. EditorInput.OnPointerMoved -= OnPointerMoved;
  464. EditorInput.OnPointerReleased -= OnPointerReleased;
  465. EditorInput.OnButtonUp -= OnButtonUp;
  466. }
  467. else if (selectedSO == null && so != null)
  468. {
  469. EditorInput.OnPointerPressed += OnPointerPressed;
  470. EditorInput.OnPointerMoved += OnPointerMoved;
  471. EditorInput.OnPointerReleased += OnPointerReleased;
  472. EditorInput.OnButtonUp += OnButtonUp;
  473. }
  474. zoomAmount = 0.0f;
  475. selectedSO = so;
  476. selectedFields.Clear();
  477. clipInfo = null;
  478. RebuildGUI();
  479. // Load existing clip if one exists
  480. if (selectedSO != null)
  481. {
  482. Animation animation = selectedSO.GetComponent<Animation>();
  483. if (animation != null)
  484. {
  485. AnimationClip clip = animation.DefaultClip;
  486. if (clip != null)
  487. LoadAnimClip(clip);
  488. }
  489. }
  490. if(clipInfo == null)
  491. clipInfo = new EditorAnimClipInfo();
  492. if(selectedSO != null)
  493. UpdateDisplayedCurves(true);
  494. }
  495. }
  496. #endregion
  497. #region Curve display
  498. private int currentFrameIdx;
  499. private int fps = 1;
  500. internal int FPS
  501. {
  502. get { return fps; }
  503. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  504. }
  505. private void SetCurrentFrame(int frameIdx)
  506. {
  507. currentFrameIdx = Math.Max(0, frameIdx);
  508. frameInputField.Value = currentFrameIdx;
  509. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  510. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  511. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  512. foreach (var kvp in clipInfo.curves)
  513. {
  514. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  515. fieldValue.path = kvp.Key;
  516. switch (kvp.Value.type)
  517. {
  518. case SerializableProperty.FieldType.Vector2:
  519. {
  520. Vector2 value = new Vector2();
  521. for (int i = 0; i < 2; i++)
  522. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  523. fieldValue.value = value;
  524. }
  525. break;
  526. case SerializableProperty.FieldType.Vector3:
  527. {
  528. Vector3 value = new Vector3();
  529. for (int i = 0; i < 3; i++)
  530. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  531. fieldValue.value = value;
  532. }
  533. break;
  534. case SerializableProperty.FieldType.Vector4:
  535. {
  536. Vector4 value = new Vector4();
  537. for (int i = 0; i < 4; i++)
  538. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  539. fieldValue.value = value;
  540. }
  541. break;
  542. case SerializableProperty.FieldType.Color:
  543. {
  544. Color value = new Color();
  545. for (int i = 0; i < 4; i++)
  546. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  547. fieldValue.value = value;
  548. }
  549. break;
  550. case SerializableProperty.FieldType.Bool:
  551. case SerializableProperty.FieldType.Int:
  552. case SerializableProperty.FieldType.Float:
  553. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  554. break;
  555. }
  556. values.Add(fieldValue);
  557. }
  558. guiFieldDisplay.SetDisplayValues(values.ToArray());
  559. }
  560. private CurveDrawInfo[] GetDisplayedCurves()
  561. {
  562. List<CurveDrawInfo> curvesToDisplay = new List<CurveDrawInfo>();
  563. if (selectedFields.Count == 0) // Display all if nothing is selected
  564. {
  565. if (clipInfo == null)
  566. return curvesToDisplay.ToArray();
  567. foreach (var curve in clipInfo.curves)
  568. {
  569. for (int i = 0; i < curve.Value.curveInfos.Length; i++)
  570. curvesToDisplay.Add(curve.Value.curveInfos[i]);
  571. }
  572. }
  573. else
  574. {
  575. for (int i = 0; i < selectedFields.Count; i++)
  576. {
  577. CurveDrawInfo curveInfo;
  578. if (TryGetCurve(selectedFields[i], out curveInfo))
  579. curvesToDisplay.Add(curveInfo);
  580. }
  581. }
  582. return curvesToDisplay.ToArray();
  583. }
  584. private Vector2 GetOptimalRange()
  585. {
  586. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  587. float xRange;
  588. float yRange;
  589. CalculateRange(curvesToDisplay, out xRange, out yRange);
  590. // Add padding to y range
  591. yRange *= 1.05f;
  592. // Don't allow zero range
  593. if (xRange == 0.0f)
  594. xRange = 60.0f;
  595. if (yRange == 0.0f)
  596. yRange = 10.0f;
  597. return new Vector2(xRange, yRange);
  598. }
  599. private void UpdateCurveColors()
  600. {
  601. int globalCurveIdx = 0;
  602. foreach (var curveGroup in clipInfo.curves)
  603. {
  604. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  605. curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
  606. }
  607. }
  608. private void UpdateDisplayedCurves(bool allowReduce = false)
  609. {
  610. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  611. guiCurveEditor.SetCurves(curvesToDisplay);
  612. Vector2 newRange = GetOptimalRange();
  613. if (!allowReduce)
  614. {
  615. // Don't reduce visible range
  616. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  617. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  618. }
  619. guiCurveEditor.Range = newRange;
  620. UpdateScrollBarSize();
  621. }
  622. #endregion
  623. #region Field display
  624. private List<string> selectedFields = new List<string>();
  625. private void AddNewField(string path, SerializableProperty.FieldType type)
  626. {
  627. bool noSelection = selectedFields.Count == 0;
  628. switch (type)
  629. {
  630. case SerializableProperty.FieldType.Vector4:
  631. {
  632. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  633. fieldCurves.type = type;
  634. fieldCurves.curveInfos = new CurveDrawInfo[4];
  635. string[] subPaths = { ".x", ".y", ".z", ".w" };
  636. for (int i = 0; i < subPaths.Length; i++)
  637. {
  638. string subFieldPath = path + subPaths[i];
  639. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  640. selectedFields.Add(subFieldPath);
  641. }
  642. clipInfo.curves[path] = fieldCurves;
  643. }
  644. break;
  645. case SerializableProperty.FieldType.Vector3:
  646. {
  647. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  648. fieldCurves.type = type;
  649. fieldCurves.curveInfos = new CurveDrawInfo[3];
  650. string[] subPaths = { ".x", ".y", ".z" };
  651. for (int i = 0; i < subPaths.Length; i++)
  652. {
  653. string subFieldPath = path + subPaths[i];
  654. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  655. selectedFields.Add(subFieldPath);
  656. }
  657. clipInfo.curves[path] = fieldCurves;
  658. }
  659. break;
  660. case SerializableProperty.FieldType.Vector2:
  661. {
  662. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  663. fieldCurves.type = type;
  664. fieldCurves.curveInfos = new CurveDrawInfo[2];
  665. string[] subPaths = { ".x", ".y" };
  666. for (int i = 0; i < subPaths.Length; i++)
  667. {
  668. string subFieldPath = path + subPaths[i];
  669. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  670. selectedFields.Add(subFieldPath);
  671. }
  672. clipInfo.curves[path] = fieldCurves;
  673. }
  674. break;
  675. case SerializableProperty.FieldType.Color:
  676. {
  677. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  678. fieldCurves.type = type;
  679. fieldCurves.curveInfos = new CurveDrawInfo[4];
  680. string[] subPaths = { ".r", ".g", ".b", ".a" };
  681. for (int i = 0; i < subPaths.Length; i++)
  682. {
  683. string subFieldPath = path + subPaths[i];
  684. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  685. selectedFields.Add(subFieldPath);
  686. }
  687. clipInfo.curves[path] = fieldCurves;
  688. }
  689. break;
  690. default: // Primitive type
  691. {
  692. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  693. fieldCurves.type = type;
  694. fieldCurves.curveInfos = new CurveDrawInfo[1];
  695. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  696. selectedFields.Add(path);
  697. clipInfo.curves[path] = fieldCurves;
  698. }
  699. break;
  700. }
  701. UpdateCurveColors();
  702. UpdateDisplayedFields();
  703. EditorApplication.SetProjectDirty();
  704. UpdateDisplayedCurves(noSelection);
  705. }
  706. private void SelectField(string path, bool additive)
  707. {
  708. if (!additive)
  709. selectedFields.Clear();
  710. bool noSelection = selectedFields.Count == 0;
  711. if (!string.IsNullOrEmpty(path))
  712. {
  713. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  714. selectedFields.Add(path);
  715. }
  716. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  717. UpdateDisplayedCurves(noSelection);
  718. }
  719. private void RemoveSelectedFields()
  720. {
  721. for (int i = 0; i < selectedFields.Count; i++)
  722. {
  723. selectedFields.Remove(selectedFields[i]);
  724. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  725. }
  726. UpdateCurveColors();
  727. UpdateDisplayedFields();
  728. selectedFields.Clear();
  729. EditorApplication.SetProjectDirty();
  730. UpdateDisplayedCurves();
  731. }
  732. private void UpdateDisplayedFields()
  733. {
  734. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  735. foreach (var KVP in clipInfo.curves)
  736. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value, !clipInfo.isImported));
  737. guiFieldDisplay.SetFields(existingFields.ToArray());
  738. }
  739. #endregion
  740. #region Helpers
  741. private Vector2I GetCurveEditorSize()
  742. {
  743. Vector2I output = new Vector2I();
  744. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  745. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  746. return output;
  747. }
  748. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xRange, out float yRange)
  749. {
  750. xRange = 0.0f;
  751. yRange = 0.0f;
  752. foreach (var curveInfo in curveInfos)
  753. {
  754. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  755. foreach (var key in keyframes)
  756. {
  757. xRange = Math.Max(xRange, key.time);
  758. yRange = Math.Max(yRange, Math.Abs(key.value));
  759. }
  760. }
  761. }
  762. private bool TryGetCurve(string path, out CurveDrawInfo curveInfo)
  763. {
  764. int index = path.LastIndexOf(".");
  765. string parentPath;
  766. string subPathSuffix = null;
  767. if (index == -1)
  768. {
  769. parentPath = path;
  770. }
  771. else
  772. {
  773. parentPath = path.Substring(0, index);
  774. subPathSuffix = path.Substring(index, path.Length - index);
  775. }
  776. FieldAnimCurves fieldCurves;
  777. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  778. {
  779. if (!string.IsNullOrEmpty(subPathSuffix))
  780. {
  781. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  782. {
  783. curveInfo = fieldCurves.curveInfos[0];
  784. return true;
  785. }
  786. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  787. {
  788. curveInfo = fieldCurves.curveInfos[1];
  789. return true;
  790. }
  791. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  792. {
  793. curveInfo = fieldCurves.curveInfos[2];
  794. return true;
  795. }
  796. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  797. {
  798. curveInfo = fieldCurves.curveInfos[3];
  799. return true;
  800. }
  801. }
  802. else
  803. {
  804. curveInfo = fieldCurves.curveInfos[0];
  805. return true;
  806. }
  807. }
  808. curveInfo = new CurveDrawInfo();
  809. return false;
  810. }
  811. private bool IsPathParent(string child, string parent)
  812. {
  813. string[] childEntries = child.Split('/', '.');
  814. string[] parentEntries = parent.Split('/', '.');
  815. if (parentEntries.Length >= child.Length)
  816. return false;
  817. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  818. for (int i = 0; i < compareLength; i++)
  819. {
  820. if (childEntries[i] != parentEntries[i])
  821. return false;
  822. }
  823. return true;
  824. }
  825. private string GetSubPathParent(string path)
  826. {
  827. int index = path.LastIndexOf(".");
  828. if (index == -1)
  829. return path;
  830. return path.Substring(0, index);
  831. }
  832. #endregion
  833. #region Input callbacks
  834. private void OnPointerPressed(PointerEvent ev)
  835. {
  836. guiCurveEditor.OnPointerPressed(ev);
  837. if (ev.button == PointerButton.Middle)
  838. {
  839. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  840. Vector2 curvePos;
  841. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  842. {
  843. dragStartPos = windowPos;
  844. isButtonHeld = true;
  845. }
  846. }
  847. }
  848. private void OnPointerMoved(PointerEvent ev)
  849. {
  850. guiCurveEditor.OnPointerMoved(ev);
  851. if (isButtonHeld)
  852. {
  853. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  854. int distance = Vector2I.Distance(dragStartPos, windowPos);
  855. if (distance >= DRAG_START_DISTANCE)
  856. {
  857. isDragInProgress = true;
  858. Cursor.Hide();
  859. Rect2I clipRect;
  860. clipRect.x = ev.ScreenPos.x - 2;
  861. clipRect.y = ev.ScreenPos.y - 2;
  862. clipRect.width = 4;
  863. clipRect.height = 4;
  864. Cursor.ClipToRect(clipRect);
  865. }
  866. }
  867. }
  868. private void OnPointerReleased(PointerEvent ev)
  869. {
  870. if (isDragInProgress)
  871. {
  872. Cursor.Show();
  873. Cursor.ClipDisable();
  874. }
  875. isButtonHeld = false;
  876. isDragInProgress = false;
  877. guiCurveEditor.OnPointerReleased(ev);
  878. }
  879. private void OnButtonUp(ButtonEvent ev)
  880. {
  881. guiCurveEditor.OnButtonUp(ev);
  882. }
  883. #endregion
  884. #region General callbacks
  885. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  886. {
  887. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  888. string pathNoRoot = path.TrimStart('/');
  889. int separatorIdx = pathNoRoot.IndexOf("/");
  890. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  891. return;
  892. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  893. AddNewField(pathNoRoot, type);
  894. }
  895. private void OnHorzScrollOrResize(float position, float size)
  896. {
  897. SetHorzScrollbarProperties(position, size);
  898. }
  899. private void OnVertScrollOrResize(float position, float size)
  900. {
  901. SetVertScrollbarProperties(position, size);
  902. }
  903. private void OnFieldSelected(string path)
  904. {
  905. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  906. SelectField(path, additive);
  907. }
  908. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  909. {
  910. UpdateSelectedSO(false);
  911. }
  912. private void OnFrameSelected(int frameIdx)
  913. {
  914. SetCurrentFrame(frameIdx);
  915. }
  916. private void OnEventsChanged()
  917. {
  918. clipInfo.events = guiCurveEditor.Events;
  919. EditorApplication.SetProjectDirty();
  920. }
  921. #endregion
  922. }
  923. /// <summary>
  924. /// Drop down window that displays options used by the animation window.
  925. /// </summary>
  926. [DefaultSize(100, 50)]
  927. internal class AnimationOptions : DropDownWindow
  928. {
  929. /// <summary>
  930. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  931. /// use.
  932. /// </summary>
  933. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  934. internal void Initialize(AnimationWindow parent)
  935. {
  936. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  937. fpsField.Value = parent.FPS;
  938. fpsField.OnChanged += x => { parent.FPS = x; };
  939. GUILayoutY vertLayout = GUI.AddLayoutY();
  940. vertLayout.AddFlexibleSpace();
  941. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  942. contentLayout.AddFlexibleSpace();
  943. contentLayout.AddElement(fpsField);
  944. contentLayout.AddFlexibleSpace();
  945. vertLayout.AddFlexibleSpace();
  946. }
  947. }
  948. /** @} */
  949. }