暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. filter.NoConnection = false;
  96. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(valueInput, unit.CompatibleValueOutput(valueInput.type)));
  97. }
  98. else if (connectionSource is ValueOutput)
  99. {
  100. var valueOutput = (ValueOutput)connectionSource;
  101. filter.CompatibleInputType = valueOutput.type;
  102. filter.NoConnection = false;
  103. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(valueOutput, unit.CompatibleValueInput(valueOutput.type)));
  104. }
  105. else if (connectionSource is ControlInput)
  106. {
  107. var controlInput = (ControlInput)connectionSource;
  108. filter.NoControlOutput = false;
  109. filter.NoConnection = false;
  110. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(controlInput, unit.controlOutputs.First()));
  111. }
  112. else if (connectionSource is ControlOutput)
  113. {
  114. var controlOutput = (ControlOutput)connectionSource;
  115. filter.NoControlInput = false;
  116. filter.NoConnection = false;
  117. NewUnit(mousePosition, GetNewUnitOptions(filter), (unit) => CompleteContextualConnection(controlOutput, unit.controlInputs.First()));
  118. }
  119. }
  120. #endregion
  121. #region Context
  122. protected override void OnContext()
  123. {
  124. if (isCreatingConnection)
  125. {
  126. CancelConnection();
  127. }
  128. else
  129. {
  130. // Checking for Alt seems to lose focus, for some reason maybe
  131. // unrelated to Bolt. Shift or other modifiers seem to work though.
  132. if (base.GetContextOptions().Any() && (!BoltFlow.Configuration.skipContextMenu || e.shift))
  133. {
  134. base.OnContext();
  135. }
  136. else
  137. {
  138. NewUnit(mousePosition);
  139. }
  140. }
  141. }
  142. protected override IEnumerable<DropdownOption> GetContextOptions()
  143. {
  144. yield return new DropdownOption((Action<Vector2>)(NewUnit), "Add Node...");
  145. yield return new DropdownOption((Action<Vector2>)(NewSticky), "Create Sticky Note");
  146. foreach (var baseOption in base.GetContextOptions())
  147. {
  148. yield return baseOption;
  149. }
  150. }
  151. public void AddUnit(IUnit unit, Vector2 position)
  152. {
  153. UndoUtility.RecordEditedObject("Create Node");
  154. unit.guid = Guid.NewGuid();
  155. unit.position = position.PixelPerfect();
  156. graph.units.Add(unit);
  157. selection.Select(unit);
  158. GUI.changed = true;
  159. }
  160. private UnitOptionTree GetNewUnitOptions(UnitOptionFilter filter)
  161. {
  162. var options = new UnitOptionTree(new GUIContent("Node"));
  163. options.filter = filter;
  164. options.reference = reference;
  165. if (filter.CompatibleOutputType == typeof(object))
  166. {
  167. options.surfaceCommonTypeLiterals = true;
  168. }
  169. return options;
  170. }
  171. private void NewSticky(Vector2 position)
  172. {
  173. UndoUtility.RecordEditedObject("Create Sticky Note");
  174. var stickyNote = new StickyNote() { position = new Rect(position, new Vector2(100, 100)) };
  175. graph.elements.Add(stickyNote);
  176. selection.Select(stickyNote);
  177. GUI.changed = true;
  178. }
  179. private void NewUnit(Vector2 position)
  180. {
  181. var filter = UnitOptionFilter.Any;
  182. filter.GraphHashCode = graph.GetHashCode();
  183. NewUnit(position, GetNewUnitOptions(filter));
  184. }
  185. private void NewUnit(Vector2 unitPosition, UnitOptionTree options, Action<IUnit> then = null)
  186. {
  187. delayCall += () =>
  188. {
  189. var activatorPosition = new Rect(e.mousePosition, new Vector2(200, 1));
  190. var context = this.context;
  191. LudiqGUI.FuzzyDropdown
  192. (
  193. activatorPosition,
  194. options,
  195. null,
  196. delegate (object _option)
  197. {
  198. context.BeginEdit();
  199. if (_option is IUnitOption)
  200. {
  201. var option = (IUnitOption)_option;
  202. var unit = option.InstantiateUnit();
  203. AddUnit(unit, unitPosition);
  204. option.PreconfigureUnit(unit);
  205. then?.Invoke(unit);
  206. GUI.changed = true;
  207. }
  208. else
  209. {
  210. if ((Type)_option == typeof(StickyNote))
  211. {
  212. NewSticky(unitPosition);
  213. }
  214. }
  215. context.EndEdit();
  216. }
  217. );
  218. };
  219. }
  220. #endregion
  221. #region Drag & Drop
  222. private bool CanDetermineDraggedInput(UnityObject uo)
  223. {
  224. if (uo.IsSceneBound())
  225. {
  226. if (reference.self == uo.GameObject())
  227. {
  228. // Because we'll be able to assign it to Self
  229. return true;
  230. }
  231. if (reference.serializedObject.IsSceneBound())
  232. {
  233. // Because we'll be able to use a direct scene reference
  234. return true;
  235. }
  236. return false;
  237. }
  238. else
  239. {
  240. return true;
  241. }
  242. }
  243. public override bool AcceptsDragAndDrop()
  244. {
  245. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  246. {
  247. return FlowDragAndDropUtility.AcceptsScript(graph);
  248. }
  249. return DragAndDropUtility.Is<UnityObject>() && !DragAndDropUtility.Is<IMacro>() && CanDetermineDraggedInput(DragAndDropUtility.Get<UnityObject>())
  250. || EditorVariablesUtility.isDraggingVariable;
  251. }
  252. public override void PerformDragAndDrop()
  253. {
  254. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  255. {
  256. var flowMacro = DragAndDropUtility.Get<ScriptGraphAsset>();
  257. var superUnit = new SubgraphUnit(flowMacro);
  258. AddUnit(superUnit, DragAndDropUtility.position);
  259. }
  260. else if (DragAndDropUtility.Is<UnityObject>())
  261. {
  262. var uo = DragAndDropUtility.Get<UnityObject>();
  263. var type = uo.GetType();
  264. var filter = UnitOptionFilter.Any;
  265. filter.Literals = false;
  266. filter.Expose = false;
  267. var options = GetNewUnitOptions(filter);
  268. var root = new List<object>();
  269. if (!uo.IsSceneBound() || reference.serializedObject.IsSceneBound())
  270. {
  271. if (uo == reference.self)
  272. {
  273. root.Add(new UnitOption<This>(new This()));
  274. }
  275. root.Add(new LiteralOption(new Literal(type, uo)));
  276. }
  277. if (uo is MonoScript script)
  278. {
  279. var scriptType = script.GetClass();
  280. if (scriptType != null)
  281. {
  282. root.Add(scriptType);
  283. }
  284. }
  285. else
  286. {
  287. root.Add(type);
  288. }
  289. if (uo is GameObject)
  290. {
  291. root.AddRange(uo.GetComponents<Component>().Select(c => c.GetType()));
  292. }
  293. options.rootOverride = root.ToArray();
  294. NewUnit(DragAndDropUtility.position, options, (unit) =>
  295. {
  296. // Try to assign a correct input
  297. var compatibleInput = unit.CompatibleValueInput(type);
  298. if (compatibleInput == null)
  299. {
  300. return;
  301. }
  302. if (uo.IsSceneBound())
  303. {
  304. if (reference.self == uo.GameObject())
  305. {
  306. // The component is owned by the same game object as the graph.
  307. if (compatibleInput.nullMeansSelf)
  308. {
  309. compatibleInput.SetDefaultValue(null);
  310. }
  311. else
  312. {
  313. var self = new This();
  314. self.position = unit.position + new Vector2(-150, 19);
  315. graph.units.Add(self);
  316. self.self.ConnectToValid(compatibleInput);
  317. }
  318. }
  319. else if (reference.serializedObject.IsSceneBound())
  320. {
  321. // The component is from another object from the same scene
  322. compatibleInput.SetDefaultValue(uo.ConvertTo(compatibleInput.type));
  323. }
  324. else
  325. {
  326. throw new NotSupportedException("Cannot determine compatible input from dragged Unity object.");
  327. }
  328. }
  329. else
  330. {
  331. compatibleInput.SetDefaultValue(uo.ConvertTo(compatibleInput.type));
  332. }
  333. });
  334. }
  335. else if (EditorVariablesUtility.isDraggingVariable)
  336. {
  337. var kind = EditorVariablesUtility.kind;
  338. var declaration = EditorVariablesUtility.declaration;
  339. UnifiedVariableUnit unit;
  340. if (e.alt)
  341. {
  342. unit = new SetVariable();
  343. }
  344. else if (e.shift)
  345. {
  346. unit = new IsVariableDefined();
  347. }
  348. else
  349. {
  350. unit = new GetVariable();
  351. }
  352. unit.kind = kind;
  353. AddUnit(unit, DragAndDropUtility.position);
  354. unit.name.SetDefaultValue(declaration.name);
  355. }
  356. }
  357. public override void DrawDragAndDropPreview()
  358. {
  359. if (DragAndDropUtility.Is<ScriptGraphAsset>())
  360. {
  361. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, DragAndDropUtility.Get<ScriptGraphAsset>().name, typeof(ScriptGraphAsset).Icon());
  362. }
  363. else if (DragAndDropUtility.Is<GameObject>())
  364. {
  365. var gameObject = DragAndDropUtility.Get<GameObject>();
  366. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, gameObject.name + "...", gameObject.Icon());
  367. }
  368. else if (DragAndDropUtility.Is<UnityObject>())
  369. {
  370. var obj = DragAndDropUtility.Get<UnityObject>();
  371. var type = obj.GetType();
  372. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, type.HumanName() + "...", type.Icon());
  373. }
  374. else if (EditorVariablesUtility.isDraggingVariable)
  375. {
  376. var kind = EditorVariablesUtility.kind;
  377. var name = EditorVariablesUtility.declaration.name;
  378. string label;
  379. if (e.alt)
  380. {
  381. label = $"Set {name}";
  382. }
  383. else if (e.shift)
  384. {
  385. label = $"Check if {name} is defined";
  386. }
  387. else
  388. {
  389. label = $"Get {name}";
  390. }
  391. GraphGUI.DrawDragAndDropPreviewLabel(DragAndDropUtility.offsetedPosition, label, BoltCore.Icons.VariableKind(kind));
  392. }
  393. }
  394. #endregion
  395. #region Drawing
  396. public bool showRelations { get; set; }
  397. #endregion
  398. #region Connection Creation
  399. public IUnitPort connectionSource { get; set; }
  400. public Vector2 connectionEnd { get; set; }
  401. public bool isCreatingConnection => connectionSource != null &&
  402. connectionSource.unit != null; // Make sure the port didn't get destroyed: https://support.ludiq.io/communities/5/topics/4034-x
  403. public void CancelConnection()
  404. {
  405. connectionSource = null;
  406. }
  407. #endregion
  408. }
  409. }