GUICurveEditor.cs 68 KB

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