GUICurveEditor.cs 66 KB

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