GUICurveEditor.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  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 BansheeEngine;
  6. namespace BansheeEditor
  7. {
  8. /** @addtogroup AnimationEditor
  9. * @{
  10. */
  11. /// <summary>
  12. /// Displays a set of animation curves and events. Allows manipulation of both by adding, removing and modifying
  13. /// curve keyframes, and animation events.
  14. /// </summary>
  15. internal class GUICurveEditor
  16. {
  17. /// <summary>
  18. /// Information about currently selected set of keyframes for a specific curve.
  19. /// </summary>
  20. class SelectedKeyframes
  21. {
  22. public int curveIdx;
  23. public List<int> keyIndices = new List<int>();
  24. }
  25. /// <summary>
  26. /// Information about a keyframe that is currently being dragged.
  27. /// </summary>
  28. struct DraggedKeyframe
  29. {
  30. public DraggedKeyframe(int index, KeyFrame original)
  31. {
  32. this.index = index;
  33. this.original = original;
  34. }
  35. public int index;
  36. public KeyFrame original;
  37. }
  38. /// <summary>
  39. /// Information about all keyframes of a specific curve that are currently being dragged.
  40. /// </summary>
  41. class DraggedKeyframes
  42. {
  43. public int curveIdx;
  44. public List<DraggedKeyframe> keys = new List<DraggedKeyframe>();
  45. }
  46. /// <summary>
  47. /// Data about an animation event.
  48. /// </summary>
  49. class EventInfo
  50. {
  51. public AnimationEvent animEvent;
  52. public bool selected;
  53. }
  54. private const int TIMELINE_HEIGHT = 20;
  55. private const int VERT_PADDING = 2;
  56. private const int EVENTS_HEIGHT = 15;
  57. private const int SIDEBAR_WIDTH = 30;
  58. private const int DRAG_START_DISTANCE = 3;
  59. private const float DRAG_SCALE = 3.0f;
  60. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  61. private EditorWindow window;
  62. private GUILayout gui;
  63. private GUILayout mainPanel;
  64. private GUIPanel drawingPanel;
  65. private GUIPanel eventsPanel;
  66. private GUITexture timelineBackground;
  67. private GUITexture eventsBackground;
  68. private GUIGraphTime guiTimeline;
  69. private GUIAnimEvents guiEvents;
  70. private GUICurveDrawing guiCurveDrawing;
  71. private GUIGraphValues guiSidebar;
  72. private int scrollBarWidth;
  73. private int scrollBarHeight;
  74. private GUIResizeableScrollBarH horzScrollBar;
  75. private GUIResizeableScrollBarV vertScrollBar;
  76. private ContextMenu blankContextMenu;
  77. private ContextMenu keyframeContextMenu;
  78. private ContextMenu blankEventContextMenu;
  79. private ContextMenu eventContextMenu;
  80. private Vector2I contextClickPosition;
  81. private CurveDrawInfo[] curveInfos = new CurveDrawInfo[0];
  82. private bool disableCurveEdit = false;
  83. private bool drawCurveRange = false;
  84. private float xRange = 60.0f;
  85. private float yRange = 10.0f;
  86. private Vector2 offset;
  87. private int width;
  88. private int height;
  89. private int markedFrameIdx;
  90. private List<SelectedKeyframes> selectedKeyframes = new List<SelectedKeyframes>();
  91. private bool showEvents = true;
  92. private List<EventInfo> events = new List<EventInfo>();
  93. private SceneObject eventsSO;
  94. private bool isPointerHeld;
  95. private bool isMousePressedOverKey;
  96. private bool isMousePressedOverTangent;
  97. private bool isDragInProgress;
  98. private bool isModifiedDuringDrag;
  99. private List<DraggedKeyframes> draggedKeyframes = new List<DraggedKeyframes>();
  100. private TangentRef draggedTangent;
  101. private Vector2I dragStart;
  102. /// <summary>
  103. /// Triggers whenever user selects a new frame. Reports the index of the selected frame.
  104. /// </summary>
  105. public Action<int> OnFrameSelected;
  106. /// <summary>
  107. /// Triggered whenever a new animation event is added.
  108. /// </summary>
  109. public Action OnEventAdded;
  110. /// <summary>
  111. /// Triggered whenever values in an animation event change.
  112. /// </summary>
  113. public Action OnEventModified;
  114. /// <summary>
  115. /// Triggered whenever an animation event is deleted.
  116. /// </summary>
  117. public Action OnEventDeleted;
  118. /// <summary>
  119. /// Triggered whenever keyframe in a curve is modified (added, removed or edited).
  120. /// </summary>
  121. public Action OnCurveModified;
  122. /// <summary>
  123. /// Triggered when the user clicks anywhere on the curve editor area.
  124. /// </summary>
  125. public Action OnClicked;
  126. /// <summary>
  127. /// The displayed range of the curve, where:
  128. /// .x - Range of the horizontal area. Displayed area ranges from [0, x].
  129. /// .y - Range of the vertical area. Displayed area ranges from [-y, y].
  130. /// </summary>
  131. public Vector2 Range
  132. {
  133. get { return new Vector2(xRange, yRange); }
  134. set
  135. {
  136. xRange = value.x;
  137. yRange = value.y;
  138. guiTimeline.SetRange(xRange);
  139. guiCurveDrawing.SetRange(xRange, yRange * 2.0f);
  140. guiSidebar.SetRange(offset.y - yRange, offset.y + yRange);
  141. if(showEvents)
  142. guiEvents.SetRange(xRange);
  143. Redraw();
  144. }
  145. }
  146. /// <summary>
  147. /// Determines how much to offset the displayed curve values.
  148. /// </summary>
  149. public Vector2 Offset
  150. {
  151. get { return offset; }
  152. set
  153. {
  154. offset = value;
  155. guiTimeline.SetOffset(offset.x);
  156. guiCurveDrawing.SetOffset(offset);
  157. guiSidebar.SetRange(offset.y - yRange, offset.y + yRange);
  158. if(showEvents)
  159. guiEvents.SetOffset(offset.x);
  160. Redraw();
  161. }
  162. }
  163. /// <summary>
  164. /// Returns the width of the curve editor, in pixels.
  165. /// </summary>
  166. public int Width
  167. {
  168. get { return width; }
  169. }
  170. /// <summary>
  171. /// Returns the height of the curve editor, in pixels.
  172. /// </summary>
  173. public int Height
  174. {
  175. get { return height; }
  176. }
  177. /// <summary>
  178. /// Set to true if curves are not allowed to be edited.
  179. /// </summary>
  180. public bool DisableCurveEdit
  181. {
  182. set { disableCurveEdit = value; }
  183. }
  184. /// <summary>
  185. /// Animation events displayed on the curve editor.
  186. /// </summary>
  187. public AnimationEvent[] Events
  188. {
  189. get
  190. {
  191. AnimationEvent[] animEvents = new AnimationEvent[events.Count];
  192. // Note: Hidden dependency. Returned events must point to the same event class this object is using, so
  193. // that any modifications made in this class will be visible in the returned values.
  194. for (int i = 0; i < events.Count; i++)
  195. animEvents[i] = events[i].animEvent;
  196. return animEvents;
  197. }
  198. set
  199. {
  200. events.Clear();
  201. for (int i = 0; i < value.Length; i++)
  202. {
  203. EventInfo eventInfo = new EventInfo();
  204. eventInfo.animEvent = value[i];
  205. events.Add(eventInfo);
  206. }
  207. UpdateEventsGUI();
  208. }
  209. }
  210. /// <summary>
  211. /// Creates a new curve editor GUI elements.
  212. /// </summary>
  213. /// <param name="window">Parent window of the GUI element.</param>
  214. /// <param name="gui">GUI layout into which to place the GUI element.</param>
  215. /// <param name="width">Width in pixels.</param>
  216. /// <param name="height">Height in pixels.</param>
  217. /// <param name="showEvents">If true show events on the graph and allow their editing.</param>
  218. public GUICurveEditor(EditorWindow window, GUILayout gui, int width, int height, bool showEvents)
  219. {
  220. this.window = window;
  221. this.gui = gui;
  222. this.showEvents = showEvents;
  223. blankContextMenu = new ContextMenu();
  224. blankContextMenu.AddItem("Add keyframe", AddKeyframeAtPosition);
  225. blankEventContextMenu = new ContextMenu();
  226. blankEventContextMenu.AddItem("Add event", AddEventAtPosition);
  227. keyframeContextMenu = new ContextMenu();
  228. keyframeContextMenu.AddItem("Delete", DeleteSelectedKeyframes);
  229. keyframeContextMenu.AddItem("Edit", EditSelectedKeyframe);
  230. keyframeContextMenu.AddItem("Tangents/Auto", () => { ChangeSelectionTangentMode(TangentMode.Auto); });
  231. keyframeContextMenu.AddItem("Tangents/Free", () => { ChangeSelectionTangentMode(TangentMode.Free); });
  232. keyframeContextMenu.AddItem("Tangents/In/Auto", () => { ChangeSelectionTangentMode(TangentMode.InAuto); });
  233. keyframeContextMenu.AddItem("Tangents/In/Free", () => { ChangeSelectionTangentMode(TangentMode.InFree); });
  234. keyframeContextMenu.AddItem("Tangents/In/Linear", () => { ChangeSelectionTangentMode(TangentMode.InLinear); });
  235. keyframeContextMenu.AddItem("Tangents/In/Step", () => { ChangeSelectionTangentMode(TangentMode.InStep); });
  236. keyframeContextMenu.AddItem("Tangents/Out/Auto", () => { ChangeSelectionTangentMode(TangentMode.OutAuto); });
  237. keyframeContextMenu.AddItem("Tangents/Out/Free", () => { ChangeSelectionTangentMode(TangentMode.OutFree); });
  238. keyframeContextMenu.AddItem("Tangents/Out/Linear", () => { ChangeSelectionTangentMode(TangentMode.OutLinear); });
  239. keyframeContextMenu.AddItem("Tangents/Out/Step", () => { ChangeSelectionTangentMode(TangentMode.OutStep); });
  240. eventContextMenu = new ContextMenu();
  241. eventContextMenu.AddItem("Delete", DeleteSelectedEvents);
  242. eventContextMenu.AddItem("Edit", EditSelectedEvent);
  243. horzScrollBar = new GUIResizeableScrollBarH();
  244. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  245. vertScrollBar = new GUIResizeableScrollBarV();
  246. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  247. GUILayout curveLayoutHorz = gui.AddLayoutX();
  248. GUILayout horzScrollBarLayout = gui.AddLayoutX();
  249. horzScrollBarLayout.AddElement(horzScrollBar);
  250. horzScrollBarLayout.AddFlexibleSpace();
  251. mainPanel = curveLayoutHorz.AddPanel();
  252. curveLayoutHorz.AddElement(vertScrollBar);
  253. curveLayoutHorz.AddFlexibleSpace();
  254. scrollBarHeight = horzScrollBar.Bounds.height;
  255. scrollBarWidth = vertScrollBar.Bounds.width;
  256. this.width = Math.Max(0, width - scrollBarWidth);
  257. this.height = Math.Max(0, height - scrollBarHeight);
  258. GUIPanel timelinePanel = mainPanel.AddPanel();
  259. guiTimeline = new GUIGraphTime(timelinePanel, this.width, TIMELINE_HEIGHT);
  260. GUIPanel timelineBgPanel = mainPanel.AddPanel(1);
  261. timelineBackground = new GUITexture(null, EditorStyles.Header);
  262. timelineBackground.Bounds = new Rect2I(0, 0, this.width, TIMELINE_HEIGHT + VERT_PADDING);
  263. timelineBgPanel.AddElement(timelineBackground);
  264. int eventsHeaderHeight = 0;
  265. if (showEvents)
  266. {
  267. eventsPanel = mainPanel.AddPanel();
  268. eventsPanel.SetPosition(0, TIMELINE_HEIGHT + VERT_PADDING);
  269. guiEvents = new GUIAnimEvents(eventsPanel, this.width, EVENTS_HEIGHT);
  270. GUIPanel eventsBgPanel = eventsPanel.AddPanel(1);
  271. eventsBackground = new GUITexture(null, EditorStyles.Header);
  272. eventsBackground.Bounds = new Rect2I(0, 0, this.width, EVENTS_HEIGHT + VERT_PADDING);
  273. eventsBgPanel.AddElement(eventsBackground);
  274. eventsHeaderHeight = EVENTS_HEIGHT;
  275. }
  276. drawingPanel = mainPanel.AddPanel();
  277. drawingPanel.SetPosition(0, TIMELINE_HEIGHT + eventsHeaderHeight + VERT_PADDING);
  278. guiCurveDrawing = new GUICurveDrawing(drawingPanel, this.width, this.height - TIMELINE_HEIGHT -
  279. eventsHeaderHeight - VERT_PADDING * 2, curveInfos);
  280. guiCurveDrawing.SetRange(60.0f, 20.0f);
  281. GUIPanel sidebarPanel = mainPanel.AddPanel(-10);
  282. sidebarPanel.SetPosition(0, TIMELINE_HEIGHT + eventsHeaderHeight + VERT_PADDING);
  283. guiSidebar = new GUIGraphValues(sidebarPanel, SIDEBAR_WIDTH, this.height - TIMELINE_HEIGHT -
  284. eventsHeaderHeight - VERT_PADDING * 2);
  285. guiSidebar.SetRange(-10.0f, 10.0f);
  286. horzScrollBar.SetWidth(this.width);
  287. vertScrollBar.SetHeight(this.height);
  288. UpdateScrollBarSize();
  289. }
  290. /// <summary>
  291. /// Change the set of curves to display.
  292. /// </summary>
  293. /// <param name="curveInfos">New set of curves to draw on the GUI element.</param>
  294. public void SetCurves(CurveDrawInfo[] curveInfos)
  295. {
  296. this.curveInfos = curveInfos;
  297. guiCurveDrawing.SetCurves(curveInfos);
  298. Redraw();
  299. }
  300. /// <summary>
  301. /// Changes curve rendering mode. Normally the curves are drawn individually, but when range rendering is enabled
  302. /// the area between the first two curves is drawn instead. This setting is ignored if less than two curves are
  303. /// present. More than two curves are also ignored.
  304. /// </summary>
  305. /// <param name="drawRange">True to enable range rendering mode, false to enable individual curve rendering.</param>
  306. public void SetDrawRange(bool drawRange)
  307. {
  308. drawCurveRange = drawRange;
  309. guiCurveDrawing.SetDrawRange(drawRange);
  310. Redraw();
  311. }
  312. /// <summary>
  313. /// Change the physical size of the GUI element.
  314. /// </summary>
  315. /// <param name="width">Width of the element in pixels.</param>
  316. /// <param name="height">Height of the element in pixels.</param>
  317. public void SetSize(int width, int height)
  318. {
  319. this.width = Math.Max(0, width - scrollBarWidth);
  320. this.height = Math.Max(0, height - scrollBarHeight);
  321. int eventsHeaderHeight = 0;
  322. if (showEvents)
  323. {
  324. eventsHeaderHeight = EVENTS_HEIGHT;
  325. guiEvents.SetSize(this.width, EVENTS_HEIGHT);
  326. eventsBackground.Bounds = new Rect2I(0, 0, this.width, EVENTS_HEIGHT + VERT_PADDING);
  327. }
  328. guiTimeline.SetSize(this.width, TIMELINE_HEIGHT);
  329. guiCurveDrawing.SetSize(this.width, this.height - TIMELINE_HEIGHT - eventsHeaderHeight);
  330. guiSidebar.SetSize(SIDEBAR_WIDTH, this.height - TIMELINE_HEIGHT - eventsHeaderHeight);
  331. timelineBackground.Bounds = new Rect2I(0, 0, this.width, TIMELINE_HEIGHT + VERT_PADDING);
  332. horzScrollBar.SetWidth(this.width);
  333. vertScrollBar.SetHeight(this.height);
  334. UpdateScrollBarSize();
  335. UpdateScrollBarPosition();
  336. }
  337. /// <summary>
  338. /// Number of frames per second, used for frame selection and marking.
  339. /// </summary>
  340. /// <param name="fps">Number of prames per second.</param>
  341. public void SetFPS(int fps)
  342. {
  343. guiTimeline.SetFPS(fps);
  344. guiCurveDrawing.SetFPS(fps);
  345. if(showEvents)
  346. guiEvents.SetFPS(fps);
  347. Redraw();
  348. }
  349. /// <summary>
  350. /// Sets a scene object that will be used for enumerating components/methods used for adding events.
  351. /// </summary>
  352. /// <param name="so">Scene object containing the animation component.</param>
  353. public void SetEventSceneObject(SceneObject so)
  354. {
  355. eventsSO = so;
  356. }
  357. /// <summary>
  358. /// Returns time for a frame with the specified index. Depends on set range and FPS.
  359. /// </summary>
  360. /// <param name="frameIdx">Index of the frame (not a key-frame) to get the time for.</param>
  361. /// <returns>Time of the frame with the provided index. </returns>
  362. public float GetTimeForFrame(int frameIdx)
  363. {
  364. return guiCurveDrawing.GetTimeForFrame(frameIdx);
  365. }
  366. /// <summary>
  367. /// Sets the frame at which to display the frame marker.
  368. /// </summary>
  369. /// <param name="frameIdx">Index of the frame to display the marker on, or -1 to clear the marker.</param>
  370. public void SetMarkedFrame(int frameIdx)
  371. {
  372. markedFrameIdx = frameIdx;
  373. guiTimeline.SetMarkedFrame(frameIdx);
  374. guiCurveDrawing.SetMarkedFrame(frameIdx);
  375. if(showEvents)
  376. guiEvents.SetMarkedFrame(frameIdx);
  377. Redraw();
  378. }
  379. /// <summary>
  380. /// Adds a new keyframe at the currently selected frame.
  381. /// </summary>
  382. public void AddKeyFrameAtMarker()
  383. {
  384. ClearSelection();
  385. if (!disableCurveEdit)
  386. {
  387. foreach (var curveInfo in curveInfos)
  388. {
  389. float t = guiCurveDrawing.GetTimeForFrame(markedFrameIdx);
  390. float value = curveInfo.curve.Evaluate(t);
  391. curveInfo.curve.AddOrUpdateKeyframe(t, value);
  392. curveInfo.curve.Apply();
  393. }
  394. }
  395. else
  396. ShowReadOnlyMessage();
  397. OnCurveModified?.Invoke();
  398. guiCurveDrawing.Rebuild();
  399. UpdateEventsGUI();
  400. }
  401. /// <summary>
  402. /// Adds a new event at the currently selected event.
  403. /// </summary>
  404. public void AddEventAtMarker()
  405. {
  406. ClearSelection();
  407. if (!showEvents)
  408. return;
  409. float eventTime = guiEvents.GetTimeForFrame(markedFrameIdx);
  410. EventInfo eventInfo = new EventInfo();
  411. eventInfo.animEvent = new AnimationEvent("", eventTime);
  412. events.Add(eventInfo);
  413. OnEventAdded?.Invoke();
  414. UpdateEventsGUI();
  415. guiCurveDrawing.Rebuild();
  416. StartEventEdit(events.Count - 1);
  417. }
  418. /// <summary>
  419. /// Rebuilds GUI displaying the animation events list.
  420. /// </summary>
  421. private void UpdateEventsGUI()
  422. {
  423. if (!showEvents)
  424. return;
  425. AnimationEvent[] animEvents = new AnimationEvent[events.Count];
  426. bool[] selected = new bool[events.Count];
  427. for (int i = 0; i < events.Count; i++)
  428. {
  429. animEvents[i] = events[i].animEvent;
  430. selected[i] = events[i].selected;
  431. }
  432. guiEvents.SetEvents(animEvents, selected);
  433. guiEvents.Rebuild();
  434. }
  435. /// <summary>
  436. /// Rebuilds the entire curve editor GUI.
  437. /// </summary>
  438. public void Redraw()
  439. {
  440. guiCurveDrawing.Rebuild();
  441. guiTimeline.Rebuild();
  442. guiSidebar.Rebuild();
  443. if(showEvents)
  444. guiEvents.Rebuild();
  445. }
  446. /// <summary>
  447. /// Changes the tangent mode for all currently selected keyframes.
  448. /// </summary>
  449. /// <param name="mode">Tangent mode to set. If only in or out tangent mode is provided, the mode for the opposite
  450. /// tangent will be kept as is.</param>
  451. private void ChangeSelectionTangentMode(TangentMode mode)
  452. {
  453. if (disableCurveEdit)
  454. {
  455. ShowReadOnlyMessage();
  456. return;
  457. }
  458. foreach (var selectedEntry in selectedKeyframes)
  459. {
  460. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  461. foreach (var keyframeIdx in selectedEntry.keyIndices)
  462. {
  463. if (mode == TangentMode.Auto || mode == TangentMode.Free)
  464. curve.SetTangentMode(keyframeIdx, mode);
  465. else
  466. {
  467. TangentMode newMode = curve.TangentModes[keyframeIdx];
  468. if (mode.HasFlag((TangentMode) TangentType.In))
  469. {
  470. // Replace only the in tangent mode, keeping the out tangent as is
  471. TangentMode inFlags = (TangentMode.InAuto | TangentMode.InFree | TangentMode.InLinear |
  472. TangentMode.InStep);
  473. newMode &= ~inFlags;
  474. newMode |= (mode & inFlags);
  475. }
  476. else
  477. {
  478. // Replace only the out tangent mode, keeping the in tangent as is
  479. TangentMode outFlags = (TangentMode.OutAuto | TangentMode.OutFree | TangentMode.OutLinear |
  480. TangentMode.OutStep);
  481. newMode &= ~outFlags;
  482. newMode |= (mode & outFlags);
  483. }
  484. curve.SetTangentMode(keyframeIdx, newMode);
  485. }
  486. }
  487. curve.Apply();
  488. }
  489. OnCurveModified?.Invoke();
  490. guiCurveDrawing.Rebuild();
  491. }
  492. /// <summary>
  493. /// Adds a new keyframe at the specified time on the provided curve.
  494. /// </summary>
  495. /// <param name="curveIdx">Index of the curve to add the keyframe to.</param>
  496. /// <param name="time">Time at which to add the keyframe.</param>
  497. private void AddKeyframe(int curveIdx, float time)
  498. {
  499. ClearSelection();
  500. if (!disableCurveEdit)
  501. {
  502. if (curveIdx < curveInfos.Length)
  503. {
  504. EdAnimationCurve curve = curveInfos[curveIdx].curve;
  505. float value = curve.Evaluate(time, false);
  506. curve.AddOrUpdateKeyframe(time, value);
  507. curve.Apply();
  508. }
  509. }
  510. else
  511. ShowReadOnlyMessage();
  512. OnCurveModified?.Invoke();
  513. guiCurveDrawing.Rebuild();
  514. UpdateEventsGUI();
  515. }
  516. /// <summary>
  517. /// Adds a new keyframe at the position the context menu was opened at.
  518. /// </summary>
  519. private void AddKeyframeAtPosition()
  520. {
  521. Vector2 curveCoord;
  522. if (guiCurveDrawing.PixelToCurveSpace(contextClickPosition, out curveCoord))
  523. {
  524. ClearSelection();
  525. if (!disableCurveEdit)
  526. {
  527. foreach (var curveInfo in curveInfos)
  528. {
  529. float t = curveCoord.x;
  530. float value = curveCoord.y;
  531. curveInfo.curve.AddOrUpdateKeyframe(t, value);
  532. curveInfo.curve.Apply();
  533. }
  534. }
  535. else
  536. ShowReadOnlyMessage();
  537. OnCurveModified?.Invoke();
  538. guiCurveDrawing.Rebuild();
  539. UpdateEventsGUI();
  540. }
  541. }
  542. /// <summary>
  543. /// Adds a new event at the position the context menu was opened at.
  544. /// </summary>
  545. private void AddEventAtPosition()
  546. {
  547. if (!showEvents)
  548. return;
  549. int frame = guiEvents.GetFrame(contextClickPosition);
  550. if (frame != -1)
  551. {
  552. ClearSelection();
  553. float time = guiEvents.GetTime(contextClickPosition.x);
  554. EventInfo eventInfo = new EventInfo();
  555. eventInfo.animEvent = new AnimationEvent("", time);
  556. events.Add(eventInfo);
  557. OnEventAdded?.Invoke();
  558. UpdateEventsGUI();
  559. guiCurveDrawing.Rebuild();
  560. StartEventEdit(events.Count - 1);
  561. }
  562. }
  563. /// <summary>
  564. /// Removes all currently selected keyframes from the curves.
  565. /// </summary>
  566. private void DeleteSelectedKeyframes()
  567. {
  568. if (!disableCurveEdit)
  569. {
  570. foreach (var selectedEntry in selectedKeyframes)
  571. {
  572. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  573. // Sort keys from highest to lowest so the indices don't change
  574. selectedEntry.keyIndices.Sort((x, y) =>
  575. {
  576. return y.CompareTo(x);
  577. });
  578. foreach (var keyframeIdx in selectedEntry.keyIndices)
  579. curve.RemoveKeyframe(keyframeIdx);
  580. curve.Apply();
  581. }
  582. }
  583. else
  584. ShowReadOnlyMessage();
  585. ClearSelection();
  586. OnCurveModified?.Invoke();
  587. guiCurveDrawing.Rebuild();
  588. UpdateEventsGUI();
  589. }
  590. /// <summary>
  591. /// Deletes all currently selected events.
  592. /// </summary>
  593. private void DeleteSelectedEvents()
  594. {
  595. List<EventInfo> newEvents = new List<EventInfo>();
  596. foreach (var entry in events)
  597. {
  598. if(!entry.selected)
  599. newEvents.Add(entry);
  600. }
  601. events = newEvents;
  602. OnEventDeleted?.Invoke();
  603. ClearSelection();
  604. guiCurveDrawing.Rebuild();
  605. UpdateEventsGUI();
  606. }
  607. /// <summary>
  608. /// Unselects any selected keyframes and events.
  609. /// </summary>
  610. private void ClearSelection()
  611. {
  612. guiCurveDrawing.ClearSelectedKeyframes();
  613. selectedKeyframes.Clear();
  614. foreach (var entry in events)
  615. entry.selected = false;
  616. }
  617. /// <summary>
  618. /// Adds the provided keyframe to the selection list (doesn't clear existing ones).
  619. /// </summary>
  620. /// <param name="keyframeRef">Keyframe to select.</param>
  621. private void SelectKeyframe(KeyframeRef keyframeRef)
  622. {
  623. guiCurveDrawing.SelectKeyframe(keyframeRef, true);
  624. if (!IsSelected(keyframeRef))
  625. {
  626. int curveIdx = selectedKeyframes.FindIndex(x =>
  627. {
  628. return x.curveIdx == keyframeRef.curveIdx;
  629. });
  630. if (curveIdx == -1)
  631. {
  632. curveIdx = selectedKeyframes.Count;
  633. SelectedKeyframes newKeyframes = new SelectedKeyframes();
  634. newKeyframes.curveIdx = keyframeRef.curveIdx;
  635. selectedKeyframes.Add(newKeyframes);
  636. }
  637. selectedKeyframes[curveIdx].keyIndices.Add(keyframeRef.keyIdx);
  638. }
  639. }
  640. /// <summary>
  641. /// Checks is the provided keyframe currently selected.
  642. /// </summary>
  643. /// <param name="keyframeRef">Keyframe to check.</param>
  644. /// <returns>True if selected, false otherwise.</returns>
  645. private bool IsSelected(KeyframeRef keyframeRef)
  646. {
  647. int curveIdx = selectedKeyframes.FindIndex(x =>
  648. {
  649. return x.curveIdx == keyframeRef.curveIdx;
  650. });
  651. if (curveIdx == -1)
  652. return false;
  653. int keyIdx = selectedKeyframes[curveIdx].keyIndices.FindIndex(x =>
  654. {
  655. return x == keyframeRef.keyIdx;
  656. });
  657. return keyIdx != -1;
  658. }
  659. /// <summary>
  660. /// Opens the edit window for the currently selected keyframe.
  661. /// </summary>
  662. private void EditSelectedKeyframe()
  663. {
  664. if (disableCurveEdit)
  665. {
  666. ShowReadOnlyMessage();
  667. return;
  668. }
  669. if (selectedKeyframes.Count == 0)
  670. return;
  671. EdAnimationCurve curve = curveInfos[selectedKeyframes[0].curveIdx].curve;
  672. KeyFrame[] keyFrames = curve.KeyFrames;
  673. int keyIndex = selectedKeyframes[0].keyIndices[0];
  674. KeyFrame keyFrame = keyFrames[keyIndex];
  675. Vector2I position = guiCurveDrawing.CurveToPixelSpace(new Vector2(keyFrame.time, keyFrame.value));
  676. Rect2I drawingBounds = GUIUtility.CalculateBounds(drawingPanel, window.GUI);
  677. position.x = MathEx.Clamp(position.x, 0, drawingBounds.width);
  678. position.y = MathEx.Clamp(position.y, 0, drawingBounds.height);
  679. Vector2I windowPos = position + new Vector2I(drawingBounds.x, drawingBounds.y);
  680. KeyframeEditWindow editWindow = DropDownWindow.Open<KeyframeEditWindow>(window, windowPos);
  681. editWindow.Initialize(keyFrame, x =>
  682. {
  683. curve.UpdateKeyframe(keyIndex, x.time, x.value);
  684. curve.Apply();
  685. guiCurveDrawing.Rebuild();
  686. },
  687. x =>
  688. {
  689. if (x)
  690. OnCurveModified?.Invoke();
  691. });
  692. }
  693. /// <summary>
  694. /// Opens the edit window for the currently selected event.
  695. /// </summary>
  696. private void EditSelectedEvent()
  697. {
  698. if (!showEvents)
  699. return;
  700. for (int i = 0; i < events.Count; i++)
  701. {
  702. if (events[i].selected)
  703. {
  704. StartEventEdit(i);
  705. break;
  706. }
  707. }
  708. }
  709. /// <summary>
  710. /// Opens the event edit window for the specified event.
  711. /// </summary>
  712. /// <param name="eventIdx">Event index to open the edit window for.</param>
  713. private void StartEventEdit(int eventIdx)
  714. {
  715. AnimationEvent animEvent = events[eventIdx].animEvent;
  716. Vector2I position = new Vector2I();
  717. position.x = guiEvents.GetOffset(animEvent.time);
  718. position.y = EVENTS_HEIGHT/2;
  719. Rect2I eventBounds = GUIUtility.CalculateBounds(eventsPanel, window.GUI);
  720. Vector2I windowPos = position + new Vector2I(eventBounds.x, eventBounds.y);
  721. if (eventsSO == null)
  722. return;
  723. Component[] components = eventsSO.GetComponents();
  724. string[] componentNames = new string[components.Length];
  725. for (int i = 0; i < components.Length; i++)
  726. componentNames[i] = components[i].GetType().Name;
  727. EventEditWindow editWindow = DropDownWindow.Open<EventEditWindow>(window, windowPos);
  728. editWindow.Initialize(animEvent, componentNames, () =>
  729. {
  730. UpdateEventsGUI();
  731. },
  732. x =>
  733. {
  734. if(x)
  735. OnEventModified?.Invoke();
  736. });
  737. }
  738. /// <summary>
  739. /// Shows a dialog box that notifies the user that the animation clip is read only.
  740. /// </summary>
  741. private void ShowReadOnlyMessage()
  742. {
  743. LocEdString title = new LocEdString("Warning");
  744. LocEdString message =
  745. new LocEdString("You cannot edit keyframes on animation clips that" +
  746. " are imported from an external file.");
  747. DialogBox.Open(title, message, DialogBox.Type.OK);
  748. }
  749. #region Input
  750. /// <summary>
  751. /// Handles input. Should be called by the owning window whenever a pointer is pressed.
  752. /// </summary>
  753. /// <param name="ev">Object containing pointer press event information.</param>
  754. internal void OnPointerPressed(PointerEvent ev)
  755. {
  756. if (ev.IsUsed)
  757. return;
  758. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  759. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  760. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  761. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  762. if (!isOverEditor)
  763. return;
  764. else
  765. OnClicked?.Invoke();
  766. Rect2I drawingBounds = drawingPanel.Bounds;
  767. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  768. Rect2I eventBounds = eventsPanel.Bounds;
  769. Vector2I eventPos = pointerPos - new Vector2I(eventBounds.x, eventBounds.y);
  770. if (ev.Button == PointerButton.Left)
  771. {
  772. Vector2 curveCoord;
  773. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  774. {
  775. KeyframeRef keyframeRef;
  776. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  777. {
  778. TangentRef tangentRef;
  779. if (guiCurveDrawing.FindTangent(drawingPos, out tangentRef))
  780. {
  781. isMousePressedOverTangent = true;
  782. dragStart = drawingPos;
  783. draggedTangent = tangentRef;
  784. }
  785. else
  786. ClearSelection();
  787. }
  788. else
  789. {
  790. if (!IsSelected(keyframeRef))
  791. {
  792. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  793. ClearSelection();
  794. SelectKeyframe(keyframeRef);
  795. }
  796. isMousePressedOverKey = true;
  797. dragStart = drawingPos;
  798. }
  799. guiCurveDrawing.Rebuild();
  800. UpdateEventsGUI();
  801. }
  802. else
  803. {
  804. int frameIdx = guiTimeline.GetFrame(pointerPos);
  805. if (frameIdx != -1)
  806. SetMarkedFrame(frameIdx);
  807. else
  808. {
  809. int eventIdx;
  810. if (showEvents && guiEvents.FindEvent(eventPos, out eventIdx))
  811. {
  812. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  813. ClearSelection();
  814. events[eventIdx].selected = true;
  815. UpdateEventsGUI();
  816. }
  817. else
  818. {
  819. ClearSelection();
  820. guiCurveDrawing.Rebuild();
  821. UpdateEventsGUI();
  822. }
  823. }
  824. OnFrameSelected?.Invoke(frameIdx);
  825. }
  826. isPointerHeld = true;
  827. }
  828. else if (ev.Button == PointerButton.Right)
  829. {
  830. Vector2 curveCoord;
  831. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  832. {
  833. contextClickPosition = drawingPos;
  834. KeyframeRef keyframeRef;
  835. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  836. {
  837. ClearSelection();
  838. blankContextMenu.Open(pointerPos, mainPanel);
  839. guiCurveDrawing.Rebuild();
  840. UpdateEventsGUI();
  841. }
  842. else
  843. {
  844. // If clicked outside of current selection, just select the one keyframe
  845. if (!IsSelected(keyframeRef))
  846. {
  847. ClearSelection();
  848. SelectKeyframe(keyframeRef);
  849. guiCurveDrawing.Rebuild();
  850. UpdateEventsGUI();
  851. }
  852. keyframeContextMenu.Open(pointerPos, mainPanel);
  853. }
  854. }
  855. else if (showEvents && guiEvents.GetFrame(eventPos) != -1) // Clicked over events bar
  856. {
  857. contextClickPosition = eventPos;
  858. int eventIdx;
  859. if (!guiEvents.FindEvent(eventPos, out eventIdx))
  860. {
  861. ClearSelection();
  862. blankEventContextMenu.Open(pointerPos, mainPanel);
  863. guiCurveDrawing.Rebuild();
  864. UpdateEventsGUI();
  865. }
  866. else
  867. {
  868. // If clicked outside of current selection, just select the one event
  869. if (!events[eventIdx].selected)
  870. {
  871. ClearSelection();
  872. events[eventIdx].selected = true;
  873. guiCurveDrawing.Rebuild();
  874. UpdateEventsGUI();
  875. }
  876. eventContextMenu.Open(pointerPos, mainPanel);
  877. }
  878. }
  879. }
  880. else if (ev.button == PointerButton.Middle)
  881. {
  882. Vector2 curvePos;
  883. if (WindowToCurveSpace(windowPos, out curvePos))
  884. {
  885. dragStartPos = windowPos;
  886. isMiddlePointerHeld = true;
  887. }
  888. }
  889. }
  890. /// <summary>
  891. /// Handles input. Should be called by the owning window whenever a pointer is double-clicked.
  892. /// </summary>
  893. /// <param name="ev">Object containing pointer press event information.</param>
  894. internal void OnPointerDoubleClicked(PointerEvent ev)
  895. {
  896. if (ev.IsUsed)
  897. return;
  898. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  899. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  900. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  901. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  902. if (!isOverEditor)
  903. return;
  904. Rect2I drawingBounds = drawingPanel.Bounds;
  905. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  906. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out var curveCoord, true))
  907. {
  908. int curveIdx = guiCurveDrawing.FindCurve(drawingPos);
  909. if (curveIdx == -1)
  910. return;
  911. AddKeyframe(curveIdx, curveCoord.x);
  912. }
  913. }
  914. /// <summary>
  915. /// Handles input. Should be called by the owning window whenever a pointer is moved.
  916. /// </summary>
  917. /// <param name="ev">Object containing pointer move event information.</param>
  918. internal void OnPointerMoved(PointerEvent ev)
  919. {
  920. if (ev.Button != PointerButton.Left)
  921. return;
  922. if (isPointerHeld)
  923. {
  924. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  925. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  926. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  927. if (isMousePressedOverKey || isMousePressedOverTangent)
  928. {
  929. Rect2I drawingBounds = drawingPanel.Bounds;
  930. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  931. if (!isDragInProgress)
  932. {
  933. int distance = Vector2I.Distance(drawingPos, dragStart);
  934. if (distance >= DRAG_START_DISTANCE)
  935. {
  936. if (isMousePressedOverKey && !disableCurveEdit)
  937. {
  938. draggedKeyframes.Clear();
  939. foreach (var selectedEntry in selectedKeyframes)
  940. {
  941. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  942. KeyFrame[] keyFrames = curve.KeyFrames;
  943. DraggedKeyframes newEntry = new DraggedKeyframes();
  944. newEntry.curveIdx = selectedEntry.curveIdx;
  945. draggedKeyframes.Add(newEntry);
  946. foreach (var keyframeIdx in selectedEntry.keyIndices)
  947. newEntry.keys.Add(new DraggedKeyframe(keyframeIdx, keyFrames[keyframeIdx]));
  948. }
  949. }
  950. isDragInProgress = true;
  951. }
  952. }
  953. if (isDragInProgress)
  954. {
  955. if (isMousePressedOverKey && !disableCurveEdit)
  956. {
  957. Vector2 diff = Vector2.Zero;
  958. Vector2 dragStartCurve;
  959. if (guiCurveDrawing.PixelToCurveSpace(dragStart, out dragStartCurve, true))
  960. {
  961. Vector2 currentPosCurve;
  962. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  963. diff = currentPosCurve - dragStartCurve;
  964. }
  965. foreach (var draggedEntry in draggedKeyframes)
  966. {
  967. EdAnimationCurve curve = curveInfos[draggedEntry.curveIdx].curve;
  968. for (int i = 0; i < draggedEntry.keys.Count; i++)
  969. {
  970. DraggedKeyframe draggedKey = draggedEntry.keys[i];
  971. float newTime = Math.Max(0.0f, draggedKey.original.time + diff.x);
  972. float newValue = draggedKey.original.value + diff.y;
  973. int newIndex = curve.UpdateKeyframe(draggedKey.index, newTime, newValue);
  974. // It's possible key changed position due to time change, but since we're moving all
  975. // keys at once they cannot change position relative to one another, otherwise we would
  976. // need to update indices for other keys as well.
  977. draggedKey.index = newIndex;
  978. draggedEntry.keys[i] = draggedKey;
  979. }
  980. curve.Apply();
  981. }
  982. // Rebuild selected keys from dragged keys (after potential sorting)
  983. ClearSelection();
  984. foreach (var draggedEntry in draggedKeyframes)
  985. {
  986. foreach (var keyframe in draggedEntry.keys)
  987. SelectKeyframe(new KeyframeRef(draggedEntry.curveIdx, keyframe.index));
  988. }
  989. isModifiedDuringDrag = true;
  990. guiCurveDrawing.Rebuild();
  991. UpdateEventsGUI();
  992. }
  993. else if (isMousePressedOverTangent && !disableCurveEdit)
  994. {
  995. EdAnimationCurve curve = curveInfos[draggedTangent.keyframeRef.curveIdx].curve;
  996. KeyFrame keyframe = curve.KeyFrames[draggedTangent.keyframeRef.keyIdx];
  997. Vector2 keyframeCurveCoords = new Vector2(keyframe.time, keyframe.value);
  998. Vector2 currentPosCurve;
  999. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  1000. {
  1001. Vector2 normal = currentPosCurve - keyframeCurveCoords;
  1002. normal = normal.Normalized;
  1003. float tangent = EdAnimationCurve.NormalToTangent(normal);
  1004. if (draggedTangent.type == TangentType.In)
  1005. {
  1006. if (normal.x > 0.0f)
  1007. tangent = float.PositiveInfinity;
  1008. keyframe.inTangent = -tangent;
  1009. if(curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1010. keyframe.outTangent = -tangent;
  1011. }
  1012. else
  1013. {
  1014. if (normal.x < 0.0f)
  1015. tangent = float.PositiveInfinity;
  1016. keyframe.outTangent = tangent;
  1017. if (curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1018. keyframe.inTangent = tangent;
  1019. }
  1020. curve.KeyFrames[draggedTangent.keyframeRef.keyIdx] = keyframe;
  1021. curve.Apply();
  1022. isModifiedDuringDrag = true;
  1023. guiCurveDrawing.Rebuild();
  1024. }
  1025. }
  1026. }
  1027. }
  1028. else // Move frame marker
  1029. {
  1030. int frameIdx = guiTimeline.GetFrame(pointerPos);
  1031. if (frameIdx != -1)
  1032. SetMarkedFrame(frameIdx);
  1033. OnFrameSelected?.Invoke(frameIdx);
  1034. }
  1035. }
  1036. if (isMiddlePointerHeld)
  1037. {
  1038. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  1039. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1040. if (distance >= DRAG_START_DISTANCE)
  1041. {
  1042. isZoomDragInProgress = true;
  1043. Cursor.Hide();
  1044. Rect2I clipRect;
  1045. clipRect.x = ev.ScreenPos.x - 2;
  1046. clipRect.y = ev.ScreenPos.y - 2;
  1047. clipRect.width = 4;
  1048. clipRect.height = 4;
  1049. Cursor.ClipToRect(clipRect);
  1050. }
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// Handles input. Should be called by the owning window whenever a pointer is released.
  1055. /// </summary>
  1056. /// <param name="ev">Object containing pointer release event information.</param>
  1057. internal void OnPointerReleased(PointerEvent ev)
  1058. {
  1059. if (isZoomDragInProgress)
  1060. {
  1061. Cursor.Show();
  1062. Cursor.ClipDisable();
  1063. }
  1064. if (isModifiedDuringDrag)
  1065. OnCurveModified?.Invoke();
  1066. isMiddlePointerHeld = false;
  1067. isZoomDragInProgress = false;
  1068. isPointerHeld = false;
  1069. isDragInProgress = false;
  1070. isMousePressedOverKey = false;
  1071. isMousePressedOverTangent = false;
  1072. isModifiedDuringDrag = false;
  1073. }
  1074. /// <summary>
  1075. /// Handles input. Should be called by the owning window whenever a button is released.
  1076. /// </summary>
  1077. /// <param name="ev">Object containing button release event information.</param>
  1078. internal void OnButtonUp(ButtonEvent ev)
  1079. {
  1080. if(ev.Button == ButtonCode.Delete)
  1081. DeleteSelectedKeyframes();
  1082. }
  1083. #endregion
  1084. #region Scroll, drag, zoom
  1085. private Vector2I dragStartPos;
  1086. private bool isMiddlePointerHeld;
  1087. private bool isZoomDragInProgress;
  1088. private float zoomAmount;
  1089. /// <summary>
  1090. /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
  1091. /// Should be called every frame.
  1092. /// </summary>
  1093. internal void HandleDragAndZoomInput()
  1094. {
  1095. // Handle middle mouse dragging
  1096. if (isZoomDragInProgress)
  1097. {
  1098. float lengthPerPixel = Range.x / Width;
  1099. float heightPerPixel = Range.y / Height;
  1100. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  1101. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  1102. Vector2 offset = Offset;
  1103. offset.x = Math.Max(0.0f, offset.x + dragX);
  1104. offset.y -= dragY;
  1105. Offset = offset;
  1106. UpdateScrollBarSize();
  1107. UpdateScrollBarPosition();
  1108. }
  1109. // Handle zoom in/out
  1110. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  1111. if (scroll != 0.0f)
  1112. {
  1113. Vector2I windowPos = window.ScreenToWindowPos(Input.PointerPosition);
  1114. Vector2 curvePos;
  1115. if (WindowToCurveSpace(windowPos, out curvePos))
  1116. {
  1117. float zoom = scroll * ZOOM_SCALE;
  1118. Zoom(curvePos, zoom);
  1119. }
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Moves or resizes the vertical scroll bar under the curve editor.
  1124. /// </summary>
  1125. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1126. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1127. private void SetVertScrollbarProperties(float position, float size)
  1128. {
  1129. Vector2 visibleRange = Range;
  1130. Vector2 totalRange = GetTotalRange();
  1131. visibleRange.y = totalRange.y*size;
  1132. Range = visibleRange;
  1133. float scrollableRange = totalRange.y - visibleRange.y;
  1134. Vector2 offset = Offset;
  1135. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  1136. Offset = offset;
  1137. }
  1138. /// <summary>
  1139. /// Moves or resizes the horizontal scroll bar under the curve editor.
  1140. /// </summary>
  1141. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1142. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1143. private void SetHorzScrollbarProperties(float position, float size)
  1144. {
  1145. Vector2 visibleRange = Range;
  1146. Vector2 totalRange = GetTotalRange();
  1147. visibleRange.x = totalRange.x * size;
  1148. Range = visibleRange;
  1149. float scrollableRange = totalRange.x - visibleRange.x;
  1150. Vector2 offset = Offset;
  1151. offset.x = scrollableRange * position;
  1152. Offset = offset;
  1153. }
  1154. /// <summary>
  1155. /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
  1156. /// </summary>
  1157. private void UpdateScrollBarSize()
  1158. {
  1159. Vector2 visibleRange = Range;
  1160. Vector2 totalRange = GetTotalRange();
  1161. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  1162. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  1163. }
  1164. /// <summary>
  1165. /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
  1166. /// </summary>
  1167. private void UpdateScrollBarPosition()
  1168. {
  1169. Vector2 visibleRange = Range;
  1170. Vector2 totalRange = GetTotalRange();
  1171. Vector2 scrollableRange = totalRange - visibleRange;
  1172. Vector2 offset = Offset;
  1173. if (scrollableRange.x > 0.0f)
  1174. horzScrollBar.Position = offset.x / scrollableRange.x;
  1175. else
  1176. horzScrollBar.Position = 0.0f;
  1177. if (scrollableRange.y > 0.0f)
  1178. {
  1179. float pos = offset.y/scrollableRange.y;
  1180. float sign = MathEx.Sign(pos);
  1181. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  1182. pos = (1.0f - pos) /2.0f;
  1183. vertScrollBar.Position = pos;
  1184. }
  1185. else
  1186. vertScrollBar.Position = 0.0f;
  1187. }
  1188. /// <summary>
  1189. /// Calculates the width/height of the curve area depending on the current zoom level.
  1190. /// </summary>
  1191. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1192. private Vector2 GetZoomedRange()
  1193. {
  1194. float zoomLevel = MathEx.Pow(2, zoomAmount);
  1195. Vector2 optimalRange = GetOptimalRange();
  1196. return optimalRange / zoomLevel;
  1197. }
  1198. /// <summary>
  1199. /// Returns the total width/height of the contents of the curve area.
  1200. /// </summary>
  1201. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1202. private Vector2 GetTotalRange()
  1203. {
  1204. // Return optimal range (that covers the visible curve)
  1205. Vector2 optimalRange = GetOptimalRange();
  1206. // Increase range in case user zoomed out
  1207. Vector2 zoomedRange = GetZoomedRange();
  1208. return Vector2.Max(optimalRange, zoomedRange);
  1209. }
  1210. /// <summary>
  1211. /// Zooms in or out at the provided position in the curve display.
  1212. /// </summary>
  1213. /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
  1214. /// (value, time)</param>
  1215. /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
  1216. private void Zoom(Vector2 curvePos, float amount)
  1217. {
  1218. // Increase or decrease the visible range depending on zoom level
  1219. Vector2 oldZoomedRange = GetZoomedRange();
  1220. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  1221. Vector2 zoomedRange = GetZoomedRange();
  1222. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  1223. Vector2 currentRange = Range;
  1224. Vector2 newRange = currentRange + zoomedDiff;
  1225. Range = newRange;
  1226. // When zooming, make sure to focus on the point provided, so adjust the offset
  1227. Vector2 rangeScale = newRange;
  1228. rangeScale.x /= currentRange.x;
  1229. rangeScale.y /= currentRange.y;
  1230. Vector2 relativeCurvePos = curvePos - Offset;
  1231. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  1232. Vector2 diff = newCurvePos - relativeCurvePos;
  1233. Offset -= diff;
  1234. UpdateScrollBarSize();
  1235. UpdateScrollBarPosition();
  1236. }
  1237. /// <summary>
  1238. /// Updates the offset and range of the curve display to fully fit the currently selected set of curves.
  1239. /// </summary>
  1240. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  1241. /// be kept as is.</param>
  1242. internal void CenterAndResize(bool resetTime)
  1243. {
  1244. Vector2 offset, range;
  1245. GetOptimalRangeAndOffset(out offset, out range);
  1246. if (!resetTime)
  1247. {
  1248. offset.x = Offset.x;
  1249. range.x = Range.x;
  1250. }
  1251. Range = range;
  1252. Offset = offset;
  1253. UpdateScrollBarPosition();
  1254. UpdateScrollBarSize();
  1255. }
  1256. /// <summary>
  1257. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1258. /// </summary>
  1259. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1260. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1261. private void OnHorzScrollOrResize(float position, float size)
  1262. {
  1263. SetHorzScrollbarProperties(position, size);
  1264. }
  1265. /// <summary>
  1266. /// Triggered when the user moves or resizes the vertical scrollbar.
  1267. /// </summary>
  1268. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1269. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1270. private void OnVertScrollOrResize(float position, float size)
  1271. {
  1272. SetVertScrollbarProperties(position, size);
  1273. }
  1274. #endregion
  1275. #region Helpers
  1276. /// <summary>
  1277. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1278. /// </summary>
  1279. /// <returns>Width/height of the curve area, in curve space (time, value).</returns>
  1280. private Vector2 GetOptimalRange()
  1281. {
  1282. float xMin, xMax;
  1283. float yMin, yMax;
  1284. CalculateRange(curveInfos, out xMin, out xMax, out yMin, out yMax);
  1285. float xRange = xMax;
  1286. float yRange = Math.Max(Math.Abs(yMin), Math.Abs(yMax));
  1287. // Add padding to y range
  1288. yRange *= 1.05f;
  1289. // Don't allow zero range
  1290. if (xRange == 0.0f)
  1291. xRange = 60.0f;
  1292. if (yRange == 0.0f)
  1293. yRange = 10.0f;
  1294. return new Vector2(xRange, yRange);
  1295. }
  1296. /// <summary>
  1297. /// Returns the offset and range required for fully displaying the currently selected set of curves.
  1298. /// </summary>
  1299. /// <param name="offset">Offset used for centering the curves.</param>
  1300. /// <param name="range">Range representing the width/height in curve space (time, value). </param>
  1301. private void GetOptimalRangeAndOffset(out Vector2 offset, out Vector2 range)
  1302. {
  1303. float xMin, xMax;
  1304. float yMin, yMax;
  1305. CalculateRange(curveInfos, out xMin, out xMax, out yMin, out yMax);
  1306. float xRange = xMax - xMin;
  1307. float yRange = (yMax - yMin) * 0.5f;
  1308. float yOffset = yMin + yRange;
  1309. // Add padding to y range
  1310. yRange *= 1.05f;
  1311. // Don't allow zero range
  1312. if (xRange == 0.0f)
  1313. xRange = 60.0f;
  1314. if (yRange == 0.0f)
  1315. yRange = 10.0f;
  1316. offset = new Vector2(xMin, yOffset);
  1317. range = new Vector2(xRange, yRange);
  1318. }
  1319. /// <summary>
  1320. /// Calculates the total range covered by a set of curves.
  1321. /// </summary>
  1322. /// <param name="curveInfos">Curves to calculate range for.</param>
  1323. /// <param name="xMin">Minimum time value present in the curves.</param>
  1324. /// <param name="xMax">Maximum time value present in the curves.</param>
  1325. /// <param name="yMin">Minimum curve value present in the curves.</param>
  1326. /// <param name="yMax">Maximum curve value present in the curves.</param>
  1327. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xMin, out float xMax, out float yMin,
  1328. out float yMax)
  1329. {
  1330. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  1331. // tangents
  1332. xMin = float.PositiveInfinity;
  1333. xMax = float.NegativeInfinity;
  1334. yMin = float.PositiveInfinity;
  1335. yMax = float.NegativeInfinity;
  1336. foreach (var curveInfo in curveInfos)
  1337. {
  1338. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  1339. foreach (var key in keyframes)
  1340. {
  1341. xMin = Math.Min(xMin, key.time);
  1342. xMax = Math.Max(xMax, key.time);
  1343. yMin = Math.Min(yMin, key.value);
  1344. yMax = Math.Max(yMax, key.value);
  1345. }
  1346. }
  1347. if (xMin == float.PositiveInfinity)
  1348. xMin = 0.0f;
  1349. if (xMax == float.NegativeInfinity)
  1350. xMax = 0.0f;
  1351. if (yMin == float.PositiveInfinity)
  1352. yMin = 0.0f;
  1353. if (yMax == float.NegativeInfinity)
  1354. yMax = 0.0f;
  1355. }
  1356. /// <summary>
  1357. /// Converts coordinate in curve space (time, value) into pixel coordinates relative to the curve drawing area
  1358. /// origin.
  1359. /// </summary>
  1360. /// <param name="curveCoords">Time and value of the location to convert.</param>
  1361. /// <returns>Coordinates relative to curve drawing area's origin, in pixels.</returns>
  1362. public Vector2I CurveToPixelSpace(Vector2 curveCoords)
  1363. {
  1364. return guiCurveDrawing.CurveToPixelSpace(curveCoords);
  1365. }
  1366. /// <summary>
  1367. /// Converts coordinates in window space (relative to the parent window origin) into coordinates in curve space.
  1368. /// </summary>
  1369. /// <param name="windowPos">Coordinates relative to parent editor window, in pixels.</param>
  1370. /// <param name="curveCoord">Curve coordinates within the range as specified by <see cref="Range"/>. Only
  1371. /// valid when function returns true.</param>
  1372. /// <returns>True if the coordinates are within the curve area, false otherwise.</returns>
  1373. public bool WindowToCurveSpace(Vector2I windowPos, out Vector2 curveCoord)
  1374. {
  1375. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  1376. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  1377. Rect2I drawingBounds = drawingPanel.Bounds;
  1378. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  1379. return guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord);
  1380. }
  1381. #endregion
  1382. }
  1383. /// <summary>
  1384. /// Drop down window that displays input boxes used for editing a keyframe.
  1385. /// </summary>
  1386. [DefaultSize(120, 80)]
  1387. internal class KeyframeEditWindow : DropDownWindow
  1388. {
  1389. private Action<bool> closeCallback;
  1390. private bool changesMade;
  1391. /// <summary>
  1392. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1393. /// use.
  1394. /// </summary>
  1395. /// <param name="keyFrame">Keyframe whose properties to edit.</param>
  1396. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1397. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1398. internal void Initialize(KeyFrame keyFrame, Action<KeyFrame> updateCallback, Action<bool> closeCallback)
  1399. {
  1400. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1401. timeField.Value = keyFrame.time;
  1402. timeField.OnChanged += x => { keyFrame.time = x; changesMade = true; updateCallback(keyFrame); };
  1403. GUIFloatField valueField = new GUIFloatField(new LocEdString("Value"), 40, "");
  1404. valueField.Value = keyFrame.value;
  1405. valueField.OnChanged += x => { keyFrame.value = x; changesMade = true; updateCallback(keyFrame); };
  1406. GUILayoutY vertLayout = GUI.AddLayoutY();
  1407. vertLayout.AddFlexibleSpace();
  1408. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1409. horzLayout.AddFlexibleSpace();
  1410. GUILayout contentLayout = horzLayout.AddLayoutY();
  1411. GUILayout timeLayout = contentLayout.AddLayoutX();
  1412. timeLayout.AddSpace(5);
  1413. timeLayout.AddElement(timeField);
  1414. timeLayout.AddFlexibleSpace();
  1415. GUILayout componentLayout = contentLayout.AddLayoutX();
  1416. componentLayout.AddSpace(5);
  1417. componentLayout.AddElement(valueField);
  1418. componentLayout.AddFlexibleSpace();
  1419. horzLayout.AddFlexibleSpace();
  1420. vertLayout.AddFlexibleSpace();
  1421. this.closeCallback = closeCallback;
  1422. }
  1423. private void OnDestroy()
  1424. {
  1425. closeCallback?.Invoke(changesMade);
  1426. }
  1427. }
  1428. /// <summary>
  1429. /// Drop down window that displays input boxes used for editing an event.
  1430. /// </summary>
  1431. [DefaultSize(200, 80)]
  1432. internal class EventEditWindow : DropDownWindow
  1433. {
  1434. private Action<bool> closeCallback;
  1435. private bool changesMade;
  1436. /// <summary>
  1437. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1438. /// use.
  1439. /// </summary>
  1440. /// <param name="animEvent">Event whose properties to edit.</param>
  1441. /// <param name="componentNames">List of component names that the user can select from.</param>
  1442. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1443. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1444. internal void Initialize(AnimationEvent animEvent, string[] componentNames, Action updateCallback,
  1445. Action<bool> closeCallback)
  1446. {
  1447. int selectedIndex = -1;
  1448. string methodName = "";
  1449. if (!string.IsNullOrEmpty(animEvent.name))
  1450. {
  1451. string[] nameEntries = animEvent.name.Split('/');
  1452. if (nameEntries.Length > 1)
  1453. {
  1454. string typeName = nameEntries[0];
  1455. for (int i = 0; i < componentNames.Length; i++)
  1456. {
  1457. if (componentNames[i] == typeName)
  1458. {
  1459. selectedIndex = i;
  1460. break;
  1461. }
  1462. }
  1463. methodName = nameEntries[nameEntries.Length - 1];
  1464. }
  1465. }
  1466. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1467. timeField.Value = animEvent.time;
  1468. timeField.OnChanged += x => { animEvent.time = x; changesMade = true; updateCallback(); };
  1469. GUIListBoxField componentField = new GUIListBoxField(componentNames, new LocEdString("Component"), 40);
  1470. if (selectedIndex != -1)
  1471. componentField.Index = selectedIndex;
  1472. componentField.OnSelectionChanged += x =>
  1473. {
  1474. string compName = "";
  1475. if (x != -1)
  1476. compName = componentNames[x] + "/";
  1477. animEvent.name = compName + x;
  1478. changesMade = true;
  1479. updateCallback();
  1480. };
  1481. GUITextField methodField = new GUITextField(new LocEdString("Method"), 40, false, "", GUIOption.FixedWidth(190));
  1482. methodField.Value = methodName;
  1483. methodField.OnChanged += x =>
  1484. {
  1485. string compName = "";
  1486. if(componentField.Index != -1)
  1487. compName = componentNames[componentField.Index] + "/";
  1488. animEvent.name = compName + x;
  1489. changesMade = true;
  1490. updateCallback();
  1491. };
  1492. GUILayoutY vertLayout = GUI.AddLayoutY();
  1493. vertLayout.AddFlexibleSpace();
  1494. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1495. horzLayout.AddFlexibleSpace();
  1496. GUILayout contentLayout = horzLayout.AddLayoutY();
  1497. GUILayout timeLayout = contentLayout.AddLayoutX();
  1498. timeLayout.AddSpace(5);
  1499. timeLayout.AddElement(timeField);
  1500. timeLayout.AddFlexibleSpace();
  1501. GUILayout componentLayout = contentLayout.AddLayoutX();
  1502. componentLayout.AddSpace(5);
  1503. componentLayout.AddElement(componentField);
  1504. componentLayout.AddFlexibleSpace();
  1505. GUILayout methodLayout = contentLayout.AddLayoutX();
  1506. methodLayout.AddSpace(5);
  1507. methodLayout.AddElement(methodField);
  1508. methodLayout.AddFlexibleSpace();
  1509. horzLayout.AddFlexibleSpace();
  1510. vertLayout.AddFlexibleSpace();
  1511. this.closeCallback = closeCallback;
  1512. }
  1513. private void OnDestroy()
  1514. {
  1515. closeCallback?.Invoke(changesMade);
  1516. }
  1517. }
  1518. /** @} */
  1519. }