GUICurveEditor.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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 = GUIUtility.CalculateBounds(eventsPanel, window.GUI);
  721. Vector2I windowPos = position + new Vector2I(eventBounds.x, eventBounds.y);
  722. if (eventsSO == null)
  723. return;
  724. Component[] components = eventsSO.GetComponents();
  725. string[] componentNames = new string[components.Length];
  726. for (int i = 0; i < components.Length; i++)
  727. componentNames[i] = components[i].GetType().Name;
  728. EventEditWindow editWindow = DropDownWindow.Open<EventEditWindow>(window, windowPos);
  729. editWindow.Initialize(animEvent, componentNames, () =>
  730. {
  731. UpdateEventsGUI();
  732. },
  733. x =>
  734. {
  735. if(x)
  736. OnEventModified?.Invoke();
  737. });
  738. }
  739. /// <summary>
  740. /// Shows a dialog box that notifies the user that the animation clip is read only.
  741. /// </summary>
  742. private void ShowReadOnlyMessage()
  743. {
  744. LocEdString title = new LocEdString("Warning");
  745. LocEdString message =
  746. new LocEdString("You cannot edit keyframes on animation clips that" +
  747. " are imported from an external file.");
  748. DialogBox.Open(title, message, DialogBox.Type.OK);
  749. }
  750. #region Input
  751. /// <summary>
  752. /// Handles input. Should be called by the owning window whenever a pointer is pressed.
  753. /// </summary>
  754. /// <param name="ev">Object containing pointer press event information.</param>
  755. internal void OnPointerPressed(PointerEvent ev)
  756. {
  757. if (ev.IsUsed)
  758. return;
  759. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  760. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  761. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  762. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  763. if (!isOverEditor)
  764. return;
  765. else
  766. OnClicked?.Invoke();
  767. Rect2I drawingBounds = drawingPanel.Bounds;
  768. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  769. Rect2I eventBounds = eventsPanel.Bounds;
  770. Vector2I eventPos = pointerPos - new Vector2I(eventBounds.x, eventBounds.y);
  771. if (ev.Button == PointerButton.Left)
  772. {
  773. Vector2 curveCoord;
  774. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  775. {
  776. KeyframeRef keyframeRef;
  777. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  778. {
  779. TangentRef tangentRef;
  780. if (guiCurveDrawing.FindTangent(drawingPos, out tangentRef))
  781. {
  782. isMousePressedOverTangent = true;
  783. dragStart = drawingPos;
  784. draggedTangent = tangentRef;
  785. }
  786. else
  787. ClearSelection();
  788. }
  789. else
  790. {
  791. if (!IsSelected(keyframeRef))
  792. {
  793. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  794. ClearSelection();
  795. SelectKeyframe(keyframeRef);
  796. }
  797. isMousePressedOverKey = true;
  798. dragStart = drawingPos;
  799. }
  800. guiCurveDrawing.Rebuild();
  801. UpdateEventsGUI();
  802. }
  803. else
  804. {
  805. int frameIdx = guiTimeline.GetFrame(pointerPos);
  806. if (frameIdx != -1)
  807. SetMarkedFrame(frameIdx);
  808. else
  809. {
  810. int eventIdx;
  811. if (showEvents && guiEvents.FindEvent(eventPos, out eventIdx))
  812. {
  813. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  814. ClearSelection();
  815. events[eventIdx].selected = true;
  816. UpdateEventsGUI();
  817. }
  818. else
  819. {
  820. ClearSelection();
  821. guiCurveDrawing.Rebuild();
  822. UpdateEventsGUI();
  823. }
  824. }
  825. OnFrameSelected?.Invoke(frameIdx);
  826. }
  827. isPointerHeld = true;
  828. }
  829. else if (ev.Button == PointerButton.Right)
  830. {
  831. Vector2 curveCoord;
  832. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  833. {
  834. contextClickPosition = drawingPos;
  835. KeyframeRef keyframeRef;
  836. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  837. {
  838. ClearSelection();
  839. blankContextMenu.Open(pointerPos, mainPanel);
  840. guiCurveDrawing.Rebuild();
  841. UpdateEventsGUI();
  842. }
  843. else
  844. {
  845. // If clicked outside of current selection, just select the one keyframe
  846. if (!IsSelected(keyframeRef))
  847. {
  848. ClearSelection();
  849. SelectKeyframe(keyframeRef);
  850. guiCurveDrawing.Rebuild();
  851. UpdateEventsGUI();
  852. }
  853. keyframeContextMenu.Open(pointerPos, mainPanel);
  854. }
  855. }
  856. else if (showEvents && guiEvents.GetFrame(eventPos) != -1) // Clicked over events bar
  857. {
  858. contextClickPosition = eventPos;
  859. int eventIdx;
  860. if (!guiEvents.FindEvent(eventPos, out eventIdx))
  861. {
  862. ClearSelection();
  863. blankEventContextMenu.Open(pointerPos, mainPanel);
  864. guiCurveDrawing.Rebuild();
  865. UpdateEventsGUI();
  866. }
  867. else
  868. {
  869. // If clicked outside of current selection, just select the one event
  870. if (!events[eventIdx].selected)
  871. {
  872. ClearSelection();
  873. events[eventIdx].selected = true;
  874. guiCurveDrawing.Rebuild();
  875. UpdateEventsGUI();
  876. }
  877. eventContextMenu.Open(pointerPos, mainPanel);
  878. }
  879. }
  880. }
  881. else if (ev.button == PointerButton.Middle)
  882. {
  883. Vector2 curvePos;
  884. if (WindowToCurveSpace(windowPos, out curvePos))
  885. {
  886. dragStartPos = windowPos;
  887. isMiddlePointerHeld = true;
  888. }
  889. }
  890. }
  891. /// <summary>
  892. /// Handles input. Should be called by the owning window whenever a pointer is double-clicked.
  893. /// </summary>
  894. /// <param name="ev">Object containing pointer press event information.</param>
  895. internal void OnPointerDoubleClicked(PointerEvent ev)
  896. {
  897. if (ev.IsUsed)
  898. return;
  899. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  900. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  901. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  902. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  903. if (!isOverEditor)
  904. return;
  905. Rect2I drawingBounds = drawingPanel.Bounds;
  906. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  907. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out var curveCoord, true))
  908. {
  909. int curveIdx = guiCurveDrawing.FindCurve(drawingPos);
  910. if (curveIdx == -1)
  911. return;
  912. AddKeyframe(curveIdx, curveCoord.x);
  913. }
  914. }
  915. /// <summary>
  916. /// Handles input. Should be called by the owning window whenever a pointer is moved.
  917. /// </summary>
  918. /// <param name="ev">Object containing pointer move event information.</param>
  919. internal void OnPointerMoved(PointerEvent ev)
  920. {
  921. if (ev.Button != PointerButton.Left)
  922. return;
  923. if (isPointerHeld)
  924. {
  925. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  926. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  927. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  928. if (isMousePressedOverKey || isMousePressedOverTangent)
  929. {
  930. Rect2I drawingBounds = drawingPanel.Bounds;
  931. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  932. if (!isDragInProgress)
  933. {
  934. int distance = Vector2I.Distance(drawingPos, dragStart);
  935. if (distance >= DRAG_START_DISTANCE)
  936. {
  937. if (isMousePressedOverKey && !disableCurveEdit)
  938. {
  939. draggedKeyframes.Clear();
  940. foreach (var selectedEntry in selectedKeyframes)
  941. {
  942. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  943. KeyFrame[] keyFrames = curve.KeyFrames;
  944. DraggedKeyframes newEntry = new DraggedKeyframes();
  945. newEntry.curveIdx = selectedEntry.curveIdx;
  946. draggedKeyframes.Add(newEntry);
  947. foreach (var keyframeIdx in selectedEntry.keyIndices)
  948. newEntry.keys.Add(new DraggedKeyframe(keyframeIdx, keyFrames[keyframeIdx]));
  949. }
  950. }
  951. isDragInProgress = true;
  952. }
  953. }
  954. if (isDragInProgress)
  955. {
  956. if (isMousePressedOverKey && !disableCurveEdit)
  957. {
  958. Vector2 diff = Vector2.Zero;
  959. Vector2 dragStartCurve;
  960. if (guiCurveDrawing.PixelToCurveSpace(dragStart, out dragStartCurve, true))
  961. {
  962. Vector2 currentPosCurve;
  963. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  964. diff = currentPosCurve - dragStartCurve;
  965. }
  966. foreach (var draggedEntry in draggedKeyframes)
  967. {
  968. EdAnimationCurve curve = curveInfos[draggedEntry.curveIdx].curve;
  969. for (int i = 0; i < draggedEntry.keys.Count; i++)
  970. {
  971. DraggedKeyframe draggedKey = draggedEntry.keys[i];
  972. float newTime = Math.Max(0.0f, draggedKey.original.time + diff.x);
  973. float newValue = draggedKey.original.value + diff.y;
  974. int newIndex = curve.UpdateKeyframe(draggedKey.index, newTime, newValue);
  975. // It's possible key changed position due to time change, but since we're moving all
  976. // keys at once they cannot change position relative to one another, otherwise we would
  977. // need to update indices for other keys as well.
  978. draggedKey.index = newIndex;
  979. draggedEntry.keys[i] = draggedKey;
  980. }
  981. curve.Apply();
  982. }
  983. // Rebuild selected keys from dragged keys (after potential sorting)
  984. ClearSelection();
  985. foreach (var draggedEntry in draggedKeyframes)
  986. {
  987. foreach (var keyframe in draggedEntry.keys)
  988. SelectKeyframe(new KeyframeRef(draggedEntry.curveIdx, keyframe.index));
  989. }
  990. isModifiedDuringDrag = true;
  991. guiCurveDrawing.Rebuild();
  992. UpdateEventsGUI();
  993. }
  994. else if (isMousePressedOverTangent && !disableCurveEdit)
  995. {
  996. EdAnimationCurve curve = curveInfos[draggedTangent.keyframeRef.curveIdx].curve;
  997. KeyFrame keyframe = curve.KeyFrames[draggedTangent.keyframeRef.keyIdx];
  998. Vector2 keyframeCurveCoords = new Vector2(keyframe.time, keyframe.value);
  999. Vector2 currentPosCurve;
  1000. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  1001. {
  1002. Vector2 normal = currentPosCurve - keyframeCurveCoords;
  1003. normal = normal.Normalized;
  1004. float tangent = EdAnimationCurve.NormalToTangent(normal);
  1005. if (draggedTangent.type == TangentType.In)
  1006. {
  1007. if (normal.x > 0.0f)
  1008. tangent = float.PositiveInfinity;
  1009. keyframe.inTangent = -tangent;
  1010. if(curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1011. keyframe.outTangent = -tangent;
  1012. }
  1013. else
  1014. {
  1015. if (normal.x < 0.0f)
  1016. tangent = float.PositiveInfinity;
  1017. keyframe.outTangent = tangent;
  1018. if (curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1019. keyframe.inTangent = tangent;
  1020. }
  1021. curve.KeyFrames[draggedTangent.keyframeRef.keyIdx] = keyframe;
  1022. curve.Apply();
  1023. isModifiedDuringDrag = true;
  1024. guiCurveDrawing.Rebuild();
  1025. }
  1026. }
  1027. }
  1028. }
  1029. else // Move frame marker
  1030. {
  1031. int frameIdx = guiTimeline.GetFrame(pointerPos);
  1032. if (frameIdx != -1)
  1033. SetMarkedFrame(frameIdx);
  1034. OnFrameSelected?.Invoke(frameIdx);
  1035. }
  1036. }
  1037. if (isMiddlePointerHeld)
  1038. {
  1039. Vector2I windowPos = window.ScreenToWindowPos(ev.ScreenPos);
  1040. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1041. if (distance >= DRAG_START_DISTANCE)
  1042. {
  1043. isZoomDragInProgress = true;
  1044. Cursor.Hide();
  1045. Rect2I clipRect;
  1046. clipRect.x = ev.ScreenPos.x - 2;
  1047. clipRect.y = ev.ScreenPos.y - 2;
  1048. clipRect.width = 4;
  1049. clipRect.height = 4;
  1050. Cursor.ClipToRect(clipRect);
  1051. }
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Handles input. Should be called by the owning window whenever a pointer is released.
  1056. /// </summary>
  1057. /// <param name="ev">Object containing pointer release event information.</param>
  1058. internal void OnPointerReleased(PointerEvent ev)
  1059. {
  1060. if (isZoomDragInProgress)
  1061. {
  1062. Cursor.Show();
  1063. Cursor.ClipDisable();
  1064. }
  1065. if (isModifiedDuringDrag)
  1066. OnCurveModified?.Invoke();
  1067. isMiddlePointerHeld = false;
  1068. isZoomDragInProgress = false;
  1069. isPointerHeld = false;
  1070. isDragInProgress = false;
  1071. isMousePressedOverKey = false;
  1072. isMousePressedOverTangent = false;
  1073. isModifiedDuringDrag = false;
  1074. }
  1075. /// <summary>
  1076. /// Handles input. Should be called by the owning window whenever a button is released.
  1077. /// </summary>
  1078. /// <param name="ev">Object containing button release event information.</param>
  1079. internal void OnButtonUp(ButtonEvent ev)
  1080. {
  1081. if(ev.Button == ButtonCode.Delete)
  1082. DeleteSelectedKeyframes();
  1083. }
  1084. #endregion
  1085. #region Scroll, drag, zoom
  1086. private Vector2I dragStartPos;
  1087. private bool isMiddlePointerHeld;
  1088. private bool isZoomDragInProgress;
  1089. private float zoomAmount;
  1090. /// <summary>
  1091. /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
  1092. /// Should be called every frame.
  1093. /// </summary>
  1094. internal void HandleDragAndZoomInput()
  1095. {
  1096. // Handle middle mouse dragging
  1097. if (isZoomDragInProgress)
  1098. {
  1099. float lengthPerPixel = Range.x / Width;
  1100. float heightPerPixel = Range.y / Height;
  1101. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  1102. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  1103. Vector2 offset = Offset;
  1104. offset.x = Math.Max(0.0f, offset.x + dragX);
  1105. offset.y -= dragY;
  1106. Offset = offset;
  1107. UpdateScrollBarSize();
  1108. UpdateScrollBarPosition();
  1109. }
  1110. // Handle zoom in/out
  1111. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  1112. if (scroll != 0.0f)
  1113. {
  1114. Vector2I windowPos = window.ScreenToWindowPos(Input.PointerPosition);
  1115. Vector2 curvePos;
  1116. if (WindowToCurveSpace(windowPos, out curvePos))
  1117. {
  1118. float zoom = scroll * ZOOM_SCALE;
  1119. Zoom(curvePos, zoom);
  1120. }
  1121. }
  1122. }
  1123. /// <summary>
  1124. /// Moves or resizes the vertical scroll bar under the curve editor.
  1125. /// </summary>
  1126. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1127. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1128. private void SetVertScrollbarProperties(float position, float size)
  1129. {
  1130. Vector2 visibleRange = Range;
  1131. Vector2 totalRange = GetTotalRange();
  1132. visibleRange.y = totalRange.y*size;
  1133. Range = visibleRange;
  1134. float scrollableRange = totalRange.y - visibleRange.y;
  1135. Vector2 offset = Offset;
  1136. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  1137. Offset = offset;
  1138. }
  1139. /// <summary>
  1140. /// Moves or resizes the horizontal scroll bar under the curve editor.
  1141. /// </summary>
  1142. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1143. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1144. private void SetHorzScrollbarProperties(float position, float size)
  1145. {
  1146. Vector2 visibleRange = Range;
  1147. Vector2 totalRange = GetTotalRange();
  1148. visibleRange.x = totalRange.x * size;
  1149. Range = visibleRange;
  1150. float scrollableRange = totalRange.x - visibleRange.x;
  1151. Vector2 offset = Offset;
  1152. offset.x = scrollableRange * position;
  1153. Offset = offset;
  1154. }
  1155. /// <summary>
  1156. /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
  1157. /// </summary>
  1158. private void UpdateScrollBarSize()
  1159. {
  1160. Vector2 visibleRange = Range;
  1161. Vector2 totalRange = GetTotalRange();
  1162. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  1163. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  1164. }
  1165. /// <summary>
  1166. /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
  1167. /// </summary>
  1168. private void UpdateScrollBarPosition()
  1169. {
  1170. Vector2 visibleRange = Range;
  1171. Vector2 totalRange = GetTotalRange();
  1172. Vector2 scrollableRange = totalRange - visibleRange;
  1173. Vector2 offset = Offset;
  1174. if (scrollableRange.x > 0.0f)
  1175. horzScrollBar.Position = offset.x / scrollableRange.x;
  1176. else
  1177. horzScrollBar.Position = 0.0f;
  1178. if (scrollableRange.y > 0.0f)
  1179. {
  1180. float pos = offset.y/scrollableRange.y;
  1181. float sign = MathEx.Sign(pos);
  1182. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  1183. pos = (1.0f - pos) /2.0f;
  1184. vertScrollBar.Position = pos;
  1185. }
  1186. else
  1187. vertScrollBar.Position = 0.0f;
  1188. }
  1189. /// <summary>
  1190. /// Calculates the width/height of the curve area depending on the current zoom level.
  1191. /// </summary>
  1192. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1193. private Vector2 GetZoomedRange()
  1194. {
  1195. float zoomLevel = MathEx.Pow(2, zoomAmount);
  1196. Vector2 optimalRange = GetOptimalRange();
  1197. return optimalRange / zoomLevel;
  1198. }
  1199. /// <summary>
  1200. /// Returns the total width/height of the contents of the curve area.
  1201. /// </summary>
  1202. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1203. private Vector2 GetTotalRange()
  1204. {
  1205. // Return optimal range (that covers the visible curve)
  1206. Vector2 optimalRange = GetOptimalRange();
  1207. // Increase range in case user zoomed out
  1208. Vector2 zoomedRange = GetZoomedRange();
  1209. return Vector2.Max(optimalRange, zoomedRange);
  1210. }
  1211. /// <summary>
  1212. /// Zooms in or out at the provided position in the curve display.
  1213. /// </summary>
  1214. /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
  1215. /// (value, time)</param>
  1216. /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
  1217. private void Zoom(Vector2 curvePos, float amount)
  1218. {
  1219. // Increase or decrease the visible range depending on zoom level
  1220. Vector2 oldZoomedRange = GetZoomedRange();
  1221. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  1222. Vector2 zoomedRange = GetZoomedRange();
  1223. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  1224. Vector2 currentRange = Range;
  1225. Vector2 newRange = currentRange + zoomedDiff;
  1226. Range = newRange;
  1227. // When zooming, make sure to focus on the point provided, so adjust the offset
  1228. Vector2 rangeScale = newRange;
  1229. rangeScale.x /= currentRange.x;
  1230. rangeScale.y /= currentRange.y;
  1231. Vector2 relativeCurvePos = curvePos - Offset;
  1232. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  1233. Vector2 diff = newCurvePos - relativeCurvePos;
  1234. Offset -= diff;
  1235. UpdateScrollBarSize();
  1236. UpdateScrollBarPosition();
  1237. }
  1238. /// <summary>
  1239. /// Updates the offset and range of the curve display to fully fit the currently selected set of curves.
  1240. /// </summary>
  1241. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  1242. /// be kept as is.</param>
  1243. internal void CenterAndResize(bool resetTime)
  1244. {
  1245. Vector2 offset, range;
  1246. GetOptimalRangeAndOffset(out offset, out range);
  1247. if (!resetTime)
  1248. {
  1249. offset.x = Offset.x;
  1250. range.x = Range.x;
  1251. }
  1252. Range = range;
  1253. Offset = offset;
  1254. UpdateScrollBarPosition();
  1255. UpdateScrollBarSize();
  1256. }
  1257. /// <summary>
  1258. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1259. /// </summary>
  1260. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1261. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1262. private void OnHorzScrollOrResize(float position, float size)
  1263. {
  1264. SetHorzScrollbarProperties(position, size);
  1265. }
  1266. /// <summary>
  1267. /// Triggered when the user moves or resizes the vertical scrollbar.
  1268. /// </summary>
  1269. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1270. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1271. private void OnVertScrollOrResize(float position, float size)
  1272. {
  1273. SetVertScrollbarProperties(position, size);
  1274. }
  1275. #endregion
  1276. #region Helpers
  1277. /// <summary>
  1278. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1279. /// </summary>
  1280. /// <returns>Width/height of the curve area, in curve space (time, value).</returns>
  1281. private Vector2 GetOptimalRange()
  1282. {
  1283. float xMin, xMax;
  1284. float yMin, yMax;
  1285. CalculateRange(curveInfos, out xMin, out xMax, out yMin, out yMax);
  1286. float xRange = xMax;
  1287. float yRange = Math.Max(Math.Abs(yMin), Math.Abs(yMax));
  1288. // Add padding to y range
  1289. yRange *= 1.05f;
  1290. // Don't allow zero range
  1291. if (xRange == 0.0f)
  1292. xRange = 60.0f;
  1293. if (yRange == 0.0f)
  1294. yRange = 10.0f;
  1295. return new Vector2(xRange, yRange);
  1296. }
  1297. /// <summary>
  1298. /// Returns the offset and range required for fully displaying the currently selected set of curves.
  1299. /// </summary>
  1300. /// <param name="offset">Offset used for centering the curves.</param>
  1301. /// <param name="range">Range representing the width/height in curve space (time, value). </param>
  1302. private void GetOptimalRangeAndOffset(out Vector2 offset, out Vector2 range)
  1303. {
  1304. float xMin, xMax;
  1305. float yMin, yMax;
  1306. CalculateRange(curveInfos, out xMin, out xMax, out yMin, out yMax);
  1307. float xRange = xMax - xMin;
  1308. float yRange = (yMax - yMin) * 0.5f;
  1309. float yOffset = yMin + yRange;
  1310. // Add padding to y range
  1311. yRange *= 1.05f;
  1312. // Don't allow zero range
  1313. if (xRange == 0.0f)
  1314. xRange = 60.0f;
  1315. if (yRange == 0.0f)
  1316. yRange = 10.0f;
  1317. offset = new Vector2(xMin, yOffset);
  1318. range = new Vector2(xRange, yRange);
  1319. }
  1320. /// <summary>
  1321. /// Calculates the total range covered by a set of curves.
  1322. /// </summary>
  1323. /// <param name="curveInfos">Curves to calculate range for.</param>
  1324. /// <param name="xMin">Minimum time value present in the curves.</param>
  1325. /// <param name="xMax">Maximum time value present in the curves.</param>
  1326. /// <param name="yMin">Minimum curve value present in the curves.</param>
  1327. /// <param name="yMax">Maximum curve value present in the curves.</param>
  1328. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xMin, out float xMax, out float yMin,
  1329. out float yMax)
  1330. {
  1331. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  1332. // tangents
  1333. xMin = float.PositiveInfinity;
  1334. xMax = float.NegativeInfinity;
  1335. yMin = float.PositiveInfinity;
  1336. yMax = float.NegativeInfinity;
  1337. foreach (var curveInfo in curveInfos)
  1338. {
  1339. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  1340. foreach (var key in keyframes)
  1341. {
  1342. xMin = Math.Min(xMin, key.time);
  1343. xMax = Math.Max(xMax, key.time);
  1344. yMin = Math.Min(yMin, key.value);
  1345. yMax = Math.Max(yMax, key.value);
  1346. }
  1347. }
  1348. if (xMin == float.PositiveInfinity)
  1349. xMin = 0.0f;
  1350. if (xMax == float.NegativeInfinity)
  1351. xMax = 0.0f;
  1352. if (yMin == float.PositiveInfinity)
  1353. yMin = 0.0f;
  1354. if (yMax == float.NegativeInfinity)
  1355. yMax = 0.0f;
  1356. }
  1357. /// <summary>
  1358. /// Converts coordinate in curve space (time, value) into pixel coordinates relative to the curve drawing area
  1359. /// origin.
  1360. /// </summary>
  1361. /// <param name="curveCoords">Time and value of the location to convert.</param>
  1362. /// <returns>Coordinates relative to curve drawing area's origin, in pixels.</returns>
  1363. public Vector2I CurveToPixelSpace(Vector2 curveCoords)
  1364. {
  1365. return guiCurveDrawing.CurveToPixelSpace(curveCoords);
  1366. }
  1367. /// <summary>
  1368. /// Converts coordinates in window space (relative to the parent window origin) into coordinates in curve space.
  1369. /// </summary>
  1370. /// <param name="windowPos">Coordinates relative to parent editor window, in pixels.</param>
  1371. /// <param name="curveCoord">Curve coordinates within the range as specified by <see cref="Range"/>. Only
  1372. /// valid when function returns true.</param>
  1373. /// <returns>True if the coordinates are within the curve area, false otherwise.</returns>
  1374. public bool WindowToCurveSpace(Vector2I windowPos, out Vector2 curveCoord)
  1375. {
  1376. Rect2I elementBounds = GUIUtility.CalculateBounds(mainPanel, window.GUI);
  1377. Vector2I pointerPos = windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  1378. Rect2I drawingBounds = drawingPanel.Bounds;
  1379. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  1380. return guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord);
  1381. }
  1382. #endregion
  1383. }
  1384. /// <summary>
  1385. /// Drop down window that displays input boxes used for editing a keyframe.
  1386. /// </summary>
  1387. [DefaultSize(120, 80)]
  1388. internal class KeyframeEditWindow : DropDownWindow
  1389. {
  1390. private Action<bool> closeCallback;
  1391. private bool changesMade;
  1392. /// <summary>
  1393. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1394. /// use.
  1395. /// </summary>
  1396. /// <param name="keyFrame">Keyframe whose properties to edit.</param>
  1397. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1398. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1399. internal void Initialize(KeyFrame keyFrame, Action<KeyFrame> updateCallback, Action<bool> closeCallback)
  1400. {
  1401. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1402. timeField.Value = keyFrame.time;
  1403. timeField.OnChanged += x => { keyFrame.time = x; changesMade = true; updateCallback(keyFrame); };
  1404. GUIFloatField valueField = new GUIFloatField(new LocEdString("Value"), 40, "");
  1405. valueField.Value = keyFrame.value;
  1406. valueField.OnChanged += x => { keyFrame.value = x; changesMade = true; updateCallback(keyFrame); };
  1407. GUILayoutY vertLayout = GUI.AddLayoutY();
  1408. vertLayout.AddFlexibleSpace();
  1409. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1410. horzLayout.AddFlexibleSpace();
  1411. GUILayout contentLayout = horzLayout.AddLayoutY();
  1412. GUILayout timeLayout = contentLayout.AddLayoutX();
  1413. timeLayout.AddSpace(5);
  1414. timeLayout.AddElement(timeField);
  1415. timeLayout.AddFlexibleSpace();
  1416. GUILayout componentLayout = contentLayout.AddLayoutX();
  1417. componentLayout.AddSpace(5);
  1418. componentLayout.AddElement(valueField);
  1419. componentLayout.AddFlexibleSpace();
  1420. horzLayout.AddFlexibleSpace();
  1421. vertLayout.AddFlexibleSpace();
  1422. this.closeCallback = closeCallback;
  1423. }
  1424. private void OnDestroy()
  1425. {
  1426. closeCallback?.Invoke(changesMade);
  1427. }
  1428. }
  1429. /// <summary>
  1430. /// Drop down window that displays input boxes used for editing an event.
  1431. /// </summary>
  1432. [DefaultSize(200, 80)]
  1433. internal class EventEditWindow : DropDownWindow
  1434. {
  1435. private Action<bool> closeCallback;
  1436. private bool changesMade;
  1437. /// <summary>
  1438. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1439. /// use.
  1440. /// </summary>
  1441. /// <param name="animEvent">Event whose properties to edit.</param>
  1442. /// <param name="componentNames">List of component names that the user can select from.</param>
  1443. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1444. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1445. internal void Initialize(AnimationEvent animEvent, string[] componentNames, Action updateCallback,
  1446. Action<bool> closeCallback)
  1447. {
  1448. int selectedIndex = -1;
  1449. string methodName = "";
  1450. if (!string.IsNullOrEmpty(animEvent.name))
  1451. {
  1452. string[] nameEntries = animEvent.name.Split('/');
  1453. if (nameEntries.Length > 1)
  1454. {
  1455. string typeName = nameEntries[0];
  1456. for (int i = 0; i < componentNames.Length; i++)
  1457. {
  1458. if (componentNames[i] == typeName)
  1459. {
  1460. selectedIndex = i;
  1461. break;
  1462. }
  1463. }
  1464. methodName = nameEntries[nameEntries.Length - 1];
  1465. }
  1466. }
  1467. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1468. timeField.Value = animEvent.time;
  1469. timeField.OnChanged += x => { animEvent.time = x; changesMade = true; updateCallback(); };
  1470. GUIListBoxField componentField = new GUIListBoxField(componentNames, new LocEdString("Component"), 40);
  1471. if (selectedIndex != -1)
  1472. componentField.Index = selectedIndex;
  1473. componentField.OnSelectionChanged += x =>
  1474. {
  1475. string compName = "";
  1476. if (x != -1)
  1477. compName = componentNames[x] + "/";
  1478. animEvent.name = compName + x;
  1479. changesMade = true;
  1480. updateCallback();
  1481. };
  1482. GUITextField methodField = new GUITextField(new LocEdString("Method"), 40, false, "", GUIOption.FixedWidth(190));
  1483. methodField.Value = methodName;
  1484. methodField.OnChanged += x =>
  1485. {
  1486. string compName = "";
  1487. if(componentField.Index != -1)
  1488. compName = componentNames[componentField.Index] + "/";
  1489. animEvent.name = compName + x;
  1490. changesMade = true;
  1491. updateCallback();
  1492. };
  1493. GUILayoutY vertLayout = GUI.AddLayoutY();
  1494. vertLayout.AddFlexibleSpace();
  1495. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1496. horzLayout.AddFlexibleSpace();
  1497. GUILayout contentLayout = horzLayout.AddLayoutY();
  1498. GUILayout timeLayout = contentLayout.AddLayoutX();
  1499. timeLayout.AddSpace(5);
  1500. timeLayout.AddElement(timeField);
  1501. timeLayout.AddFlexibleSpace();
  1502. GUILayout componentLayout = contentLayout.AddLayoutX();
  1503. componentLayout.AddSpace(5);
  1504. componentLayout.AddElement(componentField);
  1505. componentLayout.AddFlexibleSpace();
  1506. GUILayout methodLayout = contentLayout.AddLayoutX();
  1507. methodLayout.AddSpace(5);
  1508. methodLayout.AddElement(methodField);
  1509. methodLayout.AddFlexibleSpace();
  1510. horzLayout.AddFlexibleSpace();
  1511. vertLayout.AddFlexibleSpace();
  1512. this.closeCallback = closeCallback;
  1513. }
  1514. private void OnDestroy()
  1515. {
  1516. closeCallback?.Invoke(changesMade);
  1517. }
  1518. }
  1519. /** @} */
  1520. }