Ingen beskrivning
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.

Flow.cs 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. namespace Unity.VisualScripting
  7. {
  8. public sealed class Flow : IPoolable, IDisposable
  9. {
  10. // We need to check for recursion by passing some additional
  11. // context information to avoid the same port in multiple different
  12. // nested flow graphs to count as the same item. Naively,
  13. // we're using the parent as the context, which seems to work;
  14. // it won't theoretically catch recursive nesting, but then recursive
  15. // nesting already isn't supported anyway, so this way we avoid hashing
  16. // or turning the stack into a reference.
  17. // https://support.ludiq.io/communities/5/topics/2122-r
  18. // We make this an equatable struct to avoid any allocation.
  19. private struct RecursionNode : IEquatable<RecursionNode>
  20. {
  21. public IUnitPort port { get; }
  22. public IGraphParent context { get; }
  23. public RecursionNode(IUnitPort port, GraphPointer pointer)
  24. {
  25. this.port = port;
  26. this.context = pointer.parent;
  27. }
  28. public bool Equals(RecursionNode other)
  29. {
  30. return other.port == port && other.context == context;
  31. }
  32. public override bool Equals(object obj)
  33. {
  34. return obj is RecursionNode other && Equals(other);
  35. }
  36. public override int GetHashCode()
  37. {
  38. return HashUtility.GetHashCode(port, context);
  39. }
  40. }
  41. public GraphStack stack { get; private set; }
  42. private Recursion<RecursionNode> recursion;
  43. private readonly Dictionary<IUnitValuePort, object> locals = new Dictionary<IUnitValuePort, object>();
  44. public readonly VariableDeclarations variables = new VariableDeclarations();
  45. private readonly Stack<int> loops = new Stack<int>();
  46. private readonly HashSet<GraphStack> preservedStacks = new HashSet<GraphStack>();
  47. public MonoBehaviour coroutineRunner { get; private set; }
  48. private ICollection<Flow> activeCoroutinesRegistry;
  49. private bool coroutineStopRequested;
  50. public bool isCoroutine { get; private set; }
  51. private IEnumerator coroutineEnumerator;
  52. public bool isPrediction { get; private set; }
  53. private bool disposed;
  54. public bool enableDebug
  55. {
  56. get
  57. {
  58. if (isPrediction)
  59. {
  60. return false;
  61. }
  62. if (!stack.hasDebugData)
  63. {
  64. return false;
  65. }
  66. return true;
  67. }
  68. }
  69. public static Func<GraphPointer, bool> isInspectedBinding { get; set; }
  70. public bool isInspected => isInspectedBinding?.Invoke(stack) ?? false;
  71. #region Lifecycle
  72. private Flow() { }
  73. public static Flow New(GraphReference reference)
  74. {
  75. Ensure.That(nameof(reference)).IsNotNull(reference);
  76. var flow = GenericPool<Flow>.New(() => new Flow()); ;
  77. flow.stack = reference.ToStackPooled();
  78. return flow;
  79. }
  80. void IPoolable.New()
  81. {
  82. disposed = false;
  83. recursion = Recursion<RecursionNode>.New();
  84. }
  85. public void Dispose()
  86. {
  87. if (disposed)
  88. {
  89. throw new ObjectDisposedException(ToString());
  90. }
  91. GenericPool<Flow>.Free(this);
  92. }
  93. void IPoolable.Free()
  94. {
  95. stack?.Dispose();
  96. recursion?.Dispose();
  97. locals.Clear();
  98. loops.Clear();
  99. variables.Clear();
  100. // Preserved stacks could remain if coroutine was interrupted
  101. foreach (var preservedStack in preservedStacks)
  102. {
  103. preservedStack.Dispose();
  104. }
  105. preservedStacks.Clear();
  106. loopIdentifier = -1;
  107. stack = null;
  108. recursion = null;
  109. isCoroutine = false;
  110. coroutineEnumerator = null;
  111. coroutineRunner = null;
  112. activeCoroutinesRegistry?.Remove(this);
  113. activeCoroutinesRegistry = null;
  114. coroutineStopRequested = false;
  115. isPrediction = false;
  116. disposed = true;
  117. }
  118. public GraphStack PreserveStack()
  119. {
  120. var preservedStack = stack.Clone();
  121. preservedStacks.Add(preservedStack);
  122. return preservedStack;
  123. }
  124. public void RestoreStack(GraphStack stack)
  125. {
  126. this.stack.CopyFrom(stack);
  127. }
  128. public void DisposePreservedStack(GraphStack stack)
  129. {
  130. stack.Dispose();
  131. preservedStacks.Remove(stack);
  132. }
  133. #endregion
  134. #region Loops
  135. public int loopIdentifier = -1;
  136. public int currentLoop
  137. {
  138. get
  139. {
  140. if (loops.Count > 0)
  141. {
  142. return loops.Peek();
  143. }
  144. else
  145. {
  146. return -1;
  147. }
  148. }
  149. }
  150. public bool LoopIsNotBroken(int loop)
  151. {
  152. return currentLoop == loop;
  153. }
  154. public int EnterLoop()
  155. {
  156. var loop = ++loopIdentifier;
  157. loops.Push(loop);
  158. return loop;
  159. }
  160. public void BreakLoop()
  161. {
  162. if (currentLoop < 0)
  163. {
  164. throw new InvalidOperationException("No active loop to break.");
  165. }
  166. loops.Pop();
  167. }
  168. public void ExitLoop(int loop)
  169. {
  170. if (loop != currentLoop)
  171. {
  172. // Already exited through break
  173. return;
  174. }
  175. loops.Pop();
  176. }
  177. #endregion
  178. #region Control
  179. public void Run(ControlOutput port)
  180. {
  181. Invoke(port);
  182. Dispose();
  183. }
  184. public void StartCoroutine(ControlOutput port, ICollection<Flow> registry = null)
  185. {
  186. isCoroutine = true;
  187. coroutineRunner = stack.component;
  188. if (coroutineRunner == null)
  189. {
  190. coroutineRunner = CoroutineRunner.instance;
  191. }
  192. activeCoroutinesRegistry = registry;
  193. activeCoroutinesRegistry?.Add(this);
  194. // We have to store the enumerator because Coroutine itself
  195. // can't be cast to IDisposable, which we'll need when stopping.
  196. coroutineEnumerator = Coroutine(port);
  197. coroutineRunner.StartCoroutine(coroutineEnumerator);
  198. }
  199. public void StopCoroutine(bool disposeInstantly)
  200. {
  201. if (!isCoroutine)
  202. {
  203. throw new NotSupportedException("Stop may only be called on coroutines.");
  204. }
  205. if (disposeInstantly)
  206. {
  207. StopCoroutineImmediate();
  208. }
  209. else
  210. {
  211. // We prefer a soft coroutine stop here that will happen at the *next frame*,
  212. // because we don't want the flow to be disposed just yet when the event node stops
  213. // listening, as we still need it for clean up operations.
  214. coroutineStopRequested = true;
  215. }
  216. }
  217. internal void StopCoroutineImmediate()
  218. {
  219. if (coroutineRunner && coroutineEnumerator != null)
  220. {
  221. coroutineRunner.StopCoroutine(coroutineEnumerator);
  222. // Unity doesn't dispose coroutines enumerators when calling StopCoroutine, so we have to do it manually:
  223. // https://forum.unity.com/threads/finally-block-not-executing-in-a-stopped-coroutine.320611/
  224. ((IDisposable)coroutineEnumerator).Dispose();
  225. }
  226. }
  227. private IEnumerator Coroutine(ControlOutput startPort)
  228. {
  229. try
  230. {
  231. foreach (var instruction in InvokeCoroutine(startPort))
  232. {
  233. if (coroutineStopRequested)
  234. {
  235. yield break;
  236. }
  237. yield return instruction;
  238. if (coroutineStopRequested)
  239. {
  240. yield break;
  241. }
  242. }
  243. }
  244. finally
  245. {
  246. // Manual disposal might have already occurred from StopCoroutine,
  247. // so we have to avoid double disposal, which would throw.
  248. if (!disposed)
  249. {
  250. Dispose();
  251. }
  252. }
  253. }
  254. public void Invoke(ControlOutput output)
  255. {
  256. Ensure.That(nameof(output)).IsNotNull(output);
  257. var connection = output.connection;
  258. if (connection == null)
  259. {
  260. return;
  261. }
  262. var input = connection.destination;
  263. var recursionNode = new RecursionNode(output, stack);
  264. BeforeInvoke(output, recursionNode);
  265. try
  266. {
  267. var nextPort = InvokeDelegate(input);
  268. if (nextPort != null)
  269. {
  270. Invoke(nextPort);
  271. }
  272. }
  273. finally
  274. {
  275. AfterInvoke(output, recursionNode);
  276. }
  277. }
  278. private IEnumerable InvokeCoroutine(ControlOutput output)
  279. {
  280. var connection = output.connection;
  281. if (connection == null)
  282. {
  283. yield break;
  284. }
  285. var input = connection.destination;
  286. var recursionNode = new RecursionNode(output, stack);
  287. BeforeInvoke(output, recursionNode);
  288. if (input.supportsCoroutine)
  289. {
  290. foreach (var instruction in InvokeCoroutineDelegate(input))
  291. {
  292. if (instruction is ControlOutput)
  293. {
  294. foreach (var unwrappedInstruction in InvokeCoroutine((ControlOutput)instruction))
  295. {
  296. yield return unwrappedInstruction;
  297. }
  298. }
  299. else
  300. {
  301. yield return instruction;
  302. }
  303. }
  304. }
  305. else
  306. {
  307. ControlOutput nextPort = InvokeDelegate(input);
  308. if (nextPort != null)
  309. {
  310. foreach (var instruction in InvokeCoroutine(nextPort))
  311. {
  312. yield return instruction;
  313. }
  314. }
  315. }
  316. AfterInvoke(output, recursionNode);
  317. }
  318. private RecursionNode BeforeInvoke(ControlOutput output, RecursionNode recursionNode)
  319. {
  320. try
  321. {
  322. recursion?.Enter(recursionNode);
  323. }
  324. catch (StackOverflowException ex)
  325. {
  326. output.unit.HandleException(stack, ex);
  327. throw;
  328. }
  329. var connection = output.connection;
  330. var input = connection.destination;
  331. if (enableDebug)
  332. {
  333. var connectionEditorData = stack.GetElementDebugData<IUnitConnectionDebugData>(connection);
  334. var inputUnitEditorData = stack.GetElementDebugData<IUnitDebugData>(input.unit);
  335. connectionEditorData.lastInvokeFrame = EditorTimeBinding.frame;
  336. connectionEditorData.lastInvokeTime = EditorTimeBinding.time;
  337. inputUnitEditorData.lastInvokeFrame = EditorTimeBinding.frame;
  338. inputUnitEditorData.lastInvokeTime = EditorTimeBinding.time;
  339. }
  340. return recursionNode;
  341. }
  342. private void AfterInvoke(ControlOutput output, RecursionNode recursionNode)
  343. {
  344. recursion?.Exit(recursionNode);
  345. }
  346. private ControlOutput InvokeDelegate(ControlInput input)
  347. {
  348. try
  349. {
  350. if (input.requiresCoroutine)
  351. {
  352. throw new InvalidOperationException($"Port '{input.key}' on '{input.unit}' can only be triggered in a coroutine.");
  353. }
  354. return input.action(this);
  355. }
  356. catch (Exception ex)
  357. {
  358. input.unit.HandleException(stack, ex);
  359. throw;
  360. }
  361. }
  362. private IEnumerable InvokeCoroutineDelegate(ControlInput input)
  363. {
  364. var instructions = input.coroutineAction(this);
  365. while (true)
  366. {
  367. object instruction;
  368. try
  369. {
  370. if (!instructions.MoveNext())
  371. {
  372. break;
  373. }
  374. instruction = instructions.Current;
  375. }
  376. catch (Exception ex)
  377. {
  378. input.unit.HandleException(stack, ex);
  379. throw;
  380. }
  381. yield return instruction;
  382. }
  383. }
  384. #endregion
  385. #region Values
  386. public bool IsLocal(IUnitValuePort port)
  387. {
  388. Ensure.That(nameof(port)).IsNotNull(port);
  389. return locals.ContainsKey(port);
  390. }
  391. public void SetValue(IUnitValuePort port, object value)
  392. {
  393. Ensure.That(nameof(port)).IsNotNull(port);
  394. Ensure.That(nameof(value)).IsOfType(value, port.type);
  395. if (locals.ContainsKey(port))
  396. {
  397. locals[port] = value;
  398. }
  399. else
  400. {
  401. locals.Add(port, value);
  402. }
  403. }
  404. public object GetValue(ValueInput input)
  405. {
  406. if (locals.TryGetValue(input, out var local))
  407. {
  408. return local;
  409. }
  410. var connection = input.connection;
  411. if (connection != null)
  412. {
  413. if (enableDebug)
  414. {
  415. var connectionEditorData = stack.GetElementDebugData<IUnitConnectionDebugData>(connection);
  416. connectionEditorData.lastInvokeFrame = EditorTimeBinding.frame;
  417. connectionEditorData.lastInvokeTime = EditorTimeBinding.time;
  418. }
  419. var output = connection.source;
  420. var value = GetValue(output);
  421. if (enableDebug)
  422. {
  423. var connectionEditorData = stack.GetElementDebugData<ValueConnection.DebugData>(connection);
  424. connectionEditorData.lastValue = value;
  425. connectionEditorData.assignedLastValue = true;
  426. }
  427. return value;
  428. }
  429. else if (TryGetDefaultValue(input, out var defaultValue))
  430. {
  431. return defaultValue;
  432. }
  433. else
  434. {
  435. throw new MissingValuePortInputException(input.key);
  436. }
  437. }
  438. private object GetValue(ValueOutput output)
  439. {
  440. if (locals.TryGetValue(output, out var local))
  441. {
  442. return local;
  443. }
  444. if (!output.supportsFetch)
  445. {
  446. throw new InvalidOperationException($"The value of '{output.key}' on '{output.unit}' cannot be fetched dynamically, it must be assigned.");
  447. }
  448. var recursionNode = new RecursionNode(output, stack);
  449. try
  450. {
  451. recursion?.Enter(recursionNode);
  452. }
  453. catch (StackOverflowException ex)
  454. {
  455. output.unit.HandleException(stack, ex);
  456. throw;
  457. }
  458. try
  459. {
  460. if (enableDebug)
  461. {
  462. var outputUnitEditorData = stack.GetElementDebugData<IUnitDebugData>(output.unit);
  463. outputUnitEditorData.lastInvokeFrame = EditorTimeBinding.frame;
  464. outputUnitEditorData.lastInvokeTime = EditorTimeBinding.time;
  465. }
  466. var value = GetValueDelegate(output);
  467. return value;
  468. }
  469. finally
  470. {
  471. recursion?.Exit(recursionNode);
  472. }
  473. }
  474. public object GetValue(ValueInput input, Type type)
  475. {
  476. return ConversionUtility.Convert(GetValue(input), type);
  477. }
  478. public T GetValue<T>(ValueInput input)
  479. {
  480. return (T)GetValue(input, typeof(T));
  481. }
  482. public object GetConvertedValue(ValueInput input)
  483. {
  484. return GetValue(input, input.type);
  485. }
  486. private object GetDefaultValue(ValueInput input)
  487. {
  488. if (!TryGetDefaultValue(input, out var defaultValue))
  489. {
  490. throw new InvalidOperationException("Value input port does not have a default value.");
  491. }
  492. return defaultValue;
  493. }
  494. public bool TryGetDefaultValue(ValueInput input, out object defaultValue)
  495. {
  496. if (!input.unit.defaultValues.TryGetValue(input.key, out defaultValue))
  497. {
  498. return false;
  499. }
  500. if (input.nullMeansSelf && defaultValue == null)
  501. {
  502. defaultValue = stack.self;
  503. }
  504. return true;
  505. }
  506. private object GetValueDelegate(ValueOutput output)
  507. {
  508. try
  509. {
  510. return output.getValue(this);
  511. }
  512. catch (Exception ex)
  513. {
  514. output.unit.HandleException(stack, ex);
  515. throw;
  516. }
  517. }
  518. public static object FetchValue(ValueInput input, GraphReference reference)
  519. {
  520. var flow = New(reference);
  521. var result = flow.GetValue(input);
  522. flow.Dispose();
  523. return result;
  524. }
  525. public static object FetchValue(ValueInput input, Type type, GraphReference reference)
  526. {
  527. return ConversionUtility.Convert(FetchValue(input, reference), type);
  528. }
  529. public static T FetchValue<T>(ValueInput input, GraphReference reference)
  530. {
  531. return (T)FetchValue(input, typeof(T), reference);
  532. }
  533. #endregion
  534. #region Value Prediction
  535. public static bool CanPredict(IUnitValuePort port, GraphReference reference)
  536. {
  537. Ensure.That(nameof(port)).IsNotNull(port);
  538. var flow = New(reference);
  539. flow.isPrediction = true;
  540. bool canPredict;
  541. if (port is ValueInput)
  542. {
  543. canPredict = flow.CanPredict((ValueInput)port);
  544. }
  545. else if (port is ValueOutput)
  546. {
  547. canPredict = flow.CanPredict((ValueOutput)port);
  548. }
  549. else
  550. {
  551. throw new NotSupportedException();
  552. }
  553. flow.Dispose();
  554. return canPredict;
  555. }
  556. private bool CanPredict(ValueInput input)
  557. {
  558. if (!input.hasValidConnection)
  559. {
  560. if (!TryGetDefaultValue(input, out var defaultValue))
  561. {
  562. return false;
  563. }
  564. if (typeof(Component).IsAssignableFrom(input.type))
  565. {
  566. defaultValue = defaultValue?.ConvertTo(input.type);
  567. }
  568. if (!input.allowsNull && defaultValue == null)
  569. {
  570. return false;
  571. }
  572. return true;
  573. }
  574. var output = input.validConnectedPorts.Single();
  575. if (!CanPredict(output))
  576. {
  577. return false;
  578. }
  579. var connectedValue = GetValue(output);
  580. if (!ConversionUtility.CanConvert(connectedValue, input.type, false))
  581. {
  582. return false;
  583. }
  584. if (typeof(Component).IsAssignableFrom(input.type))
  585. {
  586. connectedValue = connectedValue?.ConvertTo(input.type);
  587. }
  588. if (!input.allowsNull && connectedValue == null)
  589. {
  590. return false;
  591. }
  592. return true;
  593. }
  594. private bool CanPredict(ValueOutput output)
  595. {
  596. // Shortcircuit the expensive check if the port isn't marked as predictable
  597. if (!output.supportsPrediction)
  598. {
  599. return false;
  600. }
  601. var recursionNode = new RecursionNode(output, stack);
  602. if (!recursion?.TryEnter(recursionNode) ?? false)
  603. {
  604. return false;
  605. }
  606. // Check each value dependency
  607. foreach (var relation in output.unit.relations.WithDestination(output))
  608. {
  609. if (relation.source is ValueInput)
  610. {
  611. var source = (ValueInput)relation.source;
  612. if (!CanPredict(source))
  613. {
  614. recursion?.Exit(recursionNode);
  615. return false;
  616. }
  617. }
  618. }
  619. var value = CanPredictDelegate(output);
  620. recursion?.Exit(recursionNode);
  621. return value;
  622. }
  623. private bool CanPredictDelegate(ValueOutput output)
  624. {
  625. try
  626. {
  627. return output.canPredictValue(this);
  628. }
  629. catch (Exception ex)
  630. {
  631. Debug.LogWarning($"Prediction check failed for '{output.key}' on '{output.unit}':\n{ex}");
  632. return false;
  633. }
  634. }
  635. public static object Predict(IUnitValuePort port, GraphReference reference)
  636. {
  637. Ensure.That(nameof(port)).IsNotNull(port);
  638. var flow = New(reference);
  639. flow.isPrediction = true;
  640. object value;
  641. if (port is ValueInput)
  642. {
  643. value = flow.GetValue((ValueInput)port);
  644. }
  645. else if (port is ValueOutput)
  646. {
  647. value = flow.GetValue((ValueOutput)port);
  648. }
  649. else
  650. {
  651. throw new NotSupportedException();
  652. }
  653. flow.Dispose();
  654. return value;
  655. }
  656. public static object Predict(IUnitValuePort port, GraphReference reference, Type type)
  657. {
  658. return ConversionUtility.Convert(Predict(port, reference), type);
  659. }
  660. public static T Predict<T>(IUnitValuePort port, GraphReference pointer)
  661. {
  662. return (T)Predict(port, pointer, typeof(T));
  663. }
  664. #endregion
  665. }
  666. }