AnimationWindow.cs 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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 (value, time).</returns>
  1095. private Vector2 GetOptimalRange()
  1096. {
  1097. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1098. float xRange;
  1099. float yRange;
  1100. CalculateRange(curvesToDisplay, out xRange, out yRange);
  1101. // Add padding to y range
  1102. yRange *= 1.05f;
  1103. // Don't allow zero range
  1104. if (xRange == 0.0f)
  1105. xRange = 60.0f;
  1106. if (yRange == 0.0f)
  1107. yRange = 10.0f;
  1108. return new Vector2(xRange, yRange);
  1109. }
  1110. /// <summary>
  1111. /// Calculates an unique color for each animation curve.
  1112. /// </summary>
  1113. private void UpdateCurveColors()
  1114. {
  1115. int globalCurveIdx = 0;
  1116. foreach (var curveGroup in clipInfo.curves)
  1117. {
  1118. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  1119. curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Updates the curve display with currently selected curves.
  1124. /// </summary>
  1125. /// <param name="allowReduce">Normally the curve display will expand if newly selected curves cover a larger area
  1126. /// than currently available, but the area won't be reduced if the selected curves cover
  1127. /// a smaller area. Set this to true to allow the area to be reduced.</param>
  1128. private void UpdateDisplayedCurves(bool allowReduce = false)
  1129. {
  1130. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1131. guiCurveEditor.SetCurves(curvesToDisplay);
  1132. Vector2 newRange = GetOptimalRange();
  1133. if (!allowReduce)
  1134. {
  1135. // Don't reduce visible range
  1136. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  1137. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  1138. }
  1139. guiCurveEditor.Range = newRange;
  1140. UpdateScrollBarSize();
  1141. }
  1142. #endregion
  1143. #region Field display
  1144. private List<string> selectedFields = new List<string>();
  1145. /// <summary>
  1146. /// Registers a new animation curve field.
  1147. /// </summary>
  1148. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  1149. /// <param name="type">Type of the field (float, vector, etc.)</param>
  1150. private void AddNewField(string path, SerializableProperty.FieldType type)
  1151. {
  1152. bool noSelection = selectedFields.Count == 0;
  1153. bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path);
  1154. switch (type)
  1155. {
  1156. case SerializableProperty.FieldType.Vector4:
  1157. {
  1158. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1159. fieldCurves.type = type;
  1160. fieldCurves.isPropertyCurve = isPropertyCurve;
  1161. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1162. string[] subPaths = { ".x", ".y", ".z", ".w" };
  1163. for (int i = 0; i < subPaths.Length; i++)
  1164. {
  1165. string subFieldPath = path + subPaths[i];
  1166. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1167. selectedFields.Add(subFieldPath);
  1168. }
  1169. clipInfo.curves[path] = fieldCurves;
  1170. }
  1171. break;
  1172. case SerializableProperty.FieldType.Vector3:
  1173. {
  1174. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1175. fieldCurves.type = type;
  1176. fieldCurves.isPropertyCurve = isPropertyCurve;
  1177. fieldCurves.curveInfos = new CurveDrawInfo[3];
  1178. string[] subPaths = { ".x", ".y", ".z" };
  1179. for (int i = 0; i < subPaths.Length; i++)
  1180. {
  1181. string subFieldPath = path + subPaths[i];
  1182. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1183. selectedFields.Add(subFieldPath);
  1184. }
  1185. clipInfo.curves[path] = fieldCurves;
  1186. }
  1187. break;
  1188. case SerializableProperty.FieldType.Vector2:
  1189. {
  1190. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1191. fieldCurves.type = type;
  1192. fieldCurves.isPropertyCurve = isPropertyCurve;
  1193. fieldCurves.curveInfos = new CurveDrawInfo[2];
  1194. string[] subPaths = { ".x", ".y" };
  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.Color:
  1205. {
  1206. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1207. fieldCurves.type = type;
  1208. fieldCurves.isPropertyCurve = isPropertyCurve;
  1209. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1210. string[] subPaths = { ".r", ".g", ".b", ".a" };
  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. default: // Primitive type
  1221. {
  1222. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1223. fieldCurves.type = type;
  1224. fieldCurves.isPropertyCurve = isPropertyCurve;
  1225. fieldCurves.curveInfos = new CurveDrawInfo[1];
  1226. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  1227. selectedFields.Add(path);
  1228. clipInfo.curves[path] = fieldCurves;
  1229. }
  1230. break;
  1231. }
  1232. UpdateCurveColors();
  1233. UpdateDisplayedFields();
  1234. EditorApplication.SetProjectDirty();
  1235. UpdateDisplayedCurves(noSelection);
  1236. }
  1237. /// <summary>
  1238. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  1239. /// </summary>
  1240. /// <param name="path">Path of the field to display.</param>
  1241. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  1242. /// only the provided field will be shown.</param>
  1243. private void SelectField(string path, bool additive)
  1244. {
  1245. if (!additive)
  1246. selectedFields.Clear();
  1247. bool noSelection = selectedFields.Count == 0;
  1248. if (!string.IsNullOrEmpty(path))
  1249. {
  1250. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  1251. selectedFields.Add(path);
  1252. }
  1253. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  1254. UpdateDisplayedCurves(noSelection);
  1255. }
  1256. /// <summary>
  1257. /// Deletes all currently selecting fields, removing them their curves permanently.
  1258. /// </summary>
  1259. private void RemoveSelectedFields()
  1260. {
  1261. for (int i = 0; i < selectedFields.Count; i++)
  1262. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  1263. UpdateCurveColors();
  1264. UpdateDisplayedFields();
  1265. selectedFields.Clear();
  1266. EditorApplication.SetProjectDirty();
  1267. UpdateDisplayedCurves();
  1268. }
  1269. /// <summary>
  1270. /// Updates the GUI element displaying the current animation curve fields.
  1271. /// </summary>
  1272. private void UpdateDisplayedFields()
  1273. {
  1274. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  1275. foreach (var KVP in clipInfo.curves)
  1276. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value));
  1277. guiFieldDisplay.SetFields(existingFields.ToArray());
  1278. }
  1279. #endregion
  1280. #region Helpers
  1281. /// <summary>
  1282. /// Returns the size of the curve editor GUI element.
  1283. /// </summary>
  1284. /// <returns>Width/height of the curve editor, in pixels.</returns>
  1285. private Vector2I GetCurveEditorSize()
  1286. {
  1287. Vector2I output = new Vector2I();
  1288. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  1289. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  1290. return output;
  1291. }
  1292. /// <summary>
  1293. /// Calculates the total range covered by a set of curves.
  1294. /// </summary>
  1295. /// <param name="curveInfos">Curves to calculate range for.</param>
  1296. /// <param name="xRange">Maximum time value present in the curves.</param>
  1297. /// <param name="yRange">Maximum absolute curve value present in the curves.</param>
  1298. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xRange, out float yRange)
  1299. {
  1300. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  1301. // tangents
  1302. xRange = 0.0f;
  1303. yRange = 0.0f;
  1304. foreach (var curveInfo in curveInfos)
  1305. {
  1306. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  1307. foreach (var key in keyframes)
  1308. {
  1309. xRange = Math.Max(xRange, key.time);
  1310. yRange = Math.Max(yRange, Math.Abs(key.value));
  1311. }
  1312. }
  1313. }
  1314. /// <summary>
  1315. /// Attempts to find a curve field at the specified path.
  1316. /// </summary>
  1317. /// <param name="path">Path of the curve field to look for.</param>
  1318. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  1319. /// if it is a complex type, like a vector).</param>
  1320. /// <returns>True if the curve field was found, false otherwise.</returns>
  1321. private bool TryGetCurve(string path, out CurveDrawInfo[] curveInfos)
  1322. {
  1323. int index = path.LastIndexOf(".");
  1324. string parentPath;
  1325. string subPathSuffix = null;
  1326. if (index == -1)
  1327. {
  1328. parentPath = path;
  1329. }
  1330. else
  1331. {
  1332. parentPath = path.Substring(0, index);
  1333. subPathSuffix = path.Substring(index, path.Length - index);
  1334. }
  1335. FieldAnimCurves fieldCurves;
  1336. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1337. {
  1338. if (!string.IsNullOrEmpty(subPathSuffix))
  1339. {
  1340. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1341. {
  1342. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1343. return true;
  1344. }
  1345. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1346. {
  1347. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1348. return true;
  1349. }
  1350. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1351. {
  1352. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1353. return true;
  1354. }
  1355. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1356. {
  1357. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1358. return true;
  1359. }
  1360. }
  1361. else
  1362. {
  1363. curveInfos = fieldCurves.curveInfos;
  1364. return true;
  1365. }
  1366. }
  1367. curveInfos = new CurveDrawInfo[0];
  1368. return false;
  1369. }
  1370. /// <summary>
  1371. /// Checks if one curve field path a parent of the other.
  1372. /// </summary>
  1373. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1374. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1375. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1376. private bool IsPathParent(string child, string parent)
  1377. {
  1378. string[] childEntries = child.Split('/', '.');
  1379. string[] parentEntries = parent.Split('/', '.');
  1380. if (parentEntries.Length >= child.Length)
  1381. return false;
  1382. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1383. for (int i = 0; i < compareLength; i++)
  1384. {
  1385. if (childEntries[i] != parentEntries[i])
  1386. return false;
  1387. }
  1388. return true;
  1389. }
  1390. /// <summary>
  1391. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1392. /// path.
  1393. /// </summary>
  1394. /// <param name="path">Path to check.</param>
  1395. /// <returns>Path without sub-elements.</returns>
  1396. private string GetSubPathParent(string path)
  1397. {
  1398. int index = path.LastIndexOf(".");
  1399. if (index == -1)
  1400. return path;
  1401. return path.Substring(0, index);
  1402. }
  1403. /// <summary>
  1404. /// Iterates over all components of a property and calls the provided action for every component with the current
  1405. /// value of the property. Only works with floating point (any dimension), integer, color and boolean property
  1406. /// types. Since reported values are always floating point booleans are encoded as -1.0f for false and 1.0f for
  1407. /// true, and integers are converted to floating point.
  1408. /// </summary>
  1409. /// <param name="property">Property whose components to iterate over.</param>
  1410. /// <param name="action">
  1411. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1412. /// and the sequential index of the component.
  1413. /// </param>
  1414. private void ForEachPropertyComponentGet(SerializableProperty property, Action<float, int> action)
  1415. {
  1416. switch (property.Type)
  1417. {
  1418. case SerializableProperty.FieldType.Vector2:
  1419. {
  1420. Vector2 value = property.GetValue<Vector2>();
  1421. for (int i = 0; i < 2; i++)
  1422. action(value[i], i);
  1423. }
  1424. break;
  1425. case SerializableProperty.FieldType.Vector3:
  1426. {
  1427. Vector3 value = property.GetValue<Vector3>();
  1428. for (int i = 0; i < 3; i++)
  1429. action(value[i], i);
  1430. }
  1431. break;
  1432. case SerializableProperty.FieldType.Vector4:
  1433. {
  1434. if (property.InternalType == typeof(Vector4))
  1435. {
  1436. Vector4 value = property.GetValue<Vector4>();
  1437. for (int i = 0; i < 4; i++)
  1438. action(value[i], i);
  1439. }
  1440. else if (property.InternalType == typeof(Quaternion))
  1441. {
  1442. Quaternion value = property.GetValue<Quaternion>();
  1443. for (int i = 0; i < 4; i++)
  1444. action(value[i], i);
  1445. }
  1446. }
  1447. break;
  1448. case SerializableProperty.FieldType.Color:
  1449. {
  1450. Color value = property.GetValue<Color>();
  1451. for (int i = 0; i < 4; i++)
  1452. action(value[i], i);
  1453. }
  1454. break;
  1455. case SerializableProperty.FieldType.Bool:
  1456. {
  1457. bool value = property.GetValue<bool>();
  1458. action(value ? 1.0f : -1.0f, 0);
  1459. }
  1460. break;
  1461. case SerializableProperty.FieldType.Int:
  1462. {
  1463. int value = property.GetValue<int>();
  1464. action(value, 0);
  1465. }
  1466. break;
  1467. case SerializableProperty.FieldType.Float:
  1468. {
  1469. float value = property.GetValue<float>();
  1470. action(value, 0);
  1471. }
  1472. break;
  1473. }
  1474. }
  1475. /// <summary>
  1476. /// Iterates over all components of a property, calls the provided action which returns a new value to be
  1477. /// assigned to the property component. Only works with floating point (any dimension), integer, color and boolean
  1478. /// property types. Since reported values are always floating point booleans are encoded as -1.0f for false and
  1479. /// 1.0f for true, and integers are converted to floating point.
  1480. /// </summary>
  1481. /// <param name="property">Property whose components to iterate over.</param>
  1482. /// <param name="action">
  1483. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1484. /// and the sequential index of the component.
  1485. /// </param>
  1486. private void ForEachPropertyComponentSet(SerializableProperty property, Func<int, float> action)
  1487. {
  1488. switch (property.Type)
  1489. {
  1490. case SerializableProperty.FieldType.Vector2:
  1491. {
  1492. Vector2 value = new Vector2();
  1493. for (int i = 0; i < 2; i++)
  1494. value[i] = action(i);
  1495. property.SetValue(value);
  1496. }
  1497. break;
  1498. case SerializableProperty.FieldType.Vector3:
  1499. {
  1500. Vector3 value = new Vector3();
  1501. for (int i = 0; i < 3; i++)
  1502. value[i] = action(i);
  1503. property.SetValue(value);
  1504. }
  1505. break;
  1506. case SerializableProperty.FieldType.Vector4:
  1507. {
  1508. if (property.InternalType == typeof(Vector4))
  1509. {
  1510. Vector4 value = new Vector4();
  1511. for (int i = 0; i < 4; i++)
  1512. value[i] = action(i);
  1513. property.SetValue(value);
  1514. }
  1515. else if (property.InternalType == typeof(Quaternion))
  1516. {
  1517. Quaternion value = new Quaternion();
  1518. for (int i = 0; i < 4; i++)
  1519. value[i] = action(i);
  1520. property.SetValue(value);
  1521. }
  1522. }
  1523. break;
  1524. case SerializableProperty.FieldType.Color:
  1525. {
  1526. Color value = new Color();
  1527. for (int i = 0; i < 4; i++)
  1528. value[i] = action(i);
  1529. property.SetValue(value);
  1530. }
  1531. break;
  1532. case SerializableProperty.FieldType.Bool:
  1533. {
  1534. bool value = action(0) > 0.0f ? true : false;
  1535. property.SetValue(value);
  1536. }
  1537. break;
  1538. case SerializableProperty.FieldType.Int:
  1539. {
  1540. int value = (int)action(0);
  1541. property.SetValue(value);
  1542. }
  1543. break;
  1544. case SerializableProperty.FieldType.Float:
  1545. {
  1546. float value = action(0);
  1547. property.SetValue(value);
  1548. }
  1549. break;
  1550. }
  1551. }
  1552. #endregion
  1553. #region Input callbacks
  1554. /// <summary>
  1555. /// Triggered when the user presses a mouse button.
  1556. /// </summary>
  1557. /// <param name="ev">Information about the mouse press event.</param>
  1558. private void OnPointerPressed(PointerEvent ev)
  1559. {
  1560. guiCurveEditor.OnPointerPressed(ev);
  1561. if (ev.button == PointerButton.Middle)
  1562. {
  1563. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1564. Vector2 curvePos;
  1565. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  1566. {
  1567. dragStartPos = windowPos;
  1568. isButtonHeld = true;
  1569. }
  1570. }
  1571. }
  1572. /// <summary>
  1573. /// Triggered when the user moves the mouse.
  1574. /// </summary>
  1575. /// <param name="ev">Information about the mouse move event.</param>
  1576. private void OnPointerMoved(PointerEvent ev)
  1577. {
  1578. guiCurveEditor.OnPointerMoved(ev);
  1579. if (isButtonHeld)
  1580. {
  1581. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1582. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1583. if (distance >= DRAG_START_DISTANCE)
  1584. {
  1585. isDragInProgress = true;
  1586. Cursor.Hide();
  1587. Rect2I clipRect;
  1588. clipRect.x = ev.ScreenPos.x - 2;
  1589. clipRect.y = ev.ScreenPos.y - 2;
  1590. clipRect.width = 4;
  1591. clipRect.height = 4;
  1592. Cursor.ClipToRect(clipRect);
  1593. }
  1594. }
  1595. }
  1596. /// <summary>
  1597. /// Triggered when the user releases a mouse button.
  1598. /// </summary>
  1599. /// <param name="ev">Information about the mouse release event.</param>
  1600. private void OnPointerReleased(PointerEvent ev)
  1601. {
  1602. if (isDragInProgress)
  1603. {
  1604. Cursor.Show();
  1605. Cursor.ClipDisable();
  1606. }
  1607. isButtonHeld = false;
  1608. isDragInProgress = false;
  1609. guiCurveEditor.OnPointerReleased(ev);
  1610. }
  1611. /// <summary>
  1612. /// Triggered when the user releases a keyboard button.
  1613. /// </summary>
  1614. /// <param name="ev">Information about the keyboard release event.</param>
  1615. private void OnButtonUp(ButtonEvent ev)
  1616. {
  1617. guiCurveEditor.OnButtonUp(ev);
  1618. }
  1619. #endregion
  1620. #region General callbacks
  1621. /// <summary>
  1622. /// Triggered by the field selector, when user selects a new curve field.
  1623. /// </summary>
  1624. /// <param name="path">Path of the selected curve field.</param>
  1625. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1626. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1627. {
  1628. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1629. string pathNoRoot = path.TrimStart('/');
  1630. int separatorIdx = pathNoRoot.IndexOf("/");
  1631. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1632. return;
  1633. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1634. AddNewField(pathNoRoot, type);
  1635. RecordState(pathNoRoot, 0.0f);
  1636. ApplyClipChanges();
  1637. }
  1638. /// <summary>
  1639. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1640. /// </summary>
  1641. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1642. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1643. private void OnHorzScrollOrResize(float position, float size)
  1644. {
  1645. SetHorzScrollbarProperties(position, size);
  1646. }
  1647. /// <summary>
  1648. /// Triggered when the user moves or resizes the vertical scrollbar.
  1649. /// </summary>
  1650. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1651. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1652. private void OnVertScrollOrResize(float position, float size)
  1653. {
  1654. SetVertScrollbarProperties(position, size);
  1655. }
  1656. /// <summary>
  1657. /// Triggered when the user selects a new curve field.
  1658. /// </summary>
  1659. /// <param name="path">Path of the selected curve field.</param>
  1660. private void OnFieldSelected(string path)
  1661. {
  1662. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1663. SelectField(path, additive);
  1664. }
  1665. /// <summary>
  1666. /// Triggered when the user selects a new scene object or a resource.
  1667. /// </summary>
  1668. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1669. /// <param name="resourcePaths">Newly selected resources.</param>
  1670. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1671. {
  1672. // While recording allow other objects to be selected so the user can modify them
  1673. if (state == State.Recording)
  1674. return;
  1675. UpdateSelectedSO(false);
  1676. }
  1677. /// <summary>
  1678. /// Triggered when the user selects a new frame in the curve display.
  1679. /// </summary>
  1680. /// <param name="frameIdx">Index of the selected frame.</param>
  1681. private void OnFrameSelected(int frameIdx)
  1682. {
  1683. SetCurrentFrame(frameIdx);
  1684. PreviewFrame(currentFrameIdx);
  1685. // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
  1686. // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
  1687. // animation to be evaluated synchronously when PreviewFrame is called.
  1688. delayRecord = true;
  1689. }
  1690. /// <summary>
  1691. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1692. /// </summary>
  1693. private void OnEventsChanged()
  1694. {
  1695. clipInfo.events = guiCurveEditor.Events;
  1696. EditorApplication.SetProjectDirty();
  1697. }
  1698. #endregion
  1699. }
  1700. /// <summary>
  1701. /// Drop down window that displays options used by the animation window.
  1702. /// </summary>
  1703. [DefaultSize(100, 50)]
  1704. internal class AnimationOptions : DropDownWindow
  1705. {
  1706. /// <summary>
  1707. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1708. /// use.
  1709. /// </summary>
  1710. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1711. internal void Initialize(AnimationWindow parent)
  1712. {
  1713. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1714. fpsField.Value = parent.FPS;
  1715. fpsField.OnChanged += x => { parent.FPS = x; };
  1716. GUILayoutY vertLayout = GUI.AddLayoutY();
  1717. vertLayout.AddFlexibleSpace();
  1718. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1719. contentLayout.AddFlexibleSpace();
  1720. contentLayout.AddElement(fpsField);
  1721. contentLayout.AddFlexibleSpace();
  1722. vertLayout.AddFlexibleSpace();
  1723. }
  1724. }
  1725. /// <summary>
  1726. /// Raw data representing a single animation curve.
  1727. /// </summary>
  1728. class AnimationCurveState
  1729. {
  1730. public KeyFrame[] keyFrames;
  1731. public TangentMode[] tangentModes;
  1732. }
  1733. /// <summary>
  1734. /// Raw data representing a single animation clip state.
  1735. /// </summary>
  1736. class AnimationClipState
  1737. {
  1738. public Dictionary<string, AnimationCurveState[]> curves = new Dictionary<string, AnimationCurveState[]>();
  1739. public AnimationEvent[] events;
  1740. }
  1741. /// <summary>
  1742. /// Undo command used in the AnimationWindow.
  1743. /// </summary>
  1744. internal class AnimationUndo : UndoableCommand
  1745. {
  1746. private AnimationClipState prevClipState;
  1747. private AnimationClipState clipState;
  1748. public AnimationUndo(AnimationClipState prevClipState, AnimationClipState clipState)
  1749. {
  1750. this.prevClipState = prevClipState;
  1751. this.clipState = clipState;
  1752. }
  1753. /// <inheritdoc/>
  1754. protected override void Commit()
  1755. {
  1756. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1757. window?.ApplyClipState(clipState);
  1758. }
  1759. /// <inheritdoc/>
  1760. protected override void Revert()
  1761. {
  1762. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1763. window?.ApplyClipState(prevClipState);
  1764. }
  1765. }
  1766. /** @} */
  1767. }