GradientPicker.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //********************************** Banshee Engine (www.banshee4d.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 Windows
  9. * @{
  10. */
  11. /// <summary>
  12. /// A color gradient editor window that allows the user to add or modify colors from a color gradient.
  13. /// </summary>
  14. public class GradientPicker : ModalWindow
  15. {
  16. private int EDITOR_HORZ_PADDING = 10;
  17. private ColorGradient gradient;
  18. private GradientKeyEditor editor;
  19. private GUIColorGradient guiGradient;
  20. private GUICanvas overlayCanvas;
  21. private GUIPanel editorPanel;
  22. private GUIButton guiOK;
  23. private GUIButton guiCancel;
  24. private Action<bool, ColorGradient> closedCallback;
  25. /// <summary>
  26. /// Shows the gradient picker window.
  27. /// </summary>
  28. /// <param name="closedCallback">Optional callback to trigger when the user finishes editing the gradient or
  29. /// cancels out of the dialog.</param>
  30. /// <returns>An instance of the gradient picker window.</returns>
  31. public static GradientPicker Show(Action<bool, ColorGradient> closedCallback = null)
  32. {
  33. GradientPicker picker = new GradientPicker(new ColorGradient(), closedCallback);
  34. return picker;
  35. }
  36. /// <summary>
  37. /// Shows the gradient picker window and sets the initial gradient to show.
  38. /// </summary>
  39. /// <param name="gradient">Gradient to initially display in the window.</param>
  40. /// <param name="closedCallback">Optional callback to trigger when the user finishes editing the gradient or
  41. /// cancels out of the dialog.</param>
  42. /// <returns>A. instance of the gradient picker window.</returns>
  43. public static GradientPicker Show(ColorGradient gradient, Action<bool, ColorGradient> closedCallback = null)
  44. {
  45. GradientPicker picker = new GradientPicker(gradient, closedCallback);
  46. return picker;
  47. }
  48. /// <summary>
  49. /// Constructs a new gradient picker window.
  50. /// </summary>
  51. /// <param name="gradient">Gradient to initially display in the window.</param>
  52. /// <param name="closedCallback">Optional callback to trigger when the user finishes editing the gradient or
  53. /// cancels out of the dialog.</param>
  54. protected GradientPicker(ColorGradient gradient, Action<bool, ColorGradient> closedCallback = null)
  55. : base(false)
  56. {
  57. Title = new LocEdString("Gradient Picker");
  58. Width = 270;
  59. Height = 135;
  60. this.gradient = gradient;
  61. this.closedCallback = closedCallback;
  62. }
  63. private void OnInitialize()
  64. {
  65. guiOK = new GUIButton(new LocEdString("OK"));
  66. guiCancel = new GUIButton(new LocEdString("Cancel"));
  67. guiOK.OnClick += OnOK;
  68. guiCancel.OnClick += OnCancel;
  69. GUILayout mainVertLayout = GUI.AddLayoutY();
  70. mainVertLayout.AddSpace(10);
  71. GUILayout editorHorzLayout = mainVertLayout.AddLayoutX();
  72. editorHorzLayout.AddSpace(EDITOR_HORZ_PADDING);
  73. GUIPanel gradientEditorPanel = editorHorzLayout.AddPanel();
  74. editorHorzLayout.AddSpace(EDITOR_HORZ_PADDING);
  75. mainVertLayout.AddSpace(15);
  76. GUILayout buttonHorzLayout = mainVertLayout.AddLayoutX();
  77. buttonHorzLayout.AddFlexibleSpace();
  78. buttonHorzLayout.AddElement(guiOK);
  79. buttonHorzLayout.AddSpace(10);
  80. buttonHorzLayout.AddElement(guiCancel);
  81. buttonHorzLayout.AddFlexibleSpace();
  82. mainVertLayout.AddFlexibleSpace();
  83. editorPanel = gradientEditorPanel.AddPanel(0);
  84. GUIPanel editorOverlay = gradientEditorPanel.AddPanel(-1);
  85. overlayCanvas = new GUICanvas();
  86. editorOverlay.AddElement(overlayCanvas);
  87. GUILayout editorVertLayout = editorPanel.AddLayoutY();
  88. GUILayout guiGradientLayout = editorVertLayout.AddLayoutX();
  89. guiGradientLayout.AddSpace(GradientKeyEditor.RECT_WIDTH / 2);
  90. guiGradient = new GUIColorGradient();
  91. guiGradient.Gradient = gradient;
  92. guiGradient.SetHeight(30);
  93. guiGradientLayout.AddElement(guiGradient);
  94. guiGradientLayout.AddSpace(GradientKeyEditor.RECT_WIDTH / 2);
  95. editorVertLayout.AddSpace(10);
  96. editor = new GradientKeyEditor(editorVertLayout, gradient.GetKeys(), Width - EDITOR_HORZ_PADDING * 2, 20);
  97. editor.OnGradientModified += colorGradient =>
  98. {
  99. gradient = colorGradient;
  100. guiGradient.Gradient = gradient;
  101. UpdateKeyLines();
  102. };
  103. editorVertLayout.AddFlexibleSpace();
  104. GUITexture containerBg = new GUITexture(null, EditorStylesInternal.ContainerBg);
  105. Rect2I containerBounds = editor.GetBounds(GUI);
  106. containerBounds.x -= 2;
  107. containerBounds.y -= 2;
  108. containerBounds.width += 4;
  109. containerBounds.height += 6;
  110. containerBg.Bounds = containerBounds;
  111. GUIPanel editorUnderlay = GUI.AddPanel(1);
  112. editorUnderlay.AddElement(containerBg);
  113. UpdateKeyLines();
  114. EditorInput.OnPointerPressed += OnPointerPressed;
  115. EditorInput.OnPointerDoubleClick += OnPointerDoubleClicked;
  116. EditorInput.OnPointerMoved += OnPointerMoved;
  117. EditorInput.OnPointerReleased += OnPointerReleased;
  118. EditorInput.OnButtonUp += OnButtonUp;
  119. }
  120. private void OnDestroy()
  121. {
  122. EditorInput.OnPointerPressed -= OnPointerPressed;
  123. EditorInput.OnPointerDoubleClick -= OnPointerDoubleClicked;
  124. EditorInput.OnPointerMoved -= OnPointerMoved;
  125. EditorInput.OnPointerReleased -= OnPointerReleased;
  126. EditorInput.OnButtonUp -= OnButtonUp;
  127. }
  128. /// <summary>
  129. /// Draws lines connecting the individual key color over the gradient itself.
  130. /// </summary>
  131. private void UpdateKeyLines()
  132. {
  133. overlayCanvas.Clear();
  134. ColorGradientKey[] keys = gradient.GetKeys();
  135. for (int i = 0; i < keys.Length; i++)
  136. {
  137. int pixel = editor.TimeToPixel(keys[i].time);
  138. overlayCanvas.DrawLine(new Vector2I(pixel, 0), new Vector2I(pixel, 40), Color.DarkGray);
  139. }
  140. }
  141. /// <summary>
  142. /// Triggered when the user selects a gradient and closes the dialog.
  143. /// </summary>
  144. void OnOK()
  145. {
  146. closedCallback?.Invoke(true, gradient);
  147. Close();
  148. }
  149. /// <summary>
  150. /// Triggered when the user cancels gradient editing and closes the dialog.
  151. /// </summary>
  152. void OnCancel()
  153. {
  154. closedCallback?.Invoke(false, gradient);
  155. Close();
  156. }
  157. #region Input callbacks
  158. /// <summary>
  159. /// Triggered when the user presses a mouse button.
  160. /// </summary>
  161. /// <param name="ev">Information about the mouse press event.</param>
  162. private void OnPointerPressed(PointerEvent ev)
  163. {
  164. if (ev.IsUsed)
  165. return;
  166. editor.OnPointerPressed(ScreenToKeyEditorPos(ev.ScreenPos), ev.Button);
  167. }
  168. /// <summary>
  169. /// Triggered when the user double clicks the left mouse button.
  170. /// </summary>
  171. /// <param name="ev">Information about the mouse event.</param>
  172. private void OnPointerDoubleClicked(PointerEvent ev)
  173. {
  174. if (ev.IsUsed)
  175. return;
  176. Vector2I panelPos = ScreenToKeyEditorPos(ev.ScreenPos);
  177. Rect2I guiGradientBounds = guiGradient.Bounds;
  178. if (guiGradientBounds.Contains(panelPos))
  179. {
  180. Vector2I canvasPos = panelPos - new Vector2I(guiGradientBounds.x, guiGradientBounds.y);
  181. float time = canvasPos.x / (float) Math.Max(guiGradientBounds.width - 1, 1);
  182. if (time >= 0.0f && time <= 1.0f)
  183. {
  184. List<ColorGradientKey> keys = new List<ColorGradientKey>(gradient.GetKeys());
  185. keys.Add(new ColorGradientKey(Color.Black, time));
  186. keys.Sort((lhs, rhs) => lhs.time.CompareTo(rhs.time));
  187. gradient = new ColorGradient(keys.ToArray());
  188. guiGradient.Gradient = gradient;
  189. editor.Rebuild(keys);
  190. UpdateKeyLines();
  191. }
  192. }
  193. else
  194. editor.OnPointerDoubleClicked(panelPos, ev.Button);
  195. }
  196. /// <summary>
  197. /// Triggered when the user moves the mouse.
  198. /// </summary>
  199. /// <param name="ev">Information about the mouse move event.</param>
  200. private void OnPointerMoved(PointerEvent ev)
  201. {
  202. if (ev.IsUsed)
  203. return;
  204. editor.OnPointerMoved(ScreenToKeyEditorPos(ev.ScreenPos), ev.Button);
  205. }
  206. /// <summary>
  207. /// Triggered when the user releases a mouse button.
  208. /// </summary>
  209. /// <param name="ev">Information about the mouse release event.</param>
  210. private void OnPointerReleased(PointerEvent ev)
  211. {
  212. if (ev.IsUsed)
  213. return;
  214. editor.OnPointerReleased(ScreenToKeyEditorPos(ev.ScreenPos));
  215. }
  216. /// <summary>
  217. /// Triggered when the user releases a keyboard button.
  218. /// </summary>
  219. /// <param name="ev">Information about the keyboard release event.</param>
  220. private void OnButtonUp(ButtonEvent ev)
  221. {
  222. editor.OnButtonUp(ev);
  223. }
  224. /// <summary>
  225. /// Converts screen coordinates in coordinates relative to the panel containing the key editor control.
  226. /// </summary>
  227. /// <param name="screenPos">Coordinates in screen space.</param>
  228. /// <returns>Coordinates relative to the key editor control.</returns>
  229. private Vector2I ScreenToKeyEditorPos(Vector2I screenPos)
  230. {
  231. Vector2I windowPos = ScreenToWindowPos(screenPos);
  232. Rect2I elementBounds = GUIUtility.CalculateBounds(editorPanel, GUI);
  233. return windowPos - new Vector2I(elementBounds.x, elementBounds.y);
  234. }
  235. #endregion
  236. /// <summary>
  237. /// Handles drawing and editing of individual keys present on the color gradient.
  238. /// </summary>
  239. public class GradientKeyEditor
  240. {
  241. public const int RECT_WIDTH = 14;
  242. private static readonly Color SELECTED_COLOR = Color.BansheeOrange;
  243. private static readonly Color PLAIN_COLOR = Color.DarkGray;
  244. private const int DRAG_START_DISTANCE = 3;
  245. private GUICanvas canvas;
  246. private List<ColorGradientKey> keys = new List<ColorGradientKey>();
  247. private int width;
  248. private int height;
  249. private int selectedIdx = -1;
  250. private bool isMousePressedOverKey;
  251. private bool isDragInProgress;
  252. private Vector2I dragStart;
  253. /// <summary>
  254. /// Triggered whenever keyframe in a gradient is modified (added, removed or edited).
  255. /// </summary>
  256. public Action<ColorGradient> OnGradientModified;
  257. /// <summary>
  258. /// Constructs a new gradient key editor control.
  259. /// </summary>
  260. /// <param name="parent">GUI layout to attach the child GUI controls to.</param>
  261. /// <param name="keys">Set of keys to initially display on the editor.</param>
  262. /// <param name="width">Width of the editor in pixels.</param>
  263. /// <param name="height">Height of the editor in pixels.</param>
  264. public GradientKeyEditor(GUILayout parent, ColorGradientKey[] keys, int width, int height)
  265. {
  266. canvas = new GUICanvas();
  267. parent.AddElement(canvas);
  268. Rebuild(new List<ColorGradientKey>(keys), width, height);
  269. }
  270. /// <summary>
  271. /// Rebuilds the editor display using the provided color keys.
  272. /// </summary>
  273. /// <param name="keys">Set of keys to initially display on the editor.</param>
  274. public void Rebuild(List<ColorGradientKey> keys)
  275. {
  276. this.keys = keys;
  277. canvas.Clear();
  278. for (int i = 0; i < keys.Count; i++)
  279. DrawColor(keys[i].color, MathEx.Clamp01(keys[i].time), i == selectedIdx);
  280. }
  281. /// <summary>
  282. /// Returns the bounds of the GUI element relative to the provided panel.
  283. /// </summary>
  284. public Rect2I GetBounds(GUIPanel relativeTo)
  285. {
  286. return GUIUtility.CalculateBounds(canvas, relativeTo);
  287. }
  288. /// <summary>
  289. /// Rebuilds the editor display using the provided size and color keys.
  290. /// </summary>
  291. /// <param name="keys">Set of keys to initially display on the editor.</param>
  292. /// <param name="width">Width of the editor in pixels.</param>
  293. /// <param name="height">Height of the editor in pixels.</param>
  294. private void Rebuild(List<ColorGradientKey> keys, int width, int height)
  295. {
  296. this.width = width;
  297. this.height = height;
  298. canvas.SetWidth(width);
  299. canvas.SetHeight(height);
  300. Rebuild(keys);
  301. }
  302. /// <summary>
  303. /// Rebuilds the editor display using the currently set properties.
  304. /// </summary>
  305. private void Rebuild()
  306. {
  307. Rebuild(keys, width, height);
  308. }
  309. /// <summary>
  310. /// Attempts to find a color key rectangle at the specified location.
  311. /// </summary>
  312. /// <param name="pixelCoords">Pixel position to look at, relative to the canvas element.</param>
  313. /// <param name="keyIdx">Index of the color key, if any was found.</param>
  314. /// <returns>True if the key was found under the provided position, false otherwise.</returns>
  315. public bool FindKey(Vector2I pixelCoords, out int keyIdx)
  316. {
  317. keyIdx = -1;
  318. if (pixelCoords.y < 0 || pixelCoords.y >= height)
  319. return false;
  320. for (int i = 0; i < keys.Count; i++)
  321. {
  322. float t = MathEx.Clamp01(keys[i].time);
  323. int x = (int)(t * Math.Max(width - RECT_WIDTH, 0));
  324. if (pixelCoords.x >= x & pixelCoords.x < (x + RECT_WIDTH))
  325. {
  326. keyIdx = i;
  327. return true;
  328. }
  329. }
  330. return false;
  331. }
  332. /// <summary>
  333. /// Handles input. Should be called by the owning window whenever a pointer is pressed.
  334. /// </summary>
  335. /// <param name="panelPos">Position of the pointer relative to the panel parent to this element.</param>
  336. /// <param name="button">Pointer button involved in the event.</param>
  337. internal void OnPointerPressed(Vector2I panelPos, PointerButton button)
  338. {
  339. Rect2I canvasBounds = canvas.Bounds;
  340. Vector2I canvasPos = panelPos - new Vector2I(canvasBounds.x, canvasBounds.y);
  341. if (button == PointerButton.Left)
  342. {
  343. int keyIdx;
  344. if (FindKey(canvasPos, out keyIdx))
  345. {
  346. selectedIdx = keyIdx;
  347. isMousePressedOverKey = true;
  348. dragStart = canvasPos;
  349. }
  350. else
  351. selectedIdx = -1;
  352. Rebuild();
  353. }
  354. }
  355. /// <summary>
  356. /// Handles input. Should be called by the owning window whenever a pointer is double-clicked.
  357. /// </summary>
  358. /// <param name="panelPos">Position of the pointer relative to the panel parent to this element.</param>
  359. /// <param name="button">Pointer button involved in the event.</param>
  360. internal void OnPointerDoubleClicked(Vector2I panelPos, PointerButton button)
  361. {
  362. Rect2I canvasBounds = canvas.Bounds;
  363. if (!canvasBounds.Contains(panelPos))
  364. return;
  365. Vector2I canvasPos = panelPos - new Vector2I(canvasBounds.x, canvasBounds.y);
  366. int keyIdx;
  367. if (FindKey(canvasPos, out keyIdx))
  368. {
  369. ColorPicker.Show(keys[keyIdx].color,
  370. (b, color) =>
  371. {
  372. if (b)
  373. {
  374. ColorGradientKey key = keys[keyIdx];
  375. key.color = color;
  376. keys[keyIdx] = key;
  377. OnGradientModified?.Invoke(new ColorGradient(keys.ToArray()));
  378. Rebuild();
  379. }
  380. });
  381. }
  382. else
  383. {
  384. float time = PixelToTime(canvasPos.x);
  385. if (time >= 0.0f && time <= 1.0f)
  386. {
  387. keys.Add(new ColorGradientKey(Color.Black, time));
  388. keys.Sort((lhs, rhs) => lhs.time.CompareTo(rhs.time));
  389. OnGradientModified?.Invoke(new ColorGradient(keys.ToArray()));
  390. }
  391. Rebuild();
  392. }
  393. }
  394. /// <summary>
  395. /// Handles input. Should be called by the owning window whenever a pointer is moved.
  396. /// </summary>
  397. /// <param name="panelPos">Position of the pointer relative to the panel parent to this element.</param>
  398. /// <param name="button">Pointer button involved in the event.</param>
  399. internal void OnPointerMoved(Vector2I panelPos, PointerButton button)
  400. {
  401. if (button != PointerButton.Left)
  402. return;
  403. if (isMousePressedOverKey)
  404. {
  405. Rect2I canvasBounds = canvas.Bounds;
  406. Vector2I canvasPos = panelPos - new Vector2I(canvasBounds.x, canvasBounds.y);
  407. if (!isDragInProgress)
  408. {
  409. int distance = Vector2I.Distance(canvasPos, dragStart);
  410. if (distance >= DRAG_START_DISTANCE)
  411. isDragInProgress = true;
  412. }
  413. if (isDragInProgress)
  414. {
  415. float time = PixelToTime(canvasPos.x);
  416. if (time >= 0.0f && time <= 1.0f)
  417. {
  418. ColorGradientKey key = keys[selectedIdx];
  419. key.time = time;
  420. keys[selectedIdx] = key;
  421. OnGradientModified?.Invoke(new ColorGradient(keys.ToArray()));
  422. }
  423. Rebuild();
  424. }
  425. }
  426. }
  427. /// <summary>
  428. /// Handles input. Should be called by the owning window whenever a pointer is released.
  429. /// </summary>
  430. /// <param name="panelPos">Position of the pointer relative to the panel parent to this element.</param>
  431. internal void OnPointerReleased(Vector2I panelPos)
  432. {
  433. isDragInProgress = false;
  434. isMousePressedOverKey = false;
  435. }
  436. /// <summary>
  437. /// Handles input. Should be called by the owning window whenever a button is released.
  438. /// </summary>
  439. /// <param name="ev">Object containing button release event information.</param>
  440. internal void OnButtonUp(ButtonEvent ev)
  441. {
  442. if (ev.Button == ButtonCode.Delete && selectedIdx != -1 && !isMousePressedOverKey)
  443. {
  444. if (selectedIdx < keys.Count)
  445. {
  446. keys.RemoveAt(selectedIdx);
  447. OnGradientModified?.Invoke(new ColorGradient(keys.ToArray()));
  448. }
  449. selectedIdx = -1;
  450. Rebuild();
  451. }
  452. }
  453. /** Converts a pixel position over the editor (on x axis) to a time in range [0, 1]. */
  454. internal float PixelToTime(int x)
  455. {
  456. x -= RECT_WIDTH / 2;
  457. return x / (float) Math.Max(this.width - RECT_WIDTH, 0);
  458. }
  459. /** Converts a time in range [0, 1] to a pixel position over the editor (on x axis). */
  460. internal int TimeToPixel(float t)
  461. {
  462. return (int) Math.Min(t * Math.Max(width - RECT_WIDTH, 0), width - RECT_WIDTH - 1) + RECT_WIDTH / 2;
  463. }
  464. /// <summary>
  465. /// Draws a rectangle representing a single color key in the gradient.
  466. /// </summary>
  467. /// <param name="color">Color to display.</param>
  468. /// <param name="t">Time at which to draw the rectangle, in range [0, 1].</param>
  469. /// <param name="selected">True to draw the rectangle as selected, plain otherwise.</param>
  470. private void DrawColor(Color color, float t, bool selected)
  471. {
  472. int x = TimeToPixel(t);
  473. Vector2I a = new Vector2I(x + RECT_WIDTH / 2, 0);
  474. Vector2I b = new Vector2I(x + RECT_WIDTH / 2, height - 1);
  475. Vector2I c = new Vector2I(x - RECT_WIDTH / 2, 0);
  476. Vector2I d = new Vector2I(x - RECT_WIDTH / 2, height - 1);
  477. Vector2I[] linePoints = new Vector2I[] { a, b, d, c, a };
  478. Vector2I[] trianglePoints = new Vector2I[] { a, b, c, d };
  479. Color colorNoAlpha = color;
  480. colorNoAlpha.a = 1.0f;
  481. canvas.DrawTriangleStrip(trianglePoints, colorNoAlpha, 102);
  482. canvas.DrawPolyLine(linePoints, selected ? SELECTED_COLOR : PLAIN_COLOR, 100);
  483. Vector2I alphaA = new Vector2I(x - 1, height - 1);
  484. Vector2I alphaB = new Vector2I(x + RECT_WIDTH / 2, height / 2);
  485. Vector2I alphaC = new Vector2I(x + RECT_WIDTH / 2, height - 1);
  486. canvas.DrawTriangleList(new [] { alphaA, alphaB, alphaC }, Color.White * color.a, 101);
  487. }
  488. };
  489. }
  490. /** @} */
  491. }