public string GenerateCode(NodeComponent node, string newLine) { if (newLine == null) return "Node [ " + string.Join(" ; ", node.Arguments.OfType<Branch>().Select(n => GenerateCode(n, null))) + " ]"; return "Node [ " + newLine +" "+ string.Join(newLine + " ", node.Arguments.OfType<Branch>().Select(n => GenerateCode(n, newLine + " "))) + newLine + "]"; }
public void NodeBranchesTest() { var node = new NodeComponent { Name = "getResponse", Arguments = { new Branch {Name = "b1", Tree = new LeafComponent {Fun = "totalAmount"}}, new Branch {Name = "b2", Tree = new LeafComponent {Fun = "score"}}, } }; // act var code = _generator.GenerateCode(node, null); // assert code.Should().Be("Node [ (\"b1\", Leaf totalAmount) ; (\"b2\", Leaf score) ]"); }
private void LightClosestNodes(Collider[] Nodes) { Vector3 currentPosition = transform.position; NodeComponent nodeComponent = null; foreach (Collider potentialTarget in Nodes) { nodeComponent = potentialTarget.GetComponent <NodeComponent>(); if (nodeComponent == null) { continue; } if (nodeComponent.Visit()) { AddReward(0.05f); } } }
public override void AddChildNodes(NodeComponent nodeComponent, TreeViewItem parentTree, IList <TreeViewItem> rows) { var node = nodeComponent as NodeIf; manager.AddNodeTree(node.onTrue, parentTree, rows, true); if (manager.CanAddTree(node.onFalse)) { var flowTree = CreateFlowTree(node, nameof(node.onFalse), node.onFalse, uNodeUtility.WrapTextWithKeywordColor("else")); manager.AddNodeTree( flowTree, parentTree, rows, false ); manager.AddNodeTree(node.onFalse, flowTree, rows, true); } manager.AddNodeTree(node.onFinished, parentTree, rows, false); }
private void ProcessConnection(NodeComponent goal, List <NodeComponent> open, NodeComponent fromNode, Connection connection) { var toNode = connection.To; var toNodeInfo = toNode.NodeInfo as HeuristicNodeInfo; HeuristicNodeInfo newNodeInfo = new HeuristicNodeInfo( connection, Mathf.Infinity, fromNode.NodeInfo.costSoFar + connection.Cost); float endNodeHeuristic; if (toNodeInfo.category == Category.Closed) { //If the node is closed, we need to update its cost //only when it is greater then the one of the current path //we also need to add the node again on the open list, because we should //update its neighbors if (toNodeInfo.costSoFar > newNodeInfo.costSoFar) { newNodeInfo.category = Category.Open; open.Add(toNode); toNode.NodeInfo = GetUpdateNodeInfo(toNodeInfo, newNodeInfo); } } else if (toNodeInfo.category == Category.Open) { //If the node is opened, we should update its cost //only when it is greater then the one of the current path if (toNodeInfo.costSoFar > newNodeInfo.costSoFar) { toNode.NodeInfo = GetUpdateNodeInfo(toNodeInfo, newNodeInfo); } } else { //the node is unvisited: we calculate its heuristic and add it //to the open list endNodeHeuristic = heuristicFuncDict[heuristicType](toNode, goal); newNodeInfo.estimatedTotalCost = newNodeInfo.costSoFar + endNodeHeuristic; newNodeInfo.category = Category.Open; toNode.NodeInfo = newNodeInfo; open.Add(toNode); } }
/// <summary> /// Get invoke node code. /// </summary> /// <param name="target"></param> /// <param name="forcedNotGrouped"></param> /// <returns></returns> public static string GetInvokeNodeCode(NodeComponent target, bool forcedNotGrouped = false) { if (target == null) { throw new System.Exception(); } if (target is Node && !(target as Node).IsFlowNode()) { throw new System.Exception(); } if (!forcedNotGrouped && !IsUngroupedNode(target)) { return(GenerateNode(target)); } if (forcedNotGrouped && !generatorData.ungroupedNode.Contains(target)) { throw new uNodeException($"Forbidden to generate state code because the node: {target.GetNodeName()} is not registered as State Node.\nEnsure to register it using {nameof(CodeGenerator)}.{nameof(CodeGenerator.RegisterAsStateNode)}", target); } return(RunEvent(target)); }
public void Initialize(Node node) { Node = node; Node.OnDeleted += () => { Destroy(gameObject); }; List <NodeComponent> createdComponents = new List <NodeComponent>(); foreach (GameObject possibleComponentObject in AvailableNodeComponents) { NodeComponent possibleComponent = possibleComponentObject.GetComponent <NodeComponent>(); if (possibleComponent.IsApplicable(Node)) { NodeComponent newComponent = Instantiate(possibleComponentObject, transform).GetComponent <NodeComponent>(); newComponent.ParentWidget = this; newComponent.LoadFrom(Node); createdComponents.Add(newComponent); } } Components = createdComponents.ToArray(); }
private static void ConnectNode(NodeComponent node) { if (node != null && !generatorData.connectedNode.Contains(node)) { generatorData.connectedNode.Add(node); var nodes = GetConnections(node); if (nodes != null) { foreach (NodeComponent n in nodes) { if (n) { ConnectNode(n); } } } if (node is ISuperNode) { ISuperNode superNode = node as ISuperNode; foreach (var n in superNode.nestedFlowNodes) { if (n != null) { ConnectNode(n); } } } Func <object, bool> validation = delegate(object obj) { if (obj is MemberData) { MemberData member = obj as MemberData; if (member.IsTargetingPinOrNode) { ConnectNode(member.GetTargetNode()); } } return(false); }; AnalizerUtility.AnalizeObject(node, validation); } }
public float[] CollectRewardObs() { Vector3 rayHeight = transform.position + new Vector3(0, -0.5f, 0); RaycastHit hit; int rotation = -90; Quaternion rot = Quaternion.AngleAxis(rotation, Vector3.up); Collider[] hitColliders = Physics.OverlapSphere(transform.position, 2f, rewardCubes, QueryTriggerInteraction.Collide); Collider nc = GetClosestNode(hitColliders); float startValue = 0; if (nc != null) { startValue = nc.GetComponent <NodeComponent>().value; } float[] ret = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < 8; i++) { if (Physics.Raycast(rayHeight, transform.TransformDirection(rot * Vector3.forward), out hit, 3f, rewardCubes)) { NodeComponent n = hit.collider.GetComponent <NodeComponent>(); if (n != null) { //normalized distance to start value if (n.value > startValue) { ret[i] = 1; } if (n.value < startValue) { ret[i] = -1; } } } rotation += 45; rot = Quaternion.AngleAxis(rotation, Vector3.up); } return(ret); }
private static string GenerateFlowCode(IFlowGenerate flowInput, NodeComponent source) { if (flowInput == null) { throw new ArgumentNullException("flowInput"); } if (source == null) { throw new ArgumentNullException("source"); } string data; try { data = flowInput.GenerateCode(); if (setting.fullComment && !string.IsNullOrEmpty(data)) { data = data.Insert(0, "//" + source.gameObject.name + " : " + flowInput.ToString() + " | Type:" + ParseType(source.GetType()).AddLineInEnd()); } data = data.AddLineInFirst(); } catch (Exception ex) { if (!generatorData.hasError) { if (setting != null && setting.isAsync) { generatorData.errors.Add(ex); //In case async return error commentaries. return("/*Error from node: " + source.gameObject.name + " : " + flowInput.ToString() + " */"); } Debug.LogError("Error from node:" + source.gameObject.name + " : " + flowInput.ToString() + " |Type:" + source.GetType() + "\nError:" + ex.ToString(), source); } generatorData.hasError = true; throw; } if (includeGraphInformation) { data = WrapWithInformation(data, source); } return(data); }
/// <summary> /// Get flow nodes from node. /// </summary> /// <param name="node"></param> /// <returns></returns> public static HashSet <NodeComponent> GetFlowConnection(NodeComponent node) { HashSet <NodeComponent> allNodes; if (generatorData.flowNodeConnectionsMap.TryGetValue(node, out allNodes)) { return(allNodes); } allNodes = new HashSet <NodeComponent>(); if (node is StateNode) { StateNode eventNode = node as StateNode; TransitionEvent[] TE = eventNode.GetTransitions(); foreach (TransitionEvent transition in TE) { if (transition.GetTargetNode() != null && !allNodes.Contains(transition.GetTargetNode())) { allNodes.Add(transition.GetTargetNode()); } } } Func <object, bool> validation = delegate(object obj) { if (obj is MemberData) { MemberData member = obj as MemberData; if (member != null && member.isAssigned && (member.targetType == MemberData.TargetType.FlowNode || member.targetType == MemberData.TargetType.FlowInput) && !allNodes.Contains(member.GetTargetNode())) { allNodes.Add(member.GetTargetNode()); } } return(false); }; AnalizerUtility.AnalizeObject(node, validation); generatorData.flowNodeConnectionsMap[node] = allNodes; return(allNodes); }
// // Entire methods after this line are not necessary for executing program, but just for debugging purpose. // bool checkPrefabNodeHasUniqueNodeIndex() { GameObject[] nodeInstances = GameObject.FindGameObjectsWithTag("node"); for (int i = 0; i < nodeInstances.Length - 1; i++) { for (int j = i + 1; j < nodeInstances.Length; j++) { NodeComponent nodeComponent1 = nodeInstances[i].GetComponent <NodeComponent>(); NodeComponent nodeComponent2 = nodeInstances[j].GetComponent <NodeComponent>(); int nodeIndex1 = nodeComponent1.GetNodeIndex(); int nodeIndex2 = nodeComponent2.GetNodeIndex(); if (nodeIndex1 == nodeIndex2) { return(false); } } } return(true); }
/// <summary> /// Compare node state, The compared node will automatic placed to new generated function. /// </summary> /// <param name="target">The target node to compare</param> /// <param name="state">The compare state</param> /// <returns></returns> public static string CompareNodeState(NodeComponent target, bool?state, bool invert = false) { if (target == null) { throw new ArgumentNullException(nameof(target)); } string s = GetCoroutineName(target); if (!string.IsNullOrEmpty(s)) { string result = s.Access(state == null ? "IsRunning" : state.Value ? "IsSuccess" : "IsFailure"); if (invert) { result = result.NotOperation(); } if (!generatorData.ungroupedNode.Contains(target)) { throw new uNodeException($"Forbidden to generate state code because the node: {target.GetNodeName()} is not registered as State Node.\nEnsure to register it using {nameof(CodeGenerator)}.{nameof(CodeGenerator.RegisterAsStateNode)}", target); } return(result); } return(null); }
public void VisitNode(NodeComponent node) { Console.WriteLine(node.Name + ": "); if (node.OutputNodeList.Count == 0) { Console.WriteLine($"Done!!! Output was: {node.Output}" + "\n"); } else { string text = $@"{node.TypeName} got input "; // TODO: Shorten text = node.Values.Aggregate(text, (current, value) => current + $@"{value}, "); text += "\n"; text += $@"Sending output: {node.Output} to -> "; text = node.OutputNodeList.Aggregate(text, (current, outNode) => current + $@"{outNode.TypeName}({outNode.Name}), "); Console.WriteLine(text); } }
public void SetTarget(NodeComponent thisTarget) { m_Target = thisTarget; transform.position = m_Target.GetBuildPosition(); if (!m_Target.m_isTurretUpgraded) { m_CostText.text = "$" + m_Target.m_Blueprint.m_UpgradeCost; m_SellText.text = "$" + m_Target.m_Blueprint.m_SellValue; m_UpgradeButton.interactable = true; } else { m_CostText.text = "MAXED"; m_SellText.text = "$" + (m_Target.m_Blueprint.GetSellUpgrade() + m_Target.m_Blueprint.m_SellValue); m_UpgradeButton.interactable = false; } m_UI.SetActive(true); }
/// <summary> /// Find all node connection after coroutine node. /// </summary> /// <param name="node"></param> /// <param name="allNode"></param> /// <param name="includeSuperNode"></param> /// <param name="includeCoroutineEvent"></param> public static void FindFlowConnectionAfterCoroutineNode(NodeComponent node, ref HashSet <NodeComponent> allNode, bool includeSuperNode = true, bool includeCoroutineEvent = true, bool passCoroutine = false) { if (node != null && !allNode.Contains(node)) { bool isCoroutineNode = node.IsSelfCoroutine(); if (!passCoroutine && isCoroutineNode) { passCoroutine = true; } if (passCoroutine && (!isCoroutineNode || includeCoroutineEvent)) { allNode.Add(node); } var nodes = GetFlowConnection(node); if (nodes != null) { foreach (Node n in nodes) { if (n) { FindFlowConnectionAfterCoroutineNode(n, ref allNode, includeSuperNode, includeCoroutineEvent, passCoroutine); } } } if (includeSuperNode && node is ISuperNode) { ISuperNode superNode = node as ISuperNode; foreach (var n in superNode.nestedFlowNodes) { FindFlowConnectionAfterCoroutineNode(n, ref allNode, includeSuperNode, includeCoroutineEvent, passCoroutine); } } } }
// 1 => path found!, 0 => next step required, -1 => no path possible public int NextStep() { if (Open.Count == 0) { return(-1); } NodeComponent currentTile = Open.Pop(); if (currentTile == null) { return(-1); } if (currentTile == End) { return(1); } List <NodeComponent> neighbours = currentTile.GetComponent <TileComponent>().GetCrossNeighbours(); if (DoDiagonal) { neighbours.AddRange(currentTile.GetComponent <TileComponent>().GetDiagonalNeighbours()); } for (int i = 0; i < neighbours.Count; i++) { NodeComponent currentNeighbour = neighbours[i]; if (Open.Contains(currentNeighbour)) { float currentF = currentTile.GetG() + currentNeighbour.GetH() + Vector3.Magnitude(currentNeighbour.transform.position - currentTile.transform.position); if (currentF < currentNeighbour.GetF()) { Open.Remove(currentNeighbour); Open.Add(currentNeighbour); } } else if (Closed.Contains(currentNeighbour)) { float currentF = currentTile.GetG() + currentNeighbour.GetH() + Vector3.Magnitude(currentNeighbour.transform.position - currentTile.transform.position); if (currentF < currentNeighbour.GetF()) { Closed.Remove(currentNeighbour); Open.Add(currentNeighbour); } } else { FormatNode(currentNeighbour, currentTile); Open.Add(currentNeighbour); } } ChangeTileToColor(currentTile, Color.blue); Closed.Add(currentTile); return(0); }
void ChangeTileToColor(NodeComponent _node, Color _color) { SpriteRenderer sprite = _node.GetComponent <SpriteRenderer>(); sprite.color = _color; }
private float Distance(NodeComponent from, NodeComponent to) { return(Vector3.Distance(from.transform.position, to.transform.position)); }
public override void Remove(NodeComponent node) { _children.Remove(node); }
/// <summary> /// Register flow node as coroutine node /// </summary> /// <param name="node"></param> public static void RegisterAsCoroutineNode(NodeComponent node) { }
public CircuitData(bool noError, string error, NodeComponent nodeComponent) { NoError = noError; ErrorMessage = error; NodeComponent = nodeComponent; }
/// <summary> /// If true indicate the node can return state success or failure /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool CanReturnState(NodeComponent node) { return(IsUngroupedNode(node) || uNodeUtility.IsInStateGraph(node)); }
/// <summary> /// Is the node is ungrouped? /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsUngroupedNode(NodeComponent node) { return(generatorData.ungroupedNode.Contains(node) || !generatorData.groupedNode.Contains(node)); }
/// <summary> /// Is the node are identified as coroutine node? /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsCoroutineFlow(NodeComponent node) { return(node.IsSelfCoroutine()); }
public void PasteNode(Vector3 position) { if (nodeToCopy == null || nodeToCopy.Count == 0) { return; } if (uNodeEditorUtility.IsPrefab(editorData.graph.gameObject)) { throw new Exception("Editing graph prefab dirrectly is not supported."); } uNodeEditorUtility.RegisterUndo(editorData.graph, "Paste Node"); uNodeRoot UNR = editorData.graph; float progress = 0; int loopIndex = 0; if (nodeToCopy.Count > 5) { EditorUtility.DisplayProgressBar("Loading", "", progress); } Vector2 center = Vector2.zero; int centerLength = 0; Dictionary <uNodeComponent, uNodeComponent> CopyedObjectMap = new Dictionary <uNodeComponent, uNodeComponent>(EqualityComparer <uNodeComponent> .Default); foreach (uNodeComponent comp in nodeToCopy) { if (comp == null || comp is EventNode && editorData.selectedGroup != null) { continue; } Node node = comp as Node; if (!CopyedObjectMap.ContainsKey(comp)) { uNodeComponent com = Object.Instantiate(comp); com.gameObject.name = com.gameObject.name.Replace("(Clone)", ""); if (editorData.selectedGroup == null) { if (editorData.selectedRoot) { com.transform.parent = editorData.selectedRoot.transform; } else { com.transform.parent = NodeEditorUtility.GetNodeRoot(UNR).transform; } } else { com.transform.parent = editorData.selectedGroup.transform; } int index = 0; string nm = com.gameObject.name.TrimEnd(numberChar); while (true) { bool flag = false; string gName = com.gameObject.name; foreach (Transform t in com.transform.parent) { if (t != com.transform) { if (t.gameObject.name.Equals(gName)) { flag = true; break; } } } if (flag) { com.gameObject.name = nm + index.ToString(); index++; continue; } break; } CopyedObjectMap.Add(comp, com); if (comp is IMacro || comp is ISuperNode) { var fields = EditorReflectionUtility.GetFields(comp.GetType()); foreach (var field in fields) { if (field.FieldType == typeof(List <Nodes.MacroPortNode>)) { var value = field.GetValueOptimized(comp) as List <Nodes.MacroPortNode>; if (value != null) { var sourceValue = field.GetValueOptimized(com) as List <Nodes.MacroPortNode>; for (int i = 0; i < value.Count; i++) { if (value[i] == null) { continue; } CopyedObjectMap.Add(value[i], sourceValue[i]); } } } } } } if (node != null) { center.x += node.editorRect.x; center.y += node.editorRect.y; centerLength++; } else { BaseEventNode met = comp as BaseEventNode; if (met != null) { center.x += met.editorRect.x; center.y += met.editorRect.y; centerLength++; } } loopIndex++; progress = (float)loopIndex / (float)nodeToCopy.Count; if (nodeToCopy.Count > 5) { EditorUtility.DisplayProgressBar("Loading", "", progress); } } progress = 0; center /= centerLength; HashSet <uNodeComponent> needReflectedComponent = new HashSet <uNodeComponent>(); uNodeRoot compEvent = null; foreach (uNodeComponent com in nodeToCopy) { uNodeComponent comp = null; if (CopyedObjectMap.ContainsKey(com)) { comp = CopyedObjectMap[com]; if (comp == null) { loopIndex++; progress = (float)loopIndex / (float)nodeToCopy.Count; if (nodeToCopy.Count > 5) { EditorUtility.DisplayProgressBar("Loading", "", progress); } continue; } if (comp as Node) { Node node = comp as Node; Func <object, bool> validation = delegate(object o) { if (o is MemberData) { MemberData member = o as MemberData; if (member.IsTargetingPinOrNode) { NodeComponent n = member.GetInstance() as NodeComponent; if (n && n is uNodeComponent) { if (CopyedObjectMap.ContainsKey(n)) { member.instance = CopyedObjectMap[n] as NodeComponent; n.owner = UNR; return(true); } else if (n.owner != UNR || n.transform.parent != node.transform.parent) { member.instance = null; n.owner = UNR; return(true); } //return true; } } } return(false); }; if (node as StateNode) { StateNode eventNode = node as StateNode; TransitionEvent[] TE = eventNode.GetTransitions(); foreach (TransitionEvent n in TE) { var tn = n.GetTargetNode(); if (tn == null) { continue; } if (CopyedObjectMap.ContainsKey(tn)) { n.target = MemberData.CreateConnection(CopyedObjectMap[tn] as Node, true); n.owner = UNR; } else if (n.owner != UNR || tn != null && tn.owner != UNR || tn != null && tn.transform.parent != node.transform.parent) { n.target = MemberData.none; n.owner = UNR; } } } else if (node is IMacro || node is ISuperNode) { var fields = EditorReflectionUtility.GetFields(comp.GetType()); foreach (var field in fields) { if (field.FieldType == typeof(List <Nodes.MacroPortNode>)) { var value = field.GetValueOptimized(comp) as List <Nodes.MacroPortNode>; if (value != null) { foreach (var v in value) { AnalizerUtility.AnalizeObject(v, validation); } } } } } AnalizerUtility.AnalizeObject(node, validation); node.editorRect = new Rect(node.editorRect.x - center.x + position.x, node.editorRect.y - center.y + position.y, node.editorRect.width, node.editorRect.height); if (node.owner != UNR) { node.owner = UNR; } } else if (comp is BaseEventNode) { BaseEventNode method = comp as BaseEventNode; var flows = method.GetFlows(); for (int i = 0; i < flows.Count; i++) { var tn = flows[i].GetTargetNode(); if (tn != null && CopyedObjectMap.ContainsKey(tn)) { flows[i] = new MemberData(CopyedObjectMap[flows[i].GetTargetNode()], MemberData.TargetType.FlowNode); } else if (method.owner != UNR) { flows[i] = MemberData.none; } } method.owner = UNR; method.editorRect = new Rect(method.editorRect.x - center.x + position.x, method.editorRect.y - center.y + position.y, method.editorRect.width, method.editorRect.height); } } loopIndex++; progress = (float)loopIndex / (float)nodeToCopy.Count; if (nodeToCopy.Count > 5) { EditorUtility.DisplayProgressBar("Loading", "", progress); } } if (nodeToCopy.Count > 5) { EditorUtility.ClearProgressBar(); } if (needReflectedComponent.Count > 0) { NodeEditorUtility.PerformReflectComponent(needReflectedComponent.ToList(), compEvent, UNR); } foreach (KeyValuePair <uNodeComponent, uNodeComponent> keys in CopyedObjectMap) { if (keys.Value != null) { Undo.RegisterCreatedObjectUndo(keys.Value.gameObject, "Paste Node"); } } //allCopyedEvent.Clear(); Refresh(); }
public abstract void HighlightNode(NodeComponent node);
public static void ShowInspector(GraphEditorData editorData, int limitMultiEdit = 99) { if (editorData.selected == null) { if (editorData.currentCanvas != null) { EditorGUI.DropShadowLabel(uNodeGUIUtility.GetRect(), "Graph"); EditorGUILayout.Space(); DrawGraphInspector(editorData.graph, true); if (editorData.currentCanvas != editorData.graph) { EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.DropShadowLabel(uNodeGUIUtility.GetRect(), "Edited Canvas"); EditorGUILayout.Space(); DrawUnitObject(editorData.currentCanvas); } } else if (editorData.graphData != null) { DrawUnitObject(editorData.graphData); } return; } EditorGUI.BeginDisabledGroup( (!Application.isPlaying || uNodePreference.GetPreference().preventEditingPrefab) && uNodeEditorUtility.IsPrefab(editorData.owner)); if (editorData.selected is List <NodeComponent> && editorData.selectedNodes.Count > 0 && editorData.graph != null) { editorData.selectedNodes.RemoveAll(item => item == null); int drawCount = 0; for (int i = 0; i < editorData.selectedNodes.Count; i++) { if (i >= editorData.selectedNodes.Count) { break; } NodeComponent selectedNode = editorData.selectedNodes[i]; if (drawCount >= limitMultiEdit) { break; } if (drawCount > 0) { EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); } if (DrawNodeEditor(selectedNode)) { drawCount++; } } if (drawCount >= limitMultiEdit) { EditorGUILayout.BeginVertical("Box"); EditorGUILayout.HelpBox("Multi Editing Limit : " + limitMultiEdit, MessageType.Info); EditorGUILayout.EndVertical(); } } else if (editorData.selected is TransitionEvent transitionEvent && editorData.graph != null) { EditorGUILayout.BeginVertical("Box"); Editor editor = Editor.CreateEditor(transitionEvent); if (editor != null && transitionEvent.owner == editorData.graph) { editor.OnInspectorGUI(); if (transitionEvent.GetType().GetCustomAttributes(typeof(DescriptionAttribute), false).Length != 0) { DescriptionAttribute descriptionEvent = (DescriptionAttribute)transitionEvent.GetType().GetCustomAttributes(typeof(DescriptionAttribute), false)[0]; if (descriptionEvent.description != null && descriptionEvent != null) { GUI.backgroundColor = Color.yellow; EditorGUILayout.HelpBox("Description: " + descriptionEvent.description, MessageType.None); GUI.backgroundColor = Color.white; } } } EditorGUILayout.EndVertical(); if (GUI.changed) { uNodeEditor.GUIChanged(editorData.selected); } }
/// <summary> /// Creates and adds the required GUI elements /// </summary> private void CreateGUI() { // Create the add button AddButton = ControlsFactory.CreateStandardAddCircularButton(); AddButton.Command = new RelayCommand(async() => { // Disable the button AddButton.IsEnabled = false; // Get the analyzer var analyzer = CeidDiplomatikiDI.GetDatabaseAnalyzer(DatabaseOptions.Provider); // Get the connection string DatabaseOptions.TryGetConnectionString(out var connectionString); // Get all the tables var tables = analyzer.GetTables(Database.DatabaseName); // Get all the foreign key columns var foreignKeyColumns = analyzer.GetForeignKeyColumns(Database.DatabaseName, null); // Create a steps presenter var stepsPresenter = new StepsPresenter() { AllowArbitraryNavigation = false }; // Create a node component var nodeComponent = new NodeComponent <IDbProviderTable>(tables, (table) => { // Get the foreign keys of the table var foreignKeys = foreignKeyColumns.Where(x => x.TableName == table.TableName).ToList(); // Get the tables whose primary key is related to one of the foreign keys var foreignToPrimaryKeyTables = tables.Where(x => foreignKeys.Any(y => y.ReferencedTableName == x.TableName)).ToList(); // Get the foreign keys that are related to the primary key of the table var relatedForeignKeys = foreignKeyColumns.Where(x => x.ReferencedTableName == table.TableName).ToList(); // Get the tables var primaryToForeignKeyTables = tables.Where(x => relatedForeignKeys.Any(y => y.TableName == x.TableName)).ToList(); return(foreignToPrimaryKeyTables.Concat <IDbProviderTable, IDbProviderTable>(primaryToForeignKeyTables).Distinct()); }, table => table.TableName); var nodeComponentScrollViewer = new ScrollViewer() { Content = nodeComponent, HorizontalScrollBarVisibility = ScrollBarVisibility.Visible }; // Add it to the steps presenter stepsPresenter.Add("Query", nodeComponentScrollViewer, element => nodeComponent.NodePath.Model != null); // Create the form var form = new DataForm <QueryMap>() .ShowInput(x => x.Name, settings => { settings.Name = CeidDiplomatikiDataModelHelpers.QueryMapMapper.Value.GetTitle(x => x.Name); settings.IsRequired = true; }) .ShowInput(x => x.Description, settings => settings.Name = CeidDiplomatikiDataModelHelpers.QueryMapMapper.Value.GetTitle(x => x.Description)) .ShowStringColorInput(x => x.Color, settings => settings.Name = CeidDiplomatikiDataModelHelpers.QueryMapMapper.Value.GetTitle(x => x.Color)); // Add it to the steps presenter stepsPresenter.Add("Info", form, (element) => element.Validate()); // Show a dialog var dialogResult = await DialogHelpers.ShowStepsDialogAsync(this, "Query map creation", null, stepsPresenter, IconPaths.TablePath); // If we didn't get positive feedback... if (!dialogResult.Feedback) { // Re enable the button AddButton.IsEnabled = true; // Return return; } // Get the selected tables tables = nodeComponent.NodePath.DistinctModels; // Get the pairs var pairs = nodeComponent.NodePath.Pairs; // Get the node path var nodePath = nodeComponent.NodePath; // Get the columns of the table var columns = analyzer.GetColumns(DatabaseOptions.DatabaseName, null).Where(x => tables.Any(y => y.TableName == x.TableName)).ToList(); // The joins collection var joins = new List <JoinMap>(); // For every pair... foreach (var pair in pairs) { JoinMap joinMap; if (foreignKeyColumns.Any(x => x.TableName == pair.Value.Model.TableName && x.ReferencedTableName == pair.Key.Model.TableName)) { // Get the foreign key column var foreignKeyColumn = foreignKeyColumns.First(x => x.TableName == pair.Value.Model.TableName && x.ReferencedTableName == pair.Key.Model.TableName); // Get the principle column var principleColumn = columns.First(x => x.ColumnName == foreignKeyColumn.ReferencedColumnName); // Get the foreign key column var referencedColumn = columns.First(x => x.ColumnName == foreignKeyColumn.ColumnName); // Create the join map joinMap = new JoinMap(pair.Key.Model, principleColumn, pair.Value.Model, referencedColumn, pair.Key.Index, false); } else { // Get the foreign key column var foreignKeyColumn = foreignKeyColumns.First(x => x.ReferencedTableName == pair.Value.Model.TableName && x.TableName == pair.Key.Model.TableName); // Get the principle column var principleColumn = columns.First(x => x.ColumnName == foreignKeyColumn.ColumnName); // Get the foreign key column var referencedColumn = columns.First(x => x.ColumnName == foreignKeyColumn.ReferencedColumnName); // Create the join map joinMap = new JoinMap(pair.Key.Model, principleColumn, pair.Value.Model, referencedColumn, pair.Key.Index, true); } // Add it to the joins joins.Add(joinMap); } // Create the model var model = QueryMap.FromDataModel(DatabaseOptions, Database, tables, columns, joins); // Set it to the form form.Model = model; // Update its values form.UpdateModelValues(); // Get the manager var manager = CeidDiplomatikiDI.GetCeidDiplomatikiManager; // Register the model await manager.RegisterAsync(model); // Save the changes var result = await manager.SaveChangesAsync(); // If there was an error... if (!result.Successful) { // Show the error await result.ShowDialogAsync(this); // Re enable the button AddButton.IsEnabled = true; // Return return; } // Add it to the presenter DataPresenter.Add(model); // Re enable the button AddButton.IsEnabled = true; }); // Add it to the content grid ContentGrid.Children.Add(AddButton); }
public override void Add(NodeComponent node) { _children.Add(node); }
public override void Solve(Graph graph, NodeComponent start, NodeComponent goal) { StartCoroutine(SolveCoroutine(graph, start, goal)); }
public void DeselectNode() { m_SelectedNode = null; m_NodeUI.Hide(); }