FlowCanvas.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEditor;
  5. using UnityEngine;
  6. using UnityObject = UnityEngine.Object;
  7. namespace Unity.VisualScripting
  8. {
  9. [Canvas(typeof(FlowGraph))]
  10. public sealed class FlowCanvas : VisualScriptingCanvas<FlowGraph>
  11. {
  12. public FlowCanvas(FlowGraph graph) : base(graph) { }
  13. #region Clipboard
  14. public override void ShrinkCopyGroup(HashSet<IGraphElement> copyGroup)
  15. {
  16. copyGroup.RemoveWhere(element =>
  17. {
  18. if (element is IUnitConnection)
  19. {
  20. var connection = (IUnitConnection)element;
  21. if (!copyGroup.Contains(connection.source.unit) ||
  22. !copyGroup.Contains(connection.destination.unit))
  23. {
  24. return true;
  25. }
  26. }
  27. return false;
  28. });
  29. }
  30. #endregion
  31. #region Window
  32. public override void OnToolbarGUI()
  33. {
  34. showRelations = GUILayout.Toggle(showRelations, "Relations", LudiqStyles.toolbarButton);
  35. EditorGUI.BeginChangeCheck();
  36. BoltFlow.Configuration.showConnectionValues = GUILayout.Toggle(BoltFlow.Configuration.showConnectionValues, "Values", LudiqStyles.toolbarButton);
  37. BoltCore.Configuration.dimInactiveNodes = GUILayout.Toggle(BoltCore.Configuration.dimInactiveNodes, "Dim", LudiqStyles.toolbarButton);
  38. if (EditorGUI.EndChangeCheck())
  39. {
  40. BoltFlow.Configuration.Save();
  41. BoltCore.Configuration.Save();
  42. }
  43. base.OnToolbarGUI();
  44. }
  45. #endregion
  46. #region View
  47. protected override bool shouldEdgePan => base.shouldEdgePan || isCreatingConnection;
  48. public const float inspectorZoomThreshold = 0.7f;
  49. #endregion
  50. #region Lifecycle
  51. public override void Close()
  52. {
  53. base.Close();
  54. CancelConnection();
  55. }
  56. protected override void HandleHighPriorityInput()
  57. {
  58. if (isCreatingConnection)
  59. {
  60. if (e.IsMouseDown(MouseButton.Left))
  61. {
  62. connectionEnd = mousePosition;
  63. NewUnitContextual();
  64. e.Use();
  65. }
  66. else if (e.IsFree(EventType.KeyDown) && e.keyCode == KeyCode.Escape)
  67. {
  68. CancelConnection();
  69. e.Use();
  70. }
  71. }
  72. base.HandleHighPriorityInput();
  73. }
  74. private void CompleteContextualConnection(IUnitPort source, IUnitPort destination)
  75. {
  76. source.ValidlyConnectTo(destination);
  77. Cache();
  78. var unitPosition = this.Widget<IUnitWidget>(destination.unit).position.position;
  79. var portPosition = this.Widget<IUnitPortWidget>(destination).handlePosition.center.PixelPerfect();
  80. var offset = portPosition - unitPosition;
  81. destination.unit.position -= offset;
  82. this.Widget(destination.unit).Reposition();
  83. connectionSource = null;
  84. GUI.changed = true;
  85. }
  86. public void NewUnitContextual()
  87. {
  88. var filter = UnitOptionFilter.Any;
  89. filter.GraphHashCode = graph.GetHashCode();
  90. if (connectionSource is ValueInput)
  91. {
  92. var valueInput = (ValueInput)connectionSource;
  93. filter.CompatibleOutputType = valueInput.type;
  94. filter.Expose = false;
  95. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(valueInput, unit.CompatibleValueOutput(valueInput.type)));
  96. }
  97. else if (connectionSource is ValueOutput)
  98. {
  99. var valueOutput = (ValueOutput)connectionSource;
  100. filter.CompatibleInputType = valueOutput.type;
  101. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(valueOutput, unit.CompatibleValueInput(valueOutput.type)));
  102. }
  103. else if (connectionSource is ControlInput)
  104. {
  105. var controlInput = (ControlInput)connectionSource;
  106. filter.NoControlOutput = false;
  107. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(controlInput, unit.controlOutputs.First()));
  108. }
  109. else if (connectionSource is ControlOutput)
  110. {
  111. var controlOutput = (ControlOutput)connectionSource;
  112. filter.NoControlInput = false;
  113. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(controlOutput, unit.controlInputs.First()));
  114. }
  115. }
  116. #endregion
  117. #region Context
  118. protected override void OnContext()
  119. {
  120. if (isCreatingConnection)
  121. {
  122. CancelConnection();
  123. }
  124. else
  125. {
  126. // Checking for Alt seems to lose focus, for some reason maybe
  127. // unrelated to Bolt. Shift or other modifiers seem to work though.
  128. if (base.GetContextOptions().Any() && (!BoltFlow.Configuration.skipContextMenu || e.shift))
  129. {
  130. base.OnContext();
  131. }
  132. else
  133. {
  134. NewUnit(mousePosition);
  135. }
  136. }
  137. }
  138. protected override IEnumerable<DropdownOption> GetContextOptions()
  139. {
  140. yield return new DropdownOption((Action<Vector2>)(NewUnit), "Add Node...");
  141. foreach (var baseOption in base.GetContextOptions())
  142. {
  143. yield return baseOption;
  144. }
  145. }
  146. public void AddUnit(IUnit unit, Vector2 position)
  147. {
  148. UndoUtility.RecordEditedObject("Create Node");
  149. unit.guid = Guid.NewGuid();
  150. unit.position = position.PixelPerfect();
  151. graph.units.Add(unit);
  152. selection.Select(unit);
  153. GUI.changed = true;
  154. }
  155. private UnitOptionTree GetNewUnitOptions(UnitOptionFilter filter)
  156. {
  157. var options = new UnitOptionTree(new GUIContent("Node"));
  158. options.filter = filter;
  159. options.reference = reference;
  160. if (filter.CompatibleOutputType == typeof(object))
  161. {
  162. options.surfaceCommonTypeLiterals = true;
  163. }
  164. return options;
  165. }
  166. private void NewUnit(Vector2 position)
  167. {
  168. var filter = UnitOptionFilter.Any;
  169. filter.GraphHashCode = graph.GetHashCode();
  170. NewUnit(position, GetNewUnitOptions(filter));
  171. }
  172. private void NewUnit(Vector2 unitPosition, UnitOptionTree options, Action<IUnit> then = null)
  173. {
  174. delayCall += () =>
  175. {
  176. var activatorPosition = new Rect(e.mousePosition, new Vector2(200, 1));
  177. var context = this.context;
  178. LudiqGUI.FuzzyDropdown
  179. (
  180. activatorPosition,
  181. options,
  182. null,
  183. delegate (object _option)
  184. {
  185. context.BeginEdit();
  186. var option = (IUnitOption)_option;
  187. var unit = option.InstantiateUnit();
  188. AddUnit(unit, unitPosition);
  189. option.PreconfigureUnit(unit);
  190. then?.Invoke(unit);
  191. GUI.changed = true;
  192. context.EndEdit();
  193. }
  194. );
  195. };
  196. }
  197. #endregion
  198. #region Drag & Drop
  199. private bool CanDetermineDraggedInput(UnityObject uo)
  200. {
  201. if (uo.IsSceneBound())
  202. {
  203. if (reference.self == uo.GameObject())
  204. {
  205. // Because we'll be able to assign it to Self
  206. return true;
  207. }
  208. if (reference.serializedObject.IsSceneBound())
  209. {
  210. // Because we'll be able to use a direct scene reference
  211. return true;
  212. }
  213. return false;
  214. }
  215. else
  216. {
  217. return true;
  218. }
  219. }
  220. public override bool AcceptsDragAndDrop()
  221. {
  222. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  223. {
  224. return FlowDragAndDropUtility.AcceptsScript(graph);
  225. }
  226. return DragAndDropUtility.Is<UnityObject>() && !DragAndDropUtility.Is<IMacro>() && CanDetermineDraggedInput(DragAndDropUtility.Get<UnityObject>())
  227. || EditorVariablesUtility.isDraggingVariable;
  228. }
  229. public override void PerformDragAndDrop()
  230. {
  231. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  232. {
  233. var flowMacro = DragAndDropUtility.Get<ScriptGraphAsset>();
  234. var superUnit = new SubgraphUnit(flowMacro);
  235. AddUnit(superUnit, DragAndDropUtility.position);
  236. }
  237. else if (DragAndDropUtility.Is<UnityObject>())
  238. {
  239. var uo = DragAndDropUtility.Get<UnityObject>();
  240. var type = uo.GetType();
  241. var filter = UnitOptionFilter.Any;
  242. filter.Literals = false;
  243. filter.Expose = false;
  244. var options = GetNewUnitOptions(filter);
  245. var root = new List<object>();
  246. if (!uo.IsSceneBound() || reference.serializedObject.IsSceneBound())
  247. {
  248. if (uo == reference.self)
  249. {
  250. root.Add(new UnitOption<This>(new This()));
  251. }
  252. root.Add(new LiteralOption(new Literal(type, uo)));
  253. }
  254. if (uo is MonoScript script)
  255. {
  256. var scriptType = script.GetClass();
  257. if (scriptType != null)
  258. {
  259. root.Add(scriptType);
  260. }
  261. }
  262. else
  263. {
  264. root.Add(type);
  265. }
  266. if (uo is GameObject)
  267. {
  268. root.AddRange(uo.GetComponents<Component>().Select(c => c.GetType()));
  269. }
  270. options.rootOverride = root.ToArray();
  271. NewUnit(DragAndDropUtility.position, options, (unit) =>
  272. {
  273. // Try to assign a correct input
  274. var compatibleInput = unit.CompatibleValueInput(type);
  275. if (compatibleInput == null)
  276. {
  277. return;
  278. }
  279. if (uo.IsSceneBound())
  280. {
  281. if (reference.self == uo.GameObject())
  282. {
  283. // The component is owned by the same game object as the graph.
  284. if (compatibleInput.nullMeansSelf)
  285. {
  286. compatibleInput.SetDefaultValue(null);
  287. }
  288. else
  289. {
  290. var self = new This();
  291. self.position = unit.position + new Vector2(-150, 19);
  292. graph.units.Add(self);
  293. self.self.ConnectToValid(compatibleInput);
  294. }
  295. }
  296. else if (reference.serializedObject.IsSceneBound())
  297. {
  298. // The component is from another object from the same scene
  299. compatibleInput.SetDefaultValue(uo.ConvertTo(compatibleInput.type));
  300. }
  301. else
  302. {
  303. throw new NotSupportedException("Cannot determine compatible input from dragged Unity object.");
  304. }
  305. }
  306. else
  307. {
  308. compatibleInput.SetDefaultValue(uo.ConvertTo(compatibleInput.type));
  309. }
  310. });
  311. }
  312. else if (EditorVariablesUtility.isDraggingVariable)
  313. {
  314. var kind = EditorVariablesUtility.kind;
  315. var declaration = EditorVariablesUtility.declaration;
  316. UnifiedVariableUnit unit;
  317. if (e.alt)
  318. {
  319. unit = new SetVariable();
  320. }
  321. else if (e.shift)
  322. {
  323. unit = new IsVariableDefined();
  324. }
  325. else
  326. {
  327. unit = new GetVariable();
  328. }
  329. unit.kind = kind;
  330. AddUnit(unit, DragAndDropUtility.position);
  331. unit.name.SetDefaultValue(declaration.name);
  332. }
  333. }
  334. public override void DrawDragAndDropPreview()
  335. {
  336. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  337. {
  338. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, DragAndDropUtility.Get<ScriptGraphAsset>().name, typeof(ScriptGraphAsset).Icon());
  339. }
  340. else if (DragAndDropUtility.Is<GameObject>())
  341. {
  342. var gameObject = DragAndDropUtility.Get<GameObject>();
  343. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, gameObject.name + "...", gameObject.Icon());
  344. }
  345. else if (DragAndDropUtility.Is<UnityObject>())
  346. {
  347. var obj = DragAndDropUtility.Get<UnityObject>();
  348. var type = obj.GetType();
  349. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, type.HumanName() + "...", type.Icon());
  350. }
  351. else if (EditorVariablesUtility.isDraggingVariable)
  352. {
  353. var kind = EditorVariablesUtility.kind;
  354. var name = EditorVariablesUtility.declaration.name;
  355. string label;
  356. if (e.alt)
  357. {
  358. label = $"Set {name}";
  359. }
  360. else if (e.shift)
  361. {
  362. label = $"Check if {name} is defined";
  363. }
  364. else
  365. {
  366. label = $"Get {name}";
  367. }
  368. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, label, BoltCore.Icons.VariableKind(kind));
  369. }
  370. }
  371. #endregion
  372. #region Drawing
  373. public bool showRelations { get; set; }
  374. #endregion
  375. #region Connection Creation
  376. public IUnitPort connectionSource { get; set; }
  377. public Vector2 connectionEnd { get; set; }
  378. public bool isCreatingConnection => connectionSource != null &&
  379. connectionSource.unit != null; // Make sure the port didn't get destroyed: https://support.ludiq.io/communities/5/topics/4034-x
  380. public void CancelConnection()
  381. {
  382. connectionSource = null;
  383. }
  384. #endregion
  385. }
  386. }