AnimationWindow.cs 79 KB

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