NodeEditorGUILayout.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using UnityEditor;
  6. using UnityEditorInternal;
  7. using UnityEngine;
  8. using XNode;
  9. using Object = UnityEngine.Object;
  10. namespace XNodeEditor
  11. {
  12. /// <summary> xNode-specific version of <see cref="EditorGUILayout"/> </summary>
  13. public static class NodeEditorGUILayout
  14. {
  15. private static readonly Dictionary<Object, Dictionary<string, ReorderableList>> reorderableListCache
  16. = new Dictionary<Object, Dictionary<string, ReorderableList>>();
  17. private static int reorderableListIndex = -1;
  18. /// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
  19. public static void PropertyField(SerializedProperty property, Node rootNode, bool includeChildren = true,
  20. params GUILayoutOption[] options)
  21. {
  22. PropertyField(property, rootNode, (GUIContent)null, includeChildren, options);
  23. }
  24. /// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
  25. public static void PropertyField(SerializedProperty property, Node rootNode, GUIContent label, bool includeChildren = true,
  26. params GUILayoutOption[] options)
  27. {
  28. if (property == null) throw new NullReferenceException();
  29. Node node = property.serializedObject.targetObject as Node;
  30. NodePort port = node.GetPort(property.name);
  31. PropertyField(property, rootNode, label, port, includeChildren);
  32. }
  33. /// <summary> Make a field for a serialized property. Manual node port override. </summary>
  34. public static void PropertyField(SerializedProperty property, Node rootNode, NodePort port, bool includeChildren = true,
  35. params GUILayoutOption[] options)
  36. {
  37. PropertyField(property, rootNode, null, port, includeChildren, options);
  38. }
  39. /// <summary> Make a field for a serialized property. Manual node port override. </summary>
  40. public static void PropertyField(SerializedProperty property, Node rootNode, GUIContent label, NodePort port,
  41. bool includeChildren = true, params GUILayoutOption[] options)
  42. {
  43. if (property == null) throw new NullReferenceException();
  44. // If property is not a port, display a regular property field
  45. if (port == null)
  46. {
  47. if (rootNode != null)
  48. {
  49. string showName = property.name;
  50. string tooltip = "";
  51. Node.NodeSerializeAttribute nodeSerializeAttribute;
  52. // Node.DisabledAttribute disabledAttribute;
  53. // NodeEditorUtilities.GetAttrib(rootNode.GetType(), property.name, out disabledAttribute);
  54. NodeEditorUtilities.GetAttrib(rootNode.GetType(), property.name, out nodeSerializeAttribute);
  55. if (nodeSerializeAttribute != null)
  56. {
  57. if (nodeSerializeAttribute.isDisable)
  58. {
  59. EditorGUI.BeginDisabledGroup(true);
  60. }
  61. else
  62. {
  63. EditorGUI.EndDisabledGroup();
  64. }
  65. showName = nodeSerializeAttribute.showName;
  66. tooltip = nodeSerializeAttribute.tooltip;
  67. if (nodeSerializeAttribute.showType == 0)
  68. {
  69. GUILayout.BeginHorizontal();
  70. EditorGUILayout.PropertyField(property, new GUIContent(showName, tooltip), includeChildren,
  71. GUILayout.MinWidth(30));
  72. GUILayout.EndHorizontal();
  73. }
  74. else if (nodeSerializeAttribute.showType == 1)
  75. {
  76. EditorGUILayout.LabelField(showName, property.intValue.ToString());
  77. }
  78. if (nodeSerializeAttribute.isDisable)
  79. {
  80. EditorGUI.EndDisabledGroup();
  81. }
  82. }
  83. else
  84. {
  85. EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
  86. }
  87. }
  88. }
  89. else
  90. {
  91. Rect rect = new Rect();
  92. List<PropertyAttribute> propertyAttributes =
  93. NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
  94. Node.NodeSerializeAttribute serializeAttribute;
  95. NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out serializeAttribute);
  96. // If property is an input, display a regular property field and put a port handle on the left side
  97. if (port.direction == NodePort.IO.Input)
  98. {
  99. // Get data from [Input] attribute
  100. Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
  101. Node.InputAttribute inputAttribute;
  102. bool dynamicPortList = false;
  103. if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
  104. {
  105. dynamicPortList = inputAttribute.dynamicPortList;
  106. showBacking = inputAttribute.backingValue;
  107. }
  108. bool usePropertyAttributes = dynamicPortList ||
  109. showBacking == Node.ShowBackingValue.Never ||
  110. (showBacking == Node.ShowBackingValue.Unconnected &&
  111. port.IsConnected);
  112. float spacePadding = 0;
  113. foreach (var attr in propertyAttributes)
  114. {
  115. if (attr is SpaceAttribute)
  116. {
  117. if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
  118. else spacePadding += (attr as SpaceAttribute).height;
  119. }
  120. else if (attr is HeaderAttribute)
  121. {
  122. if (usePropertyAttributes)
  123. {
  124. //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
  125. Rect position = GUILayoutUtility.GetRect(0,
  126. (EditorGUIUtility.singleLineHeight * 1.5f) -
  127. EditorGUIUtility
  128. .standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
  129. position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
  130. position = EditorGUI.IndentedRect(position);
  131. GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
  132. }
  133. else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
  134. }
  135. }
  136. if (dynamicPortList)
  137. {
  138. Type type = GetType(property);
  139. Node.ConnectionType connectionType = inputAttribute != null
  140. ? inputAttribute.connectionType
  141. : Node.ConnectionType.Multiple;
  142. string showName = serializeAttribute != null ? serializeAttribute.showName : property.name;
  143. DynamicPortList(showName, type, property.serializedObject, port.direction, connectionType);
  144. return;
  145. }
  146. switch (showBacking)
  147. {
  148. case Node.ShowBackingValue.Unconnected:
  149. // Display a label if port is connected
  150. if (port.IsConnected)
  151. EditorGUILayout.LabelField(label != null
  152. ? label
  153. : new GUIContent(property.displayName));
  154. // Display an editable property field if port is not connected
  155. else
  156. EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
  157. break;
  158. case Node.ShowBackingValue.Never:
  159. // Display a label
  160. EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
  161. break;
  162. case Node.ShowBackingValue.Always:
  163. // Display an editable property field
  164. EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
  165. break;
  166. }
  167. rect = GUILayoutUtility.GetLastRect();
  168. rect.position = rect.position - new Vector2(16, -spacePadding);
  169. // If property is an output, display a text label and put a port handle on the right side
  170. }
  171. else if (port.direction == NodePort.IO.Output)
  172. {
  173. // Get data from [Output] attribute
  174. Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
  175. Node.OutputAttribute outputAttribute;
  176. bool dynamicPortList = false;
  177. if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
  178. {
  179. dynamicPortList = outputAttribute.dynamicPortList;
  180. showBacking = outputAttribute.backingValue;
  181. }
  182. bool usePropertyAttributes = dynamicPortList ||
  183. showBacking == Node.ShowBackingValue.Never ||
  184. (showBacking == Node.ShowBackingValue.Unconnected &&
  185. port.IsConnected);
  186. float spacePadding = 0;
  187. foreach (var attr in propertyAttributes)
  188. {
  189. if (attr is SpaceAttribute)
  190. {
  191. if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
  192. else spacePadding += (attr as SpaceAttribute).height;
  193. }
  194. else if (attr is HeaderAttribute)
  195. {
  196. if (usePropertyAttributes)
  197. {
  198. //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
  199. Rect position = GUILayoutUtility.GetRect(0,
  200. (EditorGUIUtility.singleLineHeight * 1.5f) -
  201. EditorGUIUtility
  202. .standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
  203. position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
  204. position = EditorGUI.IndentedRect(position);
  205. GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
  206. }
  207. else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
  208. }
  209. }
  210. if (dynamicPortList)
  211. {
  212. Type type = GetType(property);
  213. Node.ConnectionType connectionType = outputAttribute != null
  214. ? outputAttribute.connectionType
  215. : Node.ConnectionType.Multiple;
  216. string showName = serializeAttribute != null ? serializeAttribute.showName : property.name;
  217. DynamicPortList(showName, type, property.serializedObject, port.direction, connectionType);
  218. return;
  219. }
  220. switch (showBacking)
  221. {
  222. case Node.ShowBackingValue.Unconnected:
  223. // Display a label if port is connected
  224. if (port.IsConnected)
  225. EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName),
  226. NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
  227. // Display an editable property field if port is not connected
  228. else
  229. EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
  230. break;
  231. case Node.ShowBackingValue.Never:
  232. // Display a label
  233. EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName),
  234. NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
  235. break;
  236. case Node.ShowBackingValue.Always:
  237. // Display an editable property field
  238. EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
  239. break;
  240. }
  241. rect = GUILayoutUtility.GetLastRect();
  242. rect.position = rect.position + new Vector2(rect.width, spacePadding);
  243. }
  244. rect.size = new Vector2(16, 16);
  245. NodeEditor editor = NodeEditor.GetEditor(port.node, NodeEditorWindow.current);
  246. Color backgroundColor = editor.GetTint();
  247. Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port);
  248. DrawPortHandle(rect, backgroundColor, col);
  249. // Register the handle position
  250. Vector2 portPos = rect.center;
  251. NodeEditor.portPositions[port] = portPos;
  252. }
  253. }
  254. private static Type GetType(SerializedProperty property)
  255. {
  256. Type parentType = property.serializedObject.targetObject.GetType();
  257. FieldInfo fi = parentType.GetFieldInfo(property.name);
  258. return fi.FieldType;
  259. }
  260. /// <summary> Make a simple port field. </summary>
  261. public static void PortField(NodePort port, params GUILayoutOption[] options)
  262. {
  263. PortField(null, port, options);
  264. }
  265. /// <summary> Make a simple port field. </summary>
  266. public static void PortField(GUIContent label, NodePort port, params GUILayoutOption[] options)
  267. {
  268. if (port == null) return;
  269. if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) };
  270. Vector2 position = Vector3.zero;
  271. GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
  272. // If property is an input, display a regular property field and put a port handle on the left side
  273. if (port.direction == NodePort.IO.Input)
  274. {
  275. // Display a label
  276. EditorGUILayout.LabelField(content, options);
  277. Rect rect = GUILayoutUtility.GetLastRect();
  278. position = rect.position - new Vector2(16, 0);
  279. }
  280. // If property is an output, display a text label and put a port handle on the right side
  281. else if (port.direction == NodePort.IO.Output)
  282. {
  283. // Display a label
  284. EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
  285. Rect rect = GUILayoutUtility.GetLastRect();
  286. position = rect.position + new Vector2(rect.width, 0);
  287. }
  288. PortField(position, port);
  289. }
  290. /// <summary> Make a simple port field. </summary>
  291. public static void PortField(Vector2 position, NodePort port)
  292. {
  293. if (port == null) return;
  294. Rect rect = new Rect(position, new Vector2(16, 16));
  295. NodeEditor editor = NodeEditor.GetEditor(port.node, NodeEditorWindow.current);
  296. Color backgroundColor = editor.GetTint();
  297. Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port);
  298. DrawPortHandle(rect, backgroundColor, col);
  299. // Register the handle position
  300. Vector2 portPos = rect.center;
  301. NodeEditor.portPositions[port] = portPos;
  302. }
  303. /// <summary> Add a port field to previous layout element. </summary>
  304. public static void AddPortField(NodePort port)
  305. {
  306. if (port == null) return;
  307. Rect rect = new Rect();
  308. // If property is an input, display a regular property field and put a port handle on the left side
  309. if (port.direction == NodePort.IO.Input)
  310. {
  311. rect = GUILayoutUtility.GetLastRect();
  312. rect.position = rect.position - new Vector2(16, 0);
  313. // If property is an output, display a text label and put a port handle on the right side
  314. }
  315. else if (port.direction == NodePort.IO.Output)
  316. {
  317. rect = GUILayoutUtility.GetLastRect();
  318. rect.position = rect.position + new Vector2(rect.width, 0);
  319. }
  320. rect.size = new Vector2(16, 16);
  321. NodeEditor editor = NodeEditor.GetEditor(port.node, NodeEditorWindow.current);
  322. Color backgroundColor = editor.GetTint();
  323. Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port);
  324. DrawPortHandle(rect, backgroundColor, col);
  325. // Register the handle position
  326. Vector2 portPos = rect.center;
  327. NodeEditor.portPositions[port] = portPos;
  328. }
  329. /// <summary> Draws an input and an output port on the same line </summary>
  330. public static void PortPair(NodePort input, NodePort output)
  331. {
  332. GUILayout.BeginHorizontal();
  333. PortField(input, GUILayout.MinWidth(0));
  334. PortField(output, GUILayout.MinWidth(0));
  335. GUILayout.EndHorizontal();
  336. }
  337. public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor)
  338. {
  339. Color col = GUI.color;
  340. GUI.color = backgroundColor;
  341. GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
  342. GUI.color = typeColor;
  343. GUI.DrawTexture(rect, NodeEditorResources.dot);
  344. GUI.color = col;
  345. }
  346. #region Obsolete
  347. [Obsolete("Use IsDynamicPortListPort instead")]
  348. public static bool IsInstancePortListPort(NodePort port)
  349. {
  350. return IsDynamicPortListPort(port);
  351. }
  352. [Obsolete("Use DynamicPortList instead")]
  353. public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject,
  354. NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple,
  355. Node.TypeConstraint typeConstraint = Node.TypeConstraint.None,
  356. Action<ReorderableList> onCreation = null)
  357. {
  358. DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
  359. }
  360. #endregion
  361. /// <summary> Is this port part of a DynamicPortList? </summary>
  362. public static bool IsDynamicPortListPort(NodePort port)
  363. {
  364. string[] parts = port.fieldName.Split(' ');
  365. if (parts.Length != 2) return false;
  366. Dictionary<string, ReorderableList> cache;
  367. if (reorderableListCache.TryGetValue(port.node, out cache))
  368. {
  369. ReorderableList list;
  370. if (cache.TryGetValue(parts[0], out list)) return true;
  371. }
  372. return false;
  373. }
  374. /// <summary> Draw an editable list of dynamic ports. Port names are named as "[fieldName] [index]" </summary>
  375. /// <param name="fieldName">Supply a list for editable values</param>
  376. /// <param name="type">Value type of added dynamic ports</param>
  377. /// <param name="serializedObject">The serializedObject of the node</param>
  378. /// <param name="connectionType">Connection type of added dynamic ports</param>
  379. /// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
  380. public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject,
  381. NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple,
  382. Node.TypeConstraint typeConstraint = Node.TypeConstraint.None,
  383. Action<ReorderableList> onCreation = null)
  384. {
  385. Node node = serializedObject.targetObject as Node;
  386. var indexedPorts = node.DynamicPorts.Select(x =>
  387. {
  388. string[] split = x.fieldName.Split(' ');
  389. if (split != null && split.Length == 2 && split[0] == fieldName)
  390. {
  391. int i = -1;
  392. if (int.TryParse(split[1], out i))
  393. {
  394. return new { index = i, port = x };
  395. }
  396. }
  397. return new { index = -1, port = (NodePort)null };
  398. }).Where(x => x.port != null);
  399. List<NodePort> dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
  400. node.UpdatePorts();
  401. ReorderableList list = null;
  402. Dictionary<string, ReorderableList> rlc;
  403. if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc))
  404. {
  405. if (!rlc.TryGetValue(fieldName, out list)) list = null;
  406. }
  407. // If a ReorderableList isn't cached for this array, do so.
  408. if (list == null)
  409. {
  410. SerializedProperty arrayData = serializedObject.FindProperty(fieldName);
  411. list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io,
  412. connectionType, typeConstraint, onCreation);
  413. if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list);
  414. else
  415. reorderableListCache.Add(serializedObject.targetObject,
  416. new Dictionary<string, ReorderableList>() { { fieldName, list } });
  417. }
  418. list.list = dynamicPorts;
  419. list.DoLayoutList();
  420. }
  421. private static ReorderableList CreateReorderableList(string fieldName, List<NodePort> dynamicPorts,
  422. SerializedProperty arrayData, Type type, SerializedObject serializedObject, NodePort.IO io,
  423. Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint,
  424. Action<ReorderableList> onCreation)
  425. {
  426. bool hasArrayData = arrayData != null && arrayData.isArray;
  427. Node node = serializedObject.targetObject as Node;
  428. ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
  429. string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
  430. list.drawElementCallback =
  431. (Rect rect, int index, bool isActive, bool isFocused) =>
  432. {
  433. NodePort port = node.GetPort(fieldName + " " + index);
  434. if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
  435. {
  436. if (arrayData.arraySize <= index)
  437. {
  438. EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
  439. return;
  440. }
  441. SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
  442. EditorGUI.PropertyField(rect, itemData, true);
  443. }
  444. else EditorGUI.LabelField(rect, port != null ? port.fieldName : "");
  445. if (port != null)
  446. {
  447. Vector2 pos = rect.position +
  448. (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
  449. PortField(pos, port);
  450. }
  451. };
  452. list.elementHeightCallback =
  453. (int index) =>
  454. {
  455. if (hasArrayData)
  456. {
  457. if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight;
  458. SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
  459. return EditorGUI.GetPropertyHeight(itemData);
  460. }
  461. else return EditorGUIUtility.singleLineHeight;
  462. };
  463. list.drawHeaderCallback =
  464. (Rect rect) => { EditorGUI.LabelField(rect, label); };
  465. list.onSelectCallback =
  466. (ReorderableList rl) => { reorderableListIndex = rl.index; };
  467. list.onReorderCallback =
  468. (ReorderableList rl) =>
  469. {
  470. bool hasRect = false;
  471. bool hasNewRect = false;
  472. Rect rect = Rect.zero;
  473. Rect newRect = Rect.zero;
  474. // Move up
  475. if (rl.index > reorderableListIndex)
  476. {
  477. for (int i = reorderableListIndex; i < rl.index; ++i)
  478. {
  479. NodePort port = node.GetPort(fieldName + " " + i);
  480. NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
  481. port.SwapConnections(nextPort);
  482. // Swap cached positions to mitigate twitching
  483. hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
  484. hasNewRect =
  485. NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
  486. NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
  487. NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
  488. }
  489. }
  490. // Move down
  491. else
  492. {
  493. for (int i = reorderableListIndex; i > rl.index; --i)
  494. {
  495. NodePort port = node.GetPort(fieldName + " " + i);
  496. NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
  497. port.SwapConnections(nextPort);
  498. // Swap cached positions to mitigate twitching
  499. hasRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
  500. hasNewRect =
  501. NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
  502. NodeEditorWindow.current.portConnectionPoints[port] = hasNewRect ? newRect : rect;
  503. NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
  504. }
  505. }
  506. // Apply changes
  507. serializedObject.ApplyModifiedProperties();
  508. serializedObject.Update();
  509. // Move array data if there is any
  510. if (hasArrayData)
  511. {
  512. arrayData.MoveArrayElement(reorderableListIndex, rl.index);
  513. }
  514. // Apply changes
  515. serializedObject.ApplyModifiedProperties();
  516. serializedObject.Update();
  517. NodeEditorWindow.current.Repaint();
  518. EditorApplication.delayCall += NodeEditorWindow.current.Repaint;
  519. };
  520. list.onAddCallback =
  521. (ReorderableList rl) =>
  522. {
  523. // Add dynamic port postfixed with an index number
  524. string newName = fieldName + " 0";
  525. int i = 0;
  526. while (node.HasPort(newName)) newName = fieldName + " " + (++i);
  527. if (io == NodePort.IO.Output)
  528. node.AddDynamicOutput(type, connectionType, Node.TypeConstraint.None, newName);
  529. else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
  530. serializedObject.Update();
  531. EditorUtility.SetDirty(node);
  532. if (hasArrayData)
  533. {
  534. arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
  535. }
  536. serializedObject.ApplyModifiedProperties();
  537. };
  538. list.onRemoveCallback =
  539. (ReorderableList rl) =>
  540. {
  541. var indexedPorts = node.DynamicPorts.Select(x =>
  542. {
  543. string[] split = x.fieldName.Split(' ');
  544. if (split != null && split.Length == 2 && split[0] == fieldName)
  545. {
  546. int i = -1;
  547. if (int.TryParse(split[1], out i))
  548. {
  549. return new { index = i, port = x };
  550. }
  551. }
  552. return new { index = -1, port = (NodePort)null };
  553. }).Where(x => x.port != null);
  554. dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
  555. int index = rl.index;
  556. if (dynamicPorts[index] == null)
  557. {
  558. Debug.LogWarning("No port found at index " + index + " - Skipped");
  559. }
  560. else if (dynamicPorts.Count <= index)
  561. {
  562. Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count +
  563. " - Skipped");
  564. }
  565. else
  566. {
  567. // Clear the removed ports connections
  568. dynamicPorts[index].ClearConnections();
  569. // Move following connections one step up to replace the missing connection
  570. for (int k = index + 1; k < dynamicPorts.Count(); k++)
  571. {
  572. for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++)
  573. {
  574. NodePort other = dynamicPorts[k].GetConnection(j);
  575. dynamicPorts[k].Disconnect(other);
  576. dynamicPorts[k - 1].Connect(other);
  577. }
  578. }
  579. // Remove the last dynamic port, to avoid messing up the indexing
  580. node.RemoveDynamicPort(dynamicPorts[dynamicPorts.Count() - 1].fieldName);
  581. serializedObject.Update();
  582. EditorUtility.SetDirty(node);
  583. }
  584. if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
  585. {
  586. if (arrayData.arraySize <= index)
  587. {
  588. Debug.LogWarning("Attempted to remove array index " + index + " where only " +
  589. arrayData.arraySize + " exist - Skipped");
  590. Debug.Log(rl.list[0]);
  591. return;
  592. }
  593. arrayData.DeleteArrayElementAtIndex(index);
  594. // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
  595. if (dynamicPorts.Count <= arrayData.arraySize)
  596. {
  597. while (dynamicPorts.Count <= arrayData.arraySize)
  598. {
  599. arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1);
  600. }
  601. Debug.LogWarning(
  602. "Array size exceeded dynamic ports size. Excess items removed.");
  603. }
  604. serializedObject.ApplyModifiedProperties();
  605. serializedObject.Update();
  606. }
  607. };
  608. if (hasArrayData)
  609. {
  610. int dynamicPortCount = dynamicPorts.Count;
  611. while (dynamicPortCount < arrayData.arraySize)
  612. {
  613. // Add dynamic port postfixed with an index number
  614. string newName = arrayData.name + " 0";
  615. int i = 0;
  616. while (node.HasPort(newName)) newName = arrayData.name + " " + (++i);
  617. if (io == NodePort.IO.Output)
  618. node.AddDynamicOutput(type, connectionType, typeConstraint, newName);
  619. else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
  620. EditorUtility.SetDirty(node);
  621. dynamicPortCount++;
  622. }
  623. while (arrayData.arraySize < dynamicPortCount)
  624. {
  625. arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
  626. }
  627. serializedObject.ApplyModifiedProperties();
  628. serializedObject.Update();
  629. }
  630. if (onCreation != null) onCreation(list);
  631. return list;
  632. }
  633. }
  634. }