2
0

AnimationWindow.cs 68 KB

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