AnimationWindow.cs 80 KB

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