2
0

AnimationWindow.cs 69 KB

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