public void drawShelfGroup(Event e, float yCoord, int shelfGroupIndex, Rect viewRect, NodeGraph currentNodeGraph, GUISkin viewSkin) { if (isExpanded) { groupRect = new Rect(5f, yCoord, viewRect.width - 10f, getHeight()); GUI.Box(groupRect, groupName, viewSkin.GetStyle(("shelf_group_bg"))); int hiddenNodes = 0; for (int i = 0; i < shelfNodes.Count; i++) { if (!shelfNodes[i].isHidden) { shelfNodes[i].shelfNodeRect = new Rect(10f, yCoord + 40f + (50f * (i - hiddenNodes)), viewRect.width - 20f, 40f); shelfNodes[i].drawNodeShelfGroupNode(e, yCoord, viewSkin); } else { hiddenNodes++; } } } else { groupRect = new Rect(5f, yCoord, viewRect.width - 10f, 40f); GUI.Box(groupRect, groupName, viewSkin.GetStyle(("shelf_group_bg"))); } ProcessEvent(e, currentNodeGraph); }
public static void InitNodePopup(NodeBase node, NodeGraph graph) { currentNodePopupWindow = (NodeGraphPopupWindow)EditorWindow.GetWindow<NodeGraphPopupWindow>(); currentNodePopupWindow.node = node; currentNodePopupWindow.graph = graph; currentNodePopupWindow.title = "Create a new GraphNode"; }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); GUI.Box(viewRect, viewTitle, viewSkin.GetStyle("bg_timeline")); GUILayout.BeginArea(viewRect); GUILayout.BeginVertical(); setTickSpacing(); if (currentNodeGraph != null) { foreach (NodeBase node in currentNodeGraph.nodes) { if (node.isSelected || node.timePointer.isSelected || node.timePointer.isHighlighted || WorkPreferences.showTimeInfo) { drawTimelineConnetion(node.timePointer.arrowRect.center); Color col = node.getColorByNodeType(); DrawTimelineAnimationLength(node, col, WorkPreferences.timelineRectOpacity); if(WorkPreferences.showSubGraph) DrawSubGraphNodes(node); } } } DrawTicks(viewRect, smallTickSpacing, 0.55f, Color.grey, false); DrawTicks(viewRect, bigTickSpacing, 0.35f, Color.black, true); GUILayout.EndVertical(); GUILayout.EndArea(); }
public Provinces(MultiPoly[] boundaries, ISet<int> waterProvinces, NodeGraph<int> graph, BiDictionary<int, string> tagIdMapping) { Boundaries = boundaries; WaterProvinces = waterProvinces; Graph = graph; TagIdMapping = tagIdMapping; Ownership = new Dictionary<int, int>(); }
public virtual void UpdateView(Rect editorRect, Rect percentageRect, Event e,NodeGraph nodeGraph) { if (viewSkin == null) { GetEditorSkin(); return; } //set the current view Graph this.currentNodeGraph = nodeGraph; viewRect = new Rect(editorRect.x * percentageRect.x, editorRect.y * percentageRect.y, editorRect.width * percentageRect.width, editorRect.height * percentageRect.height); }
public static void DisplayGraph(NodeGraph currentGraph) { if (currentGraph != null) { NodeEditorWindow currentWindow = (NodeEditorWindow)EditorWindow.GetWindow<NodeEditorWindow>(); if (currentGraph != null) { currentWindow.currentNodeGraph = currentGraph; NodeGraph.Instance = currentGraph; } } else { EditorUtility.DisplayDialog("Node Message", "Unable to load graph!", "OK"); } }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); if(currentTimelineView == null) currentTimelineView = new NodeTimelineView(); if (currentNodeGraph != null) { viewTitle = currentNodeGraph.graphName; currentNodeGraph.isInsidePropertyView = isInsidePropertyView; currentNodeGraph.zoom = _zoom; currentNodeGraph.panX = panX; currentNodeGraph.panY = panY; currentNodeGraph.typesOfNodes = typesOfNodes; } else{ viewTitle = "No Graph Loaded."; } workSpaceRect = new Rect(panX + (editorRect.x / _zoom), panY, 10000, 10000); EditorZoomArea.Begin(_zoom, _zoomArea); GUI.BeginGroup(workSpaceRect); GUI.Box(new Rect(0, 0, 10000, 10000), viewTitle, viewSkin.GetStyle("bg_view")); //Draw a Grid DrawUtilities.DrawGrid(new Rect(0, 0, 10000, 10000), WorkPreferences.gridSpacingDark, WorkPreferences.gridColorOuter); DrawUtilities.DrawGrid(new Rect(0, 0, 10000, 10000), WorkPreferences.gridSpacingLight, WorkPreferences.gridColorInner); GUILayout.BeginArea(new Rect(0, 0, 10000, 10000)); if (currentNodeGraph != null) { currentNodeGraph.UpdateGraphGUI(e, viewRect, new Rect(0, 0, 10000, 10000), viewSkin); } DrawStepOutOfNode(viewRect); GUILayout.EndArea(); currentTimelineView.UpdateView(new Rect(panX, -panY + (viewRect.height / _zoom) - (50f / _zoom), 10000, 50f / _zoom), new Rect(0f, 1f, 1f, 1f), e, currentNodeGraph); currentTimelineView.ProcessEvents(e); EditorZoomArea.End(); GUI.EndGroup(); }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); GUILayout.BeginArea(viewRect); GUILayout.BeginHorizontal(); GUILayout.Space(3f); GUILayout.BeginVertical(); if (GUILayout.Button("Create New Graph", GUILayout.MinHeight(25))) { NodePopupWindow.InitNodePopup(); Debug.Log("Create New Graph Button pressed"); } GUILayout.Space(5f); if (GUILayout.Button("Load Graph", GUILayout.MinHeight(25))) { NodeUtilities.LoadGraph(); Debug.Log("Load Graph Button pressed"); } GUILayout.Space(5f); if (GUILayout.Button("Show Shelf", GUILayout.MinHeight(25))) { ViewOptions.showShelf = !ViewOptions.showShelf; Debug.Log("Show Shelf Button pressed"); } GUILayout.Space(10f); GUILayout.Label("Zoom: "); NodeWorkView._zoom = EditorGUILayout.Slider(NodeWorkView._zoom, 0.6f, 1.25f); GUILayout.Space(10f); if (GUILayout.Button("Evaluate", GUILayout.MinHeight(50))) { NodeGraph.evaluateTrigger = true; Debug.Log("Evaluate pressed"); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndArea(); }
public void ProcessEvent(Event e, NodeGraph currentNodeGraph) { if (groupRect.Contains(e.mousePosition)) { if (e.button == 0 && e.type == EventType.MouseUp) { if(!isInsideAShelfNode(e)) isExpanded = !isExpanded; } if (e.button == 0 && e.type == EventType.MouseDown) { foreach (NodeShelfGroupNode node in shelfNodes) { if (node.shelfNodeRect.Contains(e.mousePosition)) { Debug.Log(node.shelfNodeName); nodeToInstantiate = node; } } } } if (e.button == 0 && e.type == EventType.MouseUp) { if (nodeToInstantiate != null) { Debug.Log(nodeToInstantiate.shelfNodeName + " instantiated."); NodeBase currentNode = NodeUtilities.CreateNode(nodeTypeView.getGroupNodeDescriptor()); NodeGraph graph = NodeUtilities.getSavedGroupNode(currentNodeGraph, nodeToInstantiate.shelfNodePath, nodeToInstantiate.shelfNodeName); if(graph != null) { currentNode.nodeGraph = graph; graph.graphNode = currentNode; currentNode.InitNodeFromDescriptor(nodeTypeView.getGroupNodeDescriptor()); NodeUtilities.positionNode(currentNode, currentNodeGraph, currentNodeGraph.mousePos); NodeUtilities.saveNode(currentNode, currentNodeGraph); } nodeToInstantiate = null; } } }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); if (currentNodeSubPropertyView == null) currentNodeSubPropertyView = new NodeSubPropertyView(); GUI.Box(viewRect, viewTitle, viewSkin.GetStyle("bg_view")); GUILayout.BeginArea(viewRect); GUILayout.BeginHorizontal(); GUILayout.Space(15f); GUILayout.BeginVertical(); GUILayout.Space(40f); if (currentNodeGraph == null) { } else { if(currentNodeGraph.selectedNodes != null && currentNodeGraph.showProperties) { if(currentNodeGraph.selectedNodes.Count > 0) { if (currentNodeGraph.selectedNodes[currentNodeGraph.selectedNodes.Count - 1] != null) { currentNodeGraph.selectedNodes[currentNodeGraph.selectedNodes.Count - 1].DrawNodeProperties(viewRect, viewSkin); } } } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndArea(); currentNodeSubPropertyView.UpdateView(new Rect(viewRect.x, viewRect.height * 0.8f , viewRect.width, viewRect.height * 0.2f), new Rect(1f , 1f, 1f, 1f), e, currentNodeGraph); currentNodeSubPropertyView.ProcessEvents(e); }
// Token: 0x06001290 RID: 4752 RVA: 0x0004FBC8 File Offset: 0x0004DDC8 private void PlacePlayerSpawnsViaNodegraph() { bool usePod = Stage.instance.usePod; NodeGraph groundNodes = SceneInfo.instance.groundNodes; NodeFlags requiredFlags = NodeFlags.None; NodeFlags nodeFlags = NodeFlags.None; nodeFlags |= NodeFlags.NoCharacterSpawn; List <NodeGraph.NodeIndex> activeNodesForHullMaskWithFlagConditions = groundNodes.GetActiveNodesForHullMaskWithFlagConditions(HullMask.Golem, requiredFlags, nodeFlags); if (usePod) { int num = activeNodesForHullMaskWithFlagConditions.Count - 1; while (num >= 0 && activeNodesForHullMaskWithFlagConditions.Count > 1) { if (!SceneDirector.IsNodeSuitableForPod(groundNodes, activeNodesForHullMaskWithFlagConditions[num])) { activeNodesForHullMaskWithFlagConditions.RemoveAt(num); } num--; } } NodeGraph.NodeIndex nodeIndex; if (this.teleporterInstance) { Vector3 position = this.teleporterInstance.transform.position; List <SceneDirector.NodeDistanceSqrPair> list = new List <SceneDirector.NodeDistanceSqrPair>(); for (int i = 0; i < activeNodesForHullMaskWithFlagConditions.Count; i++) { Vector3 b2; groundNodes.GetNodePosition(activeNodesForHullMaskWithFlagConditions[i], out b2); list.Add(new SceneDirector.NodeDistanceSqrPair { nodeIndex = activeNodesForHullMaskWithFlagConditions[i], distanceSqr = (position - b2).sqrMagnitude }); } list.Sort((SceneDirector.NodeDistanceSqrPair a, SceneDirector.NodeDistanceSqrPair b) => a.distanceSqr.CompareTo(b.distanceSqr)); int index = this.rng.RangeInt(list.Count * 3 / 4, list.Count); nodeIndex = list[index].nodeIndex; } else { nodeIndex = this.rng.NextElementUniform <NodeGraph.NodeIndex>(activeNodesForHullMaskWithFlagConditions); } NodeGraphSpider nodeGraphSpider = new NodeGraphSpider(groundNodes, HullMask.Human); nodeGraphSpider.AddNodeForNextStep(nodeIndex); while (nodeGraphSpider.PerformStep()) { List <NodeGraphSpider.StepInfo> collectedSteps = nodeGraphSpider.collectedSteps; if (usePod) { for (int j = collectedSteps.Count - 1; j >= 0; j--) { if (!SceneDirector.IsNodeSuitableForPod(groundNodes, collectedSteps[j].node)) { collectedSteps.RemoveAt(j); } } } if (collectedSteps.Count >= RoR2Application.maxPlayers) { break; } } List <NodeGraphSpider.StepInfo> collectedSteps2 = nodeGraphSpider.collectedSteps; Util.ShuffleList <NodeGraphSpider.StepInfo>(collectedSteps2, Run.instance.stageRng); int num2 = Math.Min(nodeGraphSpider.collectedSteps.Count, RoR2Application.maxPlayers); for (int k = 0; k < num2; k++) { SpawnPoint.AddSpawnPoint(groundNodes, collectedSteps2[k].node, this.rng); } }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); GUI.Box(viewRect, viewTitle, viewSkin.GetStyle("bg_view")); GUILayout.BeginArea(viewRect); GUILayout.BeginHorizontal(); GUILayout.Space(15f); GUILayout.BeginVertical(); GUILayout.Space(40f); showGridControls = EditorGUILayout.Foldout(showGridControls, "Show Grid Controls"); if (showGridControls) { GUILayout.Space(10f); WorkPreferences.gridColorOuter = EditorGUILayout.ColorField("Grid Outer Color", WorkPreferences.gridColorOuter); GUILayout.Space(6f); WorkPreferences.gridColorInner = EditorGUILayout.ColorField("Grid Inner Color", WorkPreferences.gridColorInner); GUILayout.Space(6f); WorkPreferences.gridSpacingDark = EditorGUILayout.FloatField("Grid Spacing Outer", WorkPreferences.gridSpacingDark); GUILayout.Space(6f); WorkPreferences.gridSpacingLight = EditorGUILayout.FloatField("Grid Spacing Inner", WorkPreferences.gridSpacingLight); } GUILayout.Space(10f); showNodeControls = EditorGUILayout.Foldout(showNodeControls, "Show Node Controls"); if (showNodeControls) { GUILayout.Space(10f); WorkPreferences.nodeCurveColor = EditorGUILayout.ColorField("Node Curve Color", WorkPreferences.nodeCurveColor); GUILayout.Space(6f); GUILayout.BeginHorizontal(); GUILayout.Label("Node Curve Thickness: "); WorkPreferences.nodeCurveThickness = EditorGUILayout.Slider(WorkPreferences.nodeCurveThickness, 0.5f, 10f); GUILayout.EndHorizontal(); GUILayout.Space(6f); GUILayout.BeginHorizontal(); GUILayout.Label("Default Curve Opacity: "); WorkPreferences.timelineCurveOpacityMin = EditorGUILayout.Slider(WorkPreferences.timelineCurveOpacityMin, 0.0f, 1f); GUILayout.EndHorizontal(); GUILayout.Space(6f); GUILayout.BeginHorizontal(); GUILayout.Label("Highlighted Curve Opacity: "); WorkPreferences.timelineCurveOpacityMax = EditorGUILayout.Slider(WorkPreferences.timelineCurveOpacityMax, 0.0f, 1f); GUILayout.EndHorizontal(); } GUILayout.Space(10f); showTimelineControls = EditorGUILayout.Foldout(showTimelineControls, "Show Timeline Controls"); if (showTimelineControls) { GUILayout.Space(10f); GUILayout.BeginHorizontal(); GUILayout.Label("Timeline Opacity: "); WorkPreferences.timelineRectOpacity = EditorGUILayout.Slider(WorkPreferences.timelineRectOpacity, 0.0f, 1f); GUILayout.EndHorizontal(); GUILayout.Space(6f); GUILayout.BeginHorizontal(); GUILayout.Label("Show Group Node sub Nodes "); WorkPreferences.showSubGraph = EditorGUILayout.Toggle("", WorkPreferences.showSubGraph, GUILayout.Width(500)); GUILayout.EndHorizontal(); } GUILayout.Space(10f); showFunctionalityControls = EditorGUILayout.Foldout(showFunctionalityControls, "Show Functionality Settings "); if (showFunctionalityControls) { GUILayout.Space(10f); GUILayout.BeginHorizontal(); GUILayout.Label("Live evaluating Nodes"); WorkPreferences.liveEvaluate = EditorGUILayout.Toggle("", WorkPreferences.liveEvaluate, GUILayout.Width(500)); GUILayout.EndHorizontal(); } GUILayout.Space(10f); showPropertiesSettings = EditorGUILayout.Foldout(showPropertiesSettings, "Show Property Settings "); if (showPropertiesSettings) { GUILayout.Space(10f); GUILayout.BeginHorizontal(); GUILayout.Label("Input/Output Textbox instead Slider"); WorkPreferences.useTextBox = EditorGUILayout.Toggle("", WorkPreferences.useTextBox, GUILayout.Width(500)); GUILayout.EndHorizontal(); } GUILayout.Space(50f); if (GUILayout.Button("Save")) WorkPreferences.savePreferences(); GUILayout.Space(10f); if (GUILayout.Button("Restore Defaults")) WorkPreferences.restoreDefaults(); GUILayout.Space(10f); if (GUILayout.Button("Cancel")) { WorkPreferences.loadPreferences(); PreferencesWindow.currentPreferenceWindow.Close(); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndArea(); }
public static NodeGraph getSavedGroupNode(NodeGraph currentGraph) { string graphPath = EditorUtility.OpenFilePanel("Load Graph", Application.dataPath + "/SimpleMathNodeEditor/Database/", ""); Debug.Log(graphPath); int pathLength = Application.dataPath.Length; int pathLengthWithName = (Application.dataPath + "/SimpleMathNodeEditor/Database/").Length; string finalPath = graphPath.Substring(pathLength - 6); // remove .asset extension from Path string groupNodeName = graphPath.Substring(pathLengthWithName); groupNodeName = groupNodeName.Remove(groupNodeName.Length - 6); string newPath = "Assets/SimpleMathNodeEditor/Database/" + currentGraph.graphName + "_Sub_" + groupNodeName + currentGraph.getGroupNodeCountByName(groupNodeName) + ".asset"; // remove .asset extension from Path AssetDatabase.CopyAsset(finalPath, newPath); return (NodeGraph)AssetDatabase.LoadAssetAtPath(newPath, typeof(NodeGraph)); }
public BreadthFirstPathFinder(NodeGraph pGraph) : base(pGraph) { }
private static IEnumerable <ScrObj> DuplicateNodesAndConnections( IEnumerable <Node> originalNodes, IEnumerable <Connection> originalConnections, NodeGraph target) { Dictionary <InputPort, InputPort> inputs = new Dictionary <InputPort, InputPort>(); Dictionary <OutputPort, OutputPort> outputs = new Dictionary <OutputPort, OutputPort>(); List <Node> duplicatedNodes = new List <Node>(); foreach (Node original in originalNodes) { Node duplicate = DuplicateNode(original, target); duplicate.Position += NodePreferences.DUPLICATION_OFFSET; duplicatedNodes.Add(duplicate); //Cache ports locally. original.PortHandler.AttemptInputAction(inputNode => inputs[inputNode.InputPort] = duplicate.PortHandler.inputNode.InputPort); original.PortHandler.AttemptOutputAction(outputNode => outputs[outputNode.OutputPort] = duplicate.PortHandler.outputNode.OutputPort); if (original.PortHandler.multipleOutputNode == null) { continue; } var mOutputsOriginal = new List <OutputPort>(original.PortHandler.multipleOutputNode.GetOutputs()); var mOutputsDuplicate = new List <OutputPort>(duplicate.PortHandler.multipleOutputNode.GetOutputs()); for (int i = 0; i < mOutputsOriginal.Count; i++) { outputs[mOutputsOriginal[i]] = mOutputsDuplicate[i]; } } //Duplicate connections and match ports and reconnect List <Connection> duplicatedConnections = new List <Connection>(); foreach (Connection original in originalConnections) { InputPort duplicatedInput; if (!inputs.TryGetValue(original.End, out duplicatedInput)) { continue; } OutputPort duplicatedOutput; if (!outputs.TryGetValue(original.Start, out duplicatedOutput)) { continue; } Connection connection = DuplicateConnection(original, target); if (!Connection.AttemptToConnect(connection, duplicatedInput, duplicatedOutput)) { continue; } duplicatedConnections.Add(connection); } NodeEditorUtilities.AutoSaveAssets(); return(duplicatedNodes.Cast <ScrObj>().Concat(duplicatedConnections.Cast <ScrObj>())); }
public override void UpdateView(Rect editorRect, Rect percentageRect, Event e, NodeGraph nodeGraph) { base.UpdateView(editorRect, percentageRect, e, nodeGraph); if(nodeGraph != null) nodeGraph.nodeShelfWidth = viewRect.width; if (currentNodeGraph != null) { GUI.Box(viewRect, viewTitle, viewSkin.GetStyle("bg_view")); float yCoord = 25f - panY; Rect shelfClickGroup = new Rect(5f, yCoord, viewRect.width - 10f, 40f); if (drawBasicNodes) { Rect shelfGroup = new Rect(5f, yCoord, viewRect.width - 10f, currentNodeGraph.typesOfNodes.Count * 50f + 40f); GUI.Box(shelfGroup, "Basic Nodes", viewSkin.GetStyle(("shelf_group_bg"))); basicNodeRects = new List<Rect>(); int hiddenNodes = 0; for (int i = 0; i < currentNodeGraph.typesOfNodes.Count; i++) { NodeDescriptor d = currentNodeGraph.typesOfNodes[i]; if (!d.isHidden) { yCoord = 65f + (50f * (i - hiddenNodes)) - panY; Rect r = new Rect(10f, yCoord, viewRect.width - 20f, 40f); basicNodeRects.Add(r); ProcessEvent(e, r, shelfClickGroup, d, false); string currentStyle = r.Contains(e.mousePosition) ? "node_selected" : "node_default"; GUI.Box(r, d.nodeName, viewSkin.GetStyle((currentStyle + "_titlebar_" + d.titleBarColor))); } else { hiddenNodes++; basicNodeRects.Add(new Rect()); } } yCoord = yCoord + 60f; } else { yCoord = 75f - panY; GUI.Box(shelfClickGroup, "Basic Nodes", viewSkin.GetStyle(("shelf_group_bg"))); ProcessEvent(e, new Rect(), shelfClickGroup, null, true); } for (int i = 0; i < typesOfShelfGroups.Count; i++) { typesOfShelfGroups[i].drawShelfGroup(e, yCoord, i + 1, viewRect, currentNodeGraph,viewSkin); yCoord = yCoord + typesOfShelfGroups[i].getHeight() + 10f; } if (createANode && currentNodeToInstantiate != null) { GUI.Box(new Rect(e.mousePosition.x, e.mousePosition.y, viewRect.width - 20f, 40f),currentNodeToInstantiate.nodeName, viewSkin.GetStyle("node_default_titlebar_" + currentNodeToInstantiate.titleBarColor)); } ProcessContextEvent(e); } }
/// <summary> /// Creates <see cref="ModelBase"/> object by given xml data and /// adds it to corresponding collection of the workspace. /// </summary> /// <param name="modelData">Xml data to create model</param> public void CreateModel(XmlElement modelData) { var helper = new XmlElementHelper(modelData); string typeName = helper.ReadString("type", String.Empty); if (string.IsNullOrEmpty(typeName)) { // If there wasn't a "type" attribute, then we fall-back onto // the name of the XmlElement itself, which is usually the type // name. typeName = modelData.Name; if (string.IsNullOrEmpty(typeName)) { string guid = helper.ReadString("guid"); throw new InvalidOperationException( string.Format("No type information: {0}", guid)); } } if (typeName.Contains("ConnectorModel")) { var connector = NodeGraph.LoadConnectorFromXml(modelData, Nodes.ToDictionary(node => node.GUID)); // It is possible that in some cases connector can't be created, // for example, connector connects to a custom node instance // whose input ports have been changed, so connector can't find // its end port owner. if (connector == null) { var guidAttribute = modelData.Attributes["guid"]; if (guidAttribute == null) { throw new InvalidOperationException("'guid' field missing from recorded model"); } } else { OnConnectorAdded(connector); // Update view-model and view. } } else if (typeName.Contains("NoteModel")) { var noteModel = NodeGraph.LoadNoteFromXml(modelData); AddNote(noteModel); //check whether this note belongs to a group foreach (var annotation in Annotations) { //this note "was" in a group if (annotation.DeletedModelBases.Any(m => m.GUID == noteModel.GUID)) { annotation.AddToSelectedModels(noteModel); } } } else if (typeName.Contains("AnnotationModel")) { var selectedNodes = this.Nodes == null ? null : this.Nodes.Where(s => s.IsSelected); var selectedNotes = this.Notes == null ? null : this.Notes.Where(s => s.IsSelected); var annotationModel = new AnnotationModel(selectedNodes, selectedNotes); annotationModel.ModelBaseRequested += annotationModel_GetModelBase; annotationModel.Disposed += (_) => annotationModel.ModelBaseRequested -= annotationModel_GetModelBase; annotationModel.Deserialize(modelData, SaveContext.Undo); AddNewAnnotation(annotationModel); } else if (typeName.Contains("PresetModel")) { var preset = new PresetModel(this.Nodes); preset.Deserialize(modelData, SaveContext.Undo); presets.Add(preset); //we raise this property change here so that this event bubbles up through //the model and to the DynamoViewModel so that presets show in the UI menu if our undo/redo //created the first preset RaisePropertyChanged("EnablePresetOptions"); } else // Other node types. { NodeModel nodeModel = NodeFactory.CreateNodeFromXml(modelData, SaveContext.Undo, ElementResolver); AddAndRegisterNode(nodeModel); //check whether this node belongs to a group foreach (var annotation in Annotations) { //this node "was" in a group if (annotation.DeletedModelBases.Any(m => m.GUID == nodeModel.GUID)) { annotation.AddToSelectedModels(nodeModel); } } } }
public void CreateNode(NodeGraph GraphObj, NodeType nT, VarType pT, object subType, int nodeCount = 2) { NodeBase node = null; switch (nT) { case NodeType.Math: node = NodeUtilities.CreateNode(GraphObj, NodeType.Math, subType, pT, mouseLoc, nodeCount); break; case NodeType.Event: node = NodeUtilities.CreateNode(GraphObj, nT, subType, mouseLoc); break; case NodeType.Fetch: break; case NodeType.Control: //Debug.Log("I control the world"); if ((ControlNode.ControlType)subType != ControlNode.ControlType.Cast) { node = NodeUtilities.CreateNode(GraphObj, nT, subType, mouseLoc); } break; case NodeType.Function: node = NodeUtilities.CreateNode(GraphObj, nT, subType, pT, mouseLoc, nodeCount); break; } //Debug.Log(node); // establish connection between selected pin and first input/output of matching type // e.g. float to float if (pinToAttach != null) { if (!pinToAttach.isInput) { foreach (InputPin ip in node.InPins) { if (ip.varType == pinToAttach.varType) { graph.ConnectPins(ip, (OutputPin)pinToAttach); break; } } } else { foreach (OutputPin op in node.OutPins) { if (op.varType == pinToAttach.varType) { graph.ConnectPins((InputPin)pinToAttach, op); break; } } } } Destroy(false); }
public static void DeleteNode(NodeBase currentNode, NodeGraph currentGraph) { if (currentGraph != null) { currentGraph.nodes.Remove(currentNode); GameObject.DestroyImmediate(currentNode, true); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } }
public override ChunkContentCandidateCollection GetCandidates(ChunkDetectionResult results) { ChunkContentCandidateCollection output = new ChunkContentCandidateCollection(); var inputGraph = results.InitialGraph; //.CloneByItems(); List <NodeGraph> peaks = new List <NodeGraph>(); ListDictionary <String, NodeGraph> dynamicNodes = new ListDictionary <string, NodeGraph>(); var dynamicNodeList = inputGraph.GetChildrenWithItemSet().Where(x => x.item.Category.HasFlag(NodeInTemplateRole.Dynamic)).ToList(); NodeGraph dynamicNode = dynamicNodeList.FirstOrDefault(); Int32 i = 0; Int32 i_limit = 5000; while (dynamicNode != null) { var nodePeakSearch = new JunctionPeakSearch(dynamicNode); NodeGraph peakNode = nodePeakSearch.GetJunctionPeak(Convert.ToDouble(MinJunctionSize)); dynamicNodes[dynamicNode.path].Add(dynamicNode); if (dynamicNodes[dynamicNode.path].Count > 1) { } if (peakNode == null) { //dynamicNode.removeFromParent(); } else { if (peaks.Contains(peakNode)) { } else { peaks.Add(peakNode); if (peakNode.level < MinPeakNodeLevel) { // dynamicNode.removeFromParent(); } else { //var peakNodeAtSource = results.InitialGraph.GetChildAtPath(peakNode.path, "/", false); if (peakNode.Count() != 0) { ChunkContentCandidate newCandidate = new ChunkContentCandidate(this, peakNode); // peakNode.removeFromParent(); output.Add(newCandidate); } else { } } } } i++; dynamicNode = dynamicNodeList.FirstOrDefault(x => dynamicNodes[x.path].Count == 0); // inputGraph.GetChildrenWithItemSet().FirstOrDefault(x => (x.item.Category.HasFlag(NodeInTemplateRole.Dynamic) && dynamicNodes[x.path].Count == 0)); if (i > i_limit) { break; } } if (peaks.Count > 0) { } results.Candidates.AddRange(output); return(output); }
public static void saveNode(NodeBase currentNode, NodeGraph currentGraph) { if (currentNode != null) { AssetDatabase.AddObjectToAsset(currentNode, currentGraph); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } }
public static void positionNode(NodeBase currentNode, NodeGraph currentGraph, Vector2 mousePos) { if (currentNode != null) { currentNode.InitNode(); currentNode.nodeRect.x = mousePos.x; currentNode.nodeRect.y = mousePos.y; currentNode.parentGraph = currentGraph; currentNode.timePointer.arrowRect.x = (currentNode.nodeRect.x + currentNode.nodeRect.width * 0.5f) - (currentNode.timePointer.arrowRect.width * 0.5f); currentGraph.nodes.Add(currentNode); } }
public static void CreateNode(NodeGraph currentGraph, NodeDescriptor nodeDescriptor, Vector2 mousePos) { if (currentGraph != null) { NodeBase currentNode = CreateNode(nodeDescriptor); positionNode(currentNode, currentGraph, mousePos); saveNode(currentNode, currentGraph); } }
} // If color is left as clear, it will not apply a custom color public void SetNodeView(NodeView nodeView, SerializedProperty serializedNode, NodeGraph nodeGraph, NodeDisplayContainers nodeDisplayContainers) { TargetView = nodeView; TargetProperty = serializedNode; NodeGraph = nodeGraph; m_nodeDisplayContainers = nodeDisplayContainers; }
private void Reset() { m_nodeGraph = null; GraphInspector.Reset(); NodeInspector.Reset(); }
public override void DrawView(Rect editorRect, Rect PercentRect, Event e, NodeGraph graph) { base.DrawView(editorRect, PercentRect, e, graph); // reposition to fit on screen float dy = window.position.height - (body.height + body.y); if (dy < 0) { body.y += dy; } float dx = window.position.width - (body.width + body.x); if (dx < 0) { body.x += dx; } ProcessEvents(e); Vector2 margin = new Vector2(6, 12); size = new Vector2(200, 100); //Rect viewRect = new Rect(0, 0, body.width, body.height); //Rect ctrlRect = new Rect(x,y, ctrlWidth, ctrlHeight); try { GUI.Box(body, "", skin.GetStyle("NodeCreationBackground")); GUILayout.BeginArea(new Rect(body.x + margin.x, body.y + margin.y, body.width - 2 * margin.x, body.height - 2 * margin.y)); scrollPos = GUILayout.BeginScrollView(scrollPos, false, true); EditorGUILayout.BeginVertical(); { if (showDialogues = EditorGUILayout.Foldout(showDialogues, "Dialogue")) { //Debug.Log("In my sack"); foreach (ControlNode.ControlType cT in ControlNode.dialogControls) { if (size.y < 400) { size.y += 10; } if (GUILayout.Button(cT.ToString(), skin.GetStyle("NodeCreationButton"))) { CreateNode(graph, NodeType.Control, VarType.Exec, cT); } } } if (showControls = EditorGUILayout.Foldout(showControls, "Controls")) { foreach (ControlNode.ControlType cT in cTypes) { if (ControlNode.dialogControls.Contains(cT)) { continue; } if (size.y < 400) { size.y += 10; } if (cT != ControlNode.ControlType.Custom && GUILayout.Button(cT.ToString(), skin.GetStyle("NodeCreationButton"))) { if (cT == ControlNode.ControlType.Cast) { NodeCreatePopup.Init(NodeType.Control, cT, pinToAttach, mouseLoc); Destroy(true); } else { CreateNode(graph, NodeType.Control, VarType.Exec, cT); } } } if (GUILayout.Button("Sub Start", skin.GetStyle("NodeCreationButton"))) { CreateNode(graph, NodeType.Event, VarType.Object, "New SubStart"); } //if (GUILayout.Button("End", skin.GetStyle("NodeCreationButton"))) { // CreateNode(graph, NodeType.Event, VarType.Object, true); //} } if (showMath = EditorGUILayout.Foldout(showMath, "Math")) { foreach (MathNode.OpType op in ops) { if (size.y < 400) { size.y += 10; } if (GUILayout.Button(op.ToString(), skin.GetStyle("NodeCreationButton"))) { // create math FunctionNode MathNode mn = new MathNode(); mn.Initialize(); mn.Construct(op, VarType.Float, 2); NodeCreatePopup.Init(NodeType.Math, op, pinToAttach, mouseLoc, mn.multiplePins ? -1 : 2); Destroy(true); } } } if (showFunc = EditorGUILayout.Foldout(showFunc, "Functions")) { foreach (FunctionNode.FunctionType cT in fTypes) { if (size.y < 400) { size.y += 10; } if (GUILayout.Button(cT.ToString(), skin.GetStyle("NodeCreationButton"))) { CreateNode(graph, NodeType.Function, VarType.Object, cT); } } } } EditorGUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndArea(); } catch { GUILayout.EndArea(); } }
public override NodeGraphData ImportData(string serializedData) { NodeGraphData returnData = null; JSONNode root = JSON.Parse(serializedData); Dictionary <int, object> references = new Dictionary <int, object>(); Dictionary <NodePort, NodePortData> portDatas = new Dictionary <NodePort, NodePortData>(); List <string> ignoredFields = new List <string> { "name", "graph", "ports", "nodes" }; JSONObject graphJObject; if (root.HasKey("graph")) { graphJObject = root["graph"].AsObject; int id = graphJObject["id"]; string graphTypeS = graphJObject["type"]; Type graphType = Type.GetType(graphTypeS); NodeGraph graph = (NodeGraph)Activator.CreateInstance(graphType); graph.name = graphJObject["name"]; references.Add(id, graph); returnData = new NodeGraphData(graph); //Debug.Log("Basic graph OK!"); } else { Debug.LogWarning("Basic graph KO!"); return(returnData); } if (root.HasKey("nodes")) { JSONArray nodesJArray = root["nodes"].AsArray; foreach (JSONObject nodeJObject in nodesJArray.Values) { int id = nodeJObject["id"]; string nodeTypeS = nodeJObject["type"]; Type nodeType = Type.GetType(nodeTypeS); Node node = (Node)Activator.CreateInstance(nodeType); node.name = nodeJObject["name"]; object nodeOBJ = (object)node; SimpleJSONExtension.FromJSON(ref nodeOBJ, nodeType, nodeJObject, ignoredFields, references); node.graph = returnData.graph; NodeData nodeData = new NodeData(node); JSONArray nodePortsArray = nodeJObject["ports"].AsArray; foreach (var nodePort in nodePortsArray.Values) { bool dynamic = nodePort["dynamic"].AsBool; string portName = nodePort["name"]; NodePort port = null; int portId = 0; if (dynamic) { if (!node.HasPort(portName)) { Type dynamicType = Type.GetType(nodePort["valueType"]); Node.TypeConstraint constraint = (Node.TypeConstraint)nodePort["typeConstraint"].AsInt; Node.ConnectionType connectionType = (Node.ConnectionType)nodePort["connectionType"].AsInt; NodePort.IO direction = (NodePort.IO)nodePort["direction"].AsInt; if (direction == NodePort.IO.Input) { port = node.AddInstanceInput(dynamicType, connectionType, constraint, portName); } else { port = node.AddInstanceOutput(dynamicType, connectionType, constraint, portName); } } else { Debug.LogWarning("Ignoring port bc is already created"); } } port = node.GetPort(nodePort["name"]); if (port == null) { Debug.Log("Port is null? " + node.name); foreach (var p in node.Ports) { Debug.Log(p.fieldName); } } portId = nodePort["id"]; NodePortData portData = new NodePortData(nodeData, port); nodeData.ports.Add(portData); portDatas.Add(port, portData); references.Add(portId, port); } references.Add(id, node); returnData.nodes.Add(nodeData); } //Debug.Log("Basic Nodes OK!"); } else { Debug.LogWarning("Basic Nodes KO!"); return(returnData); } if (root.HasKey("connections")) { JSONArray connectionsJArray = root["connections"].AsArray; foreach (JSONObject connectionJObject in connectionsJArray.Values) { int port1ID = connectionJObject["port1ID"].AsInt; int port2ID = connectionJObject["port2ID"].AsInt; if (references.ContainsKey(port1ID) && references.ContainsKey(port2ID)) { NodePort p1 = (NodePort)references[port1ID]; NodePort p2 = (NodePort)references[port2ID]; p1.Connect(p2); } else { Debug.LogWarning("Error recovering one connection"); } } //Debug.Log("Connections OK!"); } else { Debug.LogWarning("Connections KO!"); return(returnData); } object graphObject = returnData.graph; SimpleJSONExtension.FromJSON(ref graphObject, returnData.graph.GetType(), graphJObject, ignoredFields, references); return(returnData); }
private static IEnumerable <Node> DuplicateNodes(IEnumerable <Node> originalNodes, NodeGraph target = null) { List <Node> duplicates = new List <Node>(); foreach (Node original in originalNodes) { NodeGraph localTarget = target ?? original.Graph; Node duplicate = DuplicateNode(original, localTarget); duplicate.Position += NodePreferences.DUPLICATION_OFFSET; duplicates.Add(duplicate); } NodeEditorUtilities.AutoSaveAssets(); return(duplicates); //Repaint(); }
public void Initialize(NodeGraph data) { }
public AttributesNode(NodeGraph graph) : base(graph) { AddAttributeNode(); }
/// <summary> /// Calculates the parent's Movements. /// </summary> /// <returns>The parent.</returns> /// <param name="node">Node.</param> /// <param name="player">Player.</param> /// <param name="limit">Limit.</param> private int CalculateParent(NodeGraph <BoardState> node, int player, int limit = int.MaxValue) { int next_player = (player == 1) ? 2 : 1; // Nó já está calculado, sai if (node.obj.matchState != BoardState.MatchState.InProgress) { return(int.MinValue); } //Calcula seus filhos foreach (NodeGraph <BoardState> child in node.children) { //Useless variable int nextFromChild = this.CalculateParent(child, next_player, limit - 1); } List <NodeGraph <BoardState> > ganhos = new List <NodeGraph <BoardState> >(); List <NodeGraph <BoardState> > empates = new List <NodeGraph <BoardState> >(); List <NodeGraph <BoardState> > derrotas = new List <NodeGraph <BoardState> >(); List <NodeGraph <BoardState> > sorteio = new List <NodeGraph <BoardState> >(); //Busca Ganhos, empates e derrotas foreach (NodeGraph <BoardState> child in node.children) { if ((child.myState == BoardState.MatchState.Player1Won && player == 1) || (child.myState == BoardState.MatchState.Player2Won && player == 2)) { ganhos.Add(child); } else if ((child.myState == BoardState.MatchState.Player1Won && player == 2) || (child.myState == BoardState.MatchState.Player2Won && player == 1)) { derrotas.Add(child); } else if (child.myState == BoardState.MatchState.Draw) { empates.Add(child); } else { throw new Exception("Undefined error in AI Module!"); } } //Varre menor ganho para a escolha da ação if (ganhos.Count > 0) { int level = int.MaxValue; int level_index = 0; for (int i = 0; i < ganhos.Count; i++) { NodeGraph <BoardState> child = ganhos[i]; if (child.level < level) { level = child.level; level_index = i; sorteio = new List <NodeGraph <BoardState> >(); sorteio.Add(child); } else if (child.level == level) { sorteio.Add(child); } } } else if (empates.Count > 0) // Senão, busca empate { int level = int.MaxValue; int level_index = 0; for (int i = 0; i < empates.Count; i++) { NodeGraph <BoardState> child = empates[i]; if (child.level < level) { level = child.level; level_index = i; sorteio = new List <NodeGraph <BoardState> >(); sorteio.Add(child); } else if (child.level == level) { sorteio.Add(child); } } } else // Senão, se satisfaz com derrota :'-( (tenta adiar) { int level = int.MinValue; int level_index = 0; for (int i = 0; i < derrotas.Count; i++) { NodeGraph <BoardState> child = derrotas[i]; if (child.level > level) { level = child.level; level_index = i; sorteio = new List <NodeGraph <BoardState> >(); sorteio.Add(child); } else if (child.level == level) { sorteio.Add(child); } } } int sorteado = UnityEngine.Random.Range(0, sorteio.Count); node.level = sorteio[sorteado].level + 1; node.myState = sorteio[sorteado].myState; return(sorteio[sorteado].obj.LastMovement); }
public TypeOfNode(NodeGraph graph) : base(graph) { AddInputTypePin("Type"); AddOutputDataPin("Type", TypeSpecifier.FromType <Type>()); }
public static NodeGraph getSavedGroupNode(NodeGraph currentGraph, string path, string name) { int pathLength = Application.dataPath.Length; int pathLengthWithName = (Application.dataPath + "/SimpleMathNodeEditor/Database/").Length; string finalPath = path.Substring(pathLength - 6); // remove .asset extension from Path string newPath = "Assets/SimpleMathNodeEditor/Database/" + currentGraph.graphName + "_Sub_" + name + currentGraph.getGroupNodeCountByName(name) + ".asset"; // remove .asset extension from Path AssetDatabase.CopyAsset(finalPath, newPath); return (NodeGraph)AssetDatabase.LoadAssetAtPath(newPath, typeof(NodeGraph)); }
public ChunkDetectionResult(NodeGraph initialGraph, ChunkDetectorCollection detectors) { InitialGraph = initialGraph; CurrentGraph = InitialGraph.CloneByItems(); Detectors = detectors; }
public static NodeGroupGraph GroupNodes(List <Node> nodesToGroup, NodeGraph g, string name = "Nodes Group") { if (nodesToGroup.Count < 2) { Debug.LogWarning("Should be 2 or more nodes to make a group"); return(null); } for (int i = nodesToGroup.Count - 1; i >= 0; i--) { Node node = nodesToGroup[i]; if (node == null) { Debug.LogError("Something went wrong!"); return(null); } if ((node is IVariableNode)) { nodesToGroup.Remove(node); Debug.LogWarning("Removed GET/SET"); } else { node.name = node.name + "_" + node.GetHashCode(); } } NodeGraph gcopy = g.Copy(); NodeGroupGraph nodeGroupGraph = new NodeGroupGraph(Guid.NewGuid().ToString()); nodeGroupGraph.name = name; nodeGroupGraph.nodes = gcopy.nodes; for (int i = nodeGroupGraph.nodes.Count - 1; i >= 0; i--) { var n = nodeGroupGraph.nodes[i]; Node nod = nodesToGroup.Find(no => no.name == n.name); // node is not contained in the group => remove it from the grouped graph! if (nod == null) { nodeGroupGraph.RemoveNode(n); } } foreach (var n in nodeGroupGraph.nodes) { foreach (var p in n.Ports) { if (!p.IsConnected) { nodeGroupGraph.ports.Add(p); } } } if (g is NTGraph) { NodeGroupGraph ngc = nodeGroupGraph.AddTo((NTGraph)g, nodesToGroup[0].position); for (int i = g.nodes.Count - 1; i >= 0; i--) { Node n = g.nodes[i]; var nodeInNG = ngc.nodes.Find(no => no.name == n.name); if (nodeInNG == null) { /*foreach(var port in n.Ports){ * for (int c = port.ConnectionCount - 1 ; c >= 0; c--) { * NodePort other = port.GetConnection(c); * * Node nodeInGroup = ngc.nodes.Find( no => no.name == other.node.name); * * if(nodeInGroup != null){ * * Debug.Log("Redirect it to??? __ " + n.name); * * port.Redirect(new List<Node>(){other.node}, new List<Node>(){nodeInGroup}); * } * } * }*/ } else { foreach (var port in n.Ports) { for (int c = port.ConnectionCount - 1; c >= 0; c--) { NodePort other = port.GetConnection(c); Node nodeInGroup = ngc.nodes.Find(no => no.name == other.node.name); if (nodeInGroup == null) { nodeInNG.GetPort(port.fieldName).Connect(other); } } } g.nodes.Remove(n); } } } nodeGroupGraph.Export(); return(nodeGroupGraph); }
public static GraphNodeRef CreateNodeRef(NodeGraph graph, string guid) { return(new GraphNodeRef { graph = graph, guid = guid }); }
public static (IMutableBidirectionalGraph <CyclicCluster, CondensedEdge <DisplayNode, DisplayEdge, CyclicCluster> > Clustered, IBidirectionalGraph <DisplayNode, DisplayEdge> Simple) GetFullClusteredGraph(this NodeGraph nodeGraph) { var rootNodes = nodeGraph.Nodes.Values; var fullDisplayGraph = GetDisplaySubgraph(nodeGraph, rootNodes, SetUtils.GetEmpty <NodeKey>()); return(fullDisplayGraph.GetClusteredGraph(), fullDisplayGraph); }
// FIXME: Generic export when recieves ignore field parameters // Add attribute like IgnoreExport or similar // For linked types do similar public override string ExportData(NodeGraphData data, List <Type> referenceTypes) { JSONObject exportJSON = new JSONObject(); JSONObject graph = new JSONObject(); JSONArray graphNodesReferences = new JSONArray(); referenceTypes.Add(typeof(Node)); referenceTypes.Add(typeof(NodeGraph)); referenceTypes.Add(typeof(NodePort)); graph.Add("type", new JSONString(data.graph.GetType().AssemblyQualifiedName)); graph.Add("name", new JSONString(data.graph.name)); graph.Add("id", new JSONNumber(data.graph.GetHashCode())); NodeGraph g = data.graph; graph = (JSONObject)SimpleJSONExtension.ToJSON(g, graph, new List <string>() { "sceneVariables" }, referenceTypes); JSONArray connections = new JSONArray(); for (int c = 0; c < data.connections.Count; c++) { JSONObject connection = new JSONObject(); connection.Add("port1ID", data.connections[c].port1ID); connection.Add("port2ID", data.connections[c].port2ID); connections.Add(connection); } JSONArray nodes = new JSONArray(); for (int n = 0; n < data.nodes.Count; n++) { Node node = data.nodes[n].node; JSONObject nodeJSON = new JSONObject(); nodeJSON.Add("name", node.name); nodeJSON.Add("type", node.GetType().AssemblyQualifiedName); nodeJSON.Add("position", node.position); nodeJSON.Add("id", node.GetHashCode()); JSONArray nodePorts = new JSONArray(); for (int np = 0; np < data.nodes[n].ports.Count; np++) { NodePort port = data.nodes[n].ports[np].port; JSONObject nodePortJSON = new JSONObject(); nodePortJSON.Add("name", port.fieldName); nodePortJSON.Add("id", port.GetHashCode()); nodePortJSON.Add("dynamic", port.IsDynamic); nodePortJSON.Add("valueType", port.ValueType.AssemblyQualifiedName); nodePortJSON.Add("typeConstraint", (int)port.typeConstraint); nodePortJSON.Add("connectionType", (int)port.connectionType); nodePortJSON.Add("direction", (int)port.direction); nodePorts.Add(nodePortJSON); } nodeJSON.Add("ports", nodePorts); nodeJSON = (JSONObject)SimpleJSONExtension.ToJSON(node, nodeJSON, new List <string>(), referenceTypes); nodes.Add(nodeJSON); } exportJSON.Add("graph", graph); exportJSON.Add("connections", connections); exportJSON.Add("nodes", nodes); return(exportJSON.ToString()); }
public static IBidirectionalGraph <DisplayNode, DisplayEdge> GetDisplaySubgraph(this NodeGraph nodeGraph, IList <ITypeSymbol> rootSymbols) => GetDisplaySubgraph(nodeGraph, rootSymbols.Select(tpl => nodeGraph.GetNodeForType(tpl)).Trim(), SetUtils.GetEmpty <NodeKey>());
public void SetUpData(NodeGraph data) { }
public static IBidirectionalGraph <DisplayNode, DisplayEdge> GetDisplaySubgraph(this NodeGraph nodeGraph, IEnumerable <Node> subgraphNodes, ISet <NodeKey> pinnedNodes, object?parentContext = null) { var subgraphNodesSet = subgraphNodes.ToHashSet(); var graph = new BidirectionalGraph <DisplayNode, DisplayEdge>(); var displayNodes = subgraphNodesSet.ToDictionary(n => n, n => n.ToDisplayNode(pinnedNodes.Contains(n.Key), parentContext)); foreach (var kvp in displayNodes) { graph.AddVertex(kvp.Value); } foreach (var kvp in displayNodes) { foreach (var link in kvp.Key.ForwardLinkNodes) { if (displayNodes.ContainsKey(link)) { // Add dependencies as edges if both ends are part of the subgraph graph.AddEdge(new SimpleDisplayEdge(kvp.Value, displayNodes[link])); } } } if (subgraphNodesSet.Count > 1) { // Add multi-dependency edges, if any applicable var rootPaths = GetMultiDependencyRootPaths(nodeGraph, subgraphNodesSet); var pathsToDisplay = rootPaths.Where(p => p.IntermediateLength > 0); // foreach (var path in pathsToDisplay) { graph.AddEdge(path.ToDisplayEdge(displayNodes)); } } return(graph); }
public IAModule_GameTree(BoardState root) { this._root = root; this._nodeRoot = new NodeGraph <BoardState>(this._root); }
public static IEnumerable <NodePath> GetMultiDependencyRootPaths(NodeGraph graph, ISet <Node> roots) { if (roots.Count < 2) { throw new ArgumentOutOfRangeException(nameof(roots)); } var toExplore = new Queue <SearchEntry>(); var nodesSeen = new HashSet <Node>(); foreach (var root in roots) { toExplore.Clear(); nodesSeen.Clear(); var rootsNotFound = roots.Count - 1; toExplore.Enqueue(new SearchEntry(root, previous: null, generation: 0)); var lp = new LoopProtection(); while (toExplore.Count > 0) { lp.Iterate(); var current = toExplore.Dequeue(); foreach (var link in current.Node.ForwardLinkNodes) { if (nodesSeen.Contains(link)) { // Seen before, is either in queue or already explored (or is a root) continue; } // Mark as seen nodesSeen.Add(link); if (roots.Contains(link) && link != root) { // We've found another root yield return(NodePath.FromSearch(current, link)); rootsNotFound--; // Note: we don't add it to the explore queue, because we don't want paths with more than 2 roots. Any connections out of that root // will be found when that root is processed. } else { // Regular node we haven't seen - queue it up to explore toExplore.Enqueue(current.NextGeneration(link)); } if (rootsNotFound == 0) { // All roots have been found for this root, go to the next one break; } } if (rootsNotFound == 0) { // All roots have been found for this root, go to the next one break; } } } }
public void When_WriteAndReadAndWrite_CoreLinkedNodeGraph_Expect_SameNodeGraph(NodeGraph originalGraph) { string filePath = ArgParser.GetPath(Path.Combine(OSString, "Output_Files", "xmlOutput.xml")); XMLCreator.writeXML(originalGraph, filePath); NodeGraph restoredGraph = XMLCreator.readXML <NodeGraph>(filePath); filePath = ArgParser.GetPath(Path.Combine(OSString, "Output_Files", "xmlOutput2.xml")); XMLCreator.writeXML(restoredGraph, filePath); Assert.IsTrue(originalGraph.Equals(restoredGraph)); }
void OnDisable() { _nodegraph = null; }
// Token: 0x0600128F RID: 4751 RVA: 0x0004FBA8 File Offset: 0x0004DDA8 private static bool IsNodeSuitableForPod(NodeGraph nodeGraph, NodeGraph.NodeIndex nodeIndex) { NodeFlags nodeFlags; return(nodeGraph.GetNodeFlags(nodeIndex, out nodeFlags) && (nodeFlags & NodeFlags.NoCeiling) != NodeFlags.None); }
/// <summary> /// applies the applicable node grammars from <paramref name="nodeGrammars"/> in the sequence described by the string <paramref name="ruleSequence"/> onto the graph <paramref name="nodeGraph"/> example sequence : "ABC" will transform the nodegraph according to the rules labeled "A" then "B" then "C" if they exist withing the supplied grammar rules /// </summary> /// <param name="ruleSequence">sequence of rules to apply</param> /// <param name="nodeGrammars">all possible rules to apply</param> /// <param name="nodeGraph">the graph to be cloned and transformed</param> /// <returns>the transformed node graph</returns> public static NodeGraph ApplyNodeGrammars(string ruleSequence, ref List <NodeGrammar> nodeGrammars, NodeGraph nodeGraph, int seed) { if (ruleSequence == null) { return(nodeGraph); } NodeGraph output = (NodeGraph)nodeGraph.Clone(); // TODO : make it possible for rules to have a label of more than one character for (int ruleIndex = 0; ruleIndex < ruleSequence.Length; ruleIndex++) { string ruleLabel = ruleSequence[ruleIndex].ToString(); // collect all the rules with the right label var rules = nodeGrammars.Where((NodeGrammar gram) => gram.Name == ruleLabel); if (rules.Count() == 0) { // no rules match this label continue; } // try all the applicable rules foreach (var rule in rules) { if (IsGrammarApplicable(rule, ref output, out OrderedDictionary <int, int> translationTable, seed)) { // if the grammar is applicable we get a valid translation table back, this table will give us translations for which IDs in the graph match which IDs in the left hand side of the grammar rule // we found one that works, apply it and go to the next step in the sequence ApplyNodeRule(rule, ref output, ref translationTable); break; } } } return(output); }
// TODO: colocar pra gerar em árvore protected void CreateMazes() { /* * current = maze (primeiro maze) * enquanto mazeCount < maxMazeCount * gerar numero random de filhos * definir um para ser sala (e gerar sala e conexão com pai) * gerar labirintos comuns (menores) * gerar conexões * colocar os filhos em uma fila * atualizar contador * current = tira da fila próximo maze */ Queue <NodeGraph> queue = new Queue <NodeGraph>(); NodeGraph first = new NodeGraph(beginIndex); NodeGraph current; queue.Enqueue(first); int mazeCount = 1, maxMazeCount = Random.Range(7, 12); int currentId = beginIndex + 1; while (mazeCount < maxMazeCount) { current = queue.Dequeue(); int childrenNumber = Random.Range(Mathf.Min(maxMazeCount - mazeCount + 1, 3), Mathf.Min(maxMazeCount - mazeCount + 1, 4)); NodeGraph[] children = CreateChildren(current, childrenNumber, currentId); foreach (NodeGraph c in children) { if (c.type == 0) { queue.Enqueue(c); } } currentId += childrenNumber; mazeCount += childrenNumber; } NodeGraph final = GetEndWay(first); HallMaze[] mazes = TreeToArray(first, final, maxMazeCount); Tile entranceTile = GenerateBorderTile(mazes [0], 3 - entrance.dir, entrance.size); Tile roomTile = GenerateBorderTile(final.maze, 3 - mirrorRoom.dir, mirrorRoom.size); AddTransition(mazes [0], entranceTile.x, entranceTile.y, 3 - entrance.dir, expansionFactor); AddTransition(final.maze, roomTile.x, roomTile.y, 3 - mirrorRoom.dir, expansionFactor); this.mazes = mazes; /* * int beginDir = mirrorRoom.dir; * * for (int i = 0; i < mazeCount; i++) { * mazes[i] = new HallMaze(i + beginIndex, 1 + 2 * Random.Range(5, 8), 1 + 2 * Random.Range(5, 8)); * mazes[i].Expand (expansionFactor, expansionFactor); * } * * for (int i = 0; i < mazeCount - 1; i++) { * beginDir = GenerateDir (beginDir); * SetTransitions ( * mazes [i], * mazes [i + 1], * beginDir * ); * } */ }
private void initGraphButton_Click(object sender, EventArgs e) { graph = new NodeGraph(); try { adjmatrix = Helper.MatrixFromString(matrixBox.Text); } catch (FormatException ex) { MessageBox.Show(ex.Message, "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int nodeCount = adjmatrix.GetLength(0); vertices = new Vertex[nodeCount]; for (int k = 0; k < nodeCount; k++) { vertices[k] = new Vertex(k.ToString(), 1.0, 0); graph.AddVertex(vertices[k]); } //dreadnaut für orbits starten string dreadnautcmd = "n=" + nodeCount + " g "; for (int irow = 0; irow < nodeCount; irow++) { for (int icol = 0; icol < nodeCount; icol++) { if (adjmatrix[irow, icol] != 0) { graph.AddEdge(new Edge<Vertex>(vertices[irow], vertices[icol])); dreadnautcmd += icol + " "; } } dreadnautcmd += ";"; } dreadnautcmd += "x o q"; string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "dreadnaut.exe"); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.FileName = path; Process process = new Process(); process.StartInfo = startInfo; try { System.IO.File.WriteAllBytes(path, ClusterNum.Properties.Resources.dreadnaut); process.Start(); } catch (Exception ex) { MessageBox.Show("dreadnaut konnte nicht gestartet werden", "dreadnaut-Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } process.StandardInput.WriteLine(dreadnautcmd); process.WaitForExit(); System.IO.File.Delete(path); string ergebnis = process.StandardOutput.ReadToEnd(); //cluster auslesen cluster = Helper.dreadnaut2cluster(ergebnis); rmsChart.Series.Clear(); gseries = new Series[nodeCount]; clusterBox.Text = ""; for (int nodenum = 0; nodenum < nodeCount; nodenum++) { gseries[nodenum] = new Series(); gseries[nodenum].IsVisibleInLegend = false; gseries[nodenum].ChartArea = "ChartArea1"; rmsChart.Series.Add(gseries[nodenum]); } for (int i = 0; i < cluster.Length; i++) { clusterBox.Text += "Cluster " + i + " mit Knoten: "; foreach (int k in cluster[i]) { clusterBox.Text += +k + " "; vertices[k].Cluster = i; } clusterBox.Text += "\r\n"; System.Windows.Media.Color coltmp = Vertex.cluster_colors[i % Vertex.cluster_colors.Length]; foreach (int nodenum in cluster[i]) { if (nodenum == cluster[i][0]) { gseries[nodenum].LegendText = "Cluster " + i.ToString(); gseries[nodenum].IsVisibleInLegend = true; } gseries[nodenum].BorderWidth = 2; gseries[nodenum].ChartType = SeriesChartType.FastLine; gseries[nodenum].Color = Color.FromArgb(255, coltmp.R, coltmp.G, coltmp.B); } } //Tmat erstellen if (networkDropdown.SelectedIndex == 3) { //nutze relativkoordinaten wenn custom ausgewählt TMat = Helper.TMat(cluster); } else {//nutze eingespeicherte TMat = Helper.TMat(networkDropdown.SelectedIndex); } //Parameter für die anordnung. einfach irgendwelche genommen. nochmal drüber nachdenken/nachlesen GraphControl = new GraphSharpControl(); GraphControl.layout.LayoutMode = LayoutMode.Simple; GraphControl.layout.LayoutAlgorithmType = "CompoundFDP"; GraphSharp.Algorithms.Layout.Compound.FDP.CompoundFDPLayoutParameters layoutParam = new GraphSharp.Algorithms.Layout.Compound.FDP.CompoundFDPLayoutParameters(); layoutParam.ElasticConstant *= 1.5; GraphControl.layout.LayoutParameters = layoutParam; GraphControl.layout.OverlapRemovalConstraint = AlgorithmConstraints.Must; GraphControl.layout.OverlapRemovalAlgorithmType = "FSA"; GraphSharp.Algorithms.OverlapRemoval.OverlapRemovalParameters overlapParam = new GraphSharp.Algorithms.OverlapRemoval.OverlapRemovalParameters(); overlapParam.HorizontalGap = 25; overlapParam.VerticalGap = 25; GraphControl.layout.OverlapRemovalParameters = overlapParam; GraphControl.layout.HighlightAlgorithmType = "Simple"; GraphControl.layout.Graph = graph; elementHost1.Child = GraphControl; graph_loaded = true; iterator_init(); runButton.Enabled = true; iterateButton.Enabled = true; layoutButton.Enabled = true; betaRunButton.Enabled = true; }