/// <summary> /// Construct a depdenency graph of the <see cref="Character"/>'s <see cref="ModifierSource"/>s. /// </summary> /// <param name="character"> /// The <see cref="Character"/> to generate the dependency graph for. This cannot be null. /// </param> /// <param name="modifierSources"> /// The already extracted list of <see cref="ModifierSource"/>s to use. This cannot be null. /// </param> /// <returns> /// A <see cref="GraphNode{ModifierSource}"/> that is the root node of a dependency graph. The root /// node can be ignored and is not part of the graph itself. /// </returns> /// <exception cref="ArgumentNullException"> /// No argument can be null. /// </exception> internal static GraphNode<ModifierSource> ConstructDependencyGraph(Character character, IList<ModifierSource> modifierSources) { if (character == null) { throw new ArgumentNullException("character"); } if (modifierSources == null) { throw new ArgumentNullException("modifierSources"); } GraphNode<ModifierSource> root; IEqualityComparer<ModifierSource> comparer; Dictionary<ModifierSource, GraphNode<ModifierSource>> graphNodeLookup; // Rather than use "EqualityComparer<ModifierSource>.Default", use identity equality. // This allows two instances of the same modifier source with the same name to be used // within the graph. This can occur frequently with powers. comparer = new IdentityEqualityComparer<ModifierSource>(); // Optimization for GraphNode.Find(). graphNodeLookup = new Dictionary<ModifierSource, GraphNode<ModifierSource>>(); // Construct a dependency graph. root = new GraphNode<ModifierSource>(new NullModifierSource(), comparer); foreach (ModifierSource modifierSource in modifierSources) { List<KeyValuePair<ModifierSource, ModifierSource>> dependencies; GraphNode<ModifierSource> parentGraphNode; GraphNode<ModifierSource> childGraphNode; // Get the dependencies dependencies = modifierSource.GetDependencies(character); // For each dependency, find the source ModifierSource and add // the destination under it. foreach (KeyValuePair<ModifierSource, ModifierSource> dependency in dependencies) { // Find the parent of the dependency if (!graphNodeLookup.TryGetValue(dependency.Key, out parentGraphNode)) { parentGraphNode = new GraphNode<ModifierSource>(dependency.Key, comparer); root.AddChild(parentGraphNode); graphNodeLookup[dependency.Key] = parentGraphNode; } // Find the child of the dependency if (!graphNodeLookup.TryGetValue(dependency.Value, out childGraphNode)) { childGraphNode = new GraphNode<ModifierSource>(dependency.Value, comparer); graphNodeLookup[dependency.Value] = childGraphNode; } // Add the child to the parent parentGraphNode.AddChild(childGraphNode); } } return root; }
private void PopulateMapsForFileInputNode(GraphNode inputNode) { using (_gate.DisposableWait()) { var projectPath = inputNode.Id.GetNestedValueByName<Uri>(CodeGraphNodeIdName.Assembly); var filePath = inputNode.Id.GetNestedValueByName<Uri>(CodeGraphNodeIdName.File); if (projectPath == null || filePath == null) { return; } var project = _solution.Projects.FirstOrDefault( p => string.Equals(p.FilePath, projectPath.OriginalString, StringComparison.OrdinalIgnoreCase)); if (project == null) { return; } _nodeToContextProjectMap.Add(inputNode, project); var document = project.Documents.FirstOrDefault( d => string.Equals(d.FilePath, filePath.OriginalString, StringComparison.OrdinalIgnoreCase)); if (document == null) { return; } _nodeToContextDocumentMap.Add(inputNode, document); } }
public static void Save(PlanerCore planer, GraphNode node, int direction, bool onPlaySave) { //Debug.Log("OnSave"); //PlayerPrefs.DeleteAll(); PlayerPrefs.SetInt("MineCount", planer.MineController.Mines.Count); //Debug.Log(Application.loadedLevelName); string currentLevel = Application.loadedLevelName; if (currentLevel == "GlobalMap") currentLevel = Creator.PreviousLevel; PlayerPrefs.SetString("CurrentLevel", currentLevel); for (int i = 0; i < planer.MineController.Mines.Count; i++) { PlayerPrefs.SetInt("Mine" + i, Armory.WeaponIndex(planer.MineController.Mines[i].GetType().Name)); } if (onPlaySave) { PlayerPrefs.SetInt("XCoord", node.X); PlayerPrefs.SetInt("YCoord", node.Y); PlayerPrefs.SetInt("IndexCoord", node.Index); PlayerPrefs.SetInt("LevelCoord", node.Level); if(direction<0) direction=planer.Direction; PlayerPrefs.SetInt("Direction", direction); } }
public GraphEdge(GraphNode source, GraphNode destination) { this._source = source; this._destination = destination; source.AdjecentEdges.Add(this); }
public AStarNode(GraphNode<StateConfig> state, AStarNode parent, float pathCost, float estCost) { this.state = state; this.parent = parent; this.pathCost = pathCost; this.estCost = estCost; }
public void SetCurrentNode(GraphNode gn) { if(currentNode != null) currentNode.SetActive(false); currentNode = gn; currentNode.SetActive(true); }
public static void DrawGraphNodeGizmo(GraphNode node, GizmoType type) { using (new GizmosColor(GraphEditorWindow.GetGraphColor(node.graph))) { if (node.graph == null) { Vector3 nodePinPosition = node.transform.position + GraphEditorWindow.GetGraphNodePinShift(node); Gizmos.DrawLine(node.transform.position, nodePinPosition); Gizmos.DrawWireSphere(nodePinPosition, GraphEditorWindow.GraphNodePinRadius * 1.1f); return; } if ((type & GizmoType.Selected) != 0) { GraphEditor.DrawGraphGizmo(node.graph, GizmoType.NonSelected); Vector3 pinShift = GraphEditorWindow.GetGraphNodePinShift(node); Vector3 nodePinPosition = node.transform.position + pinShift; Gizmos.DrawLine(node.transform.position, nodePinPosition); Gizmos.DrawWireSphere(nodePinPosition, GraphEditorWindow.GraphNodePinRadius * 1.1f); foreach (GraphNode linkedNode in node.EnumLinkedNodes()) { Gizmos.DrawLine(nodePinPosition, linkedNode.transform.position + pinShift); } } else if (type == GizmoType.NonSelected) { Vector3 pinShift = GraphEditorWindow.GetGraphNodePinShift(node); Vector3 nodePinPosition = node.transform.position + pinShift; Gizmos.DrawLine(node.transform.position, nodePinPosition); Gizmos.DrawSphere(nodePinPosition, GraphEditorWindow.GraphNodePinRadius); } } }
public void ShouldFindShortesPathWhen1PathExists() { //http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm var one = new GraphNode<int>(1); var two = new GraphNode<int>(2); var three = new GraphNode<int>(3); var four = new GraphNode<int>(4); var five = new GraphNode<int>(5); var six = new GraphNode<int>(6); one.AddNeighbour(six, 14); one.AddNeighbour(three, 9); one.AddNeighbour(two, 7); two.AddNeighbour(three, 10); two.AddNeighbour(four, 15); three.AddNeighbour(six, 2); three.AddNeighbour(four, 11); four.AddNeighbour(five, 6); five.AddNeighbour(six, 9); var graph = new List<GraphNode<int>> {one, two, three, four, five, six}; var dijkstra = new Dijkstra<int>(graph); var path = dijkstra.FindShortestPathBetween(one, five); path[0].Value.ShouldBe(1); path[1].Value.ShouldBe(3); path[2].Value.ShouldBe(6); path[3].Value.ShouldBe(5); }
protected override void OnLoad(EventArgs e) { node = Node; if (node is DR_Goals) { viewMorph = new GoalViewMini((DR_Goals)node); } else if (node is DR_Fragments) { viewMorph = new FragmentViewMini((DR_Fragments)node); } else if (node is DR_Tags) { viewMorph = new TagViewMini((DR_Tags)node); } else if (node is DR_GraphEdges) { viewMorph = new EdgeViewMini((DR_GraphEdges)node); } else throw new NotImplementedException("Not implemented: NodeViewMini(" + node.GetType().ToString() + ")"); Controls.Add(viewMorph); base.OnLoad(e); }
public static bool findLinkV5(GraphNode start, GraphNode end) { System.Collections.Generic.Queue<GraphNode> searched = new System.Collections.Generic.Queue<GraphNode>(); searched.Enqueue(start); start.state = Visiting; while (searched.Count!=0) { GraphNode gn = searched.Dequeue(); if (gn!=null) { gn.state = Visited; foreach (GraphNode node in gn.Nodes) { if (node.state == Unvisitied) { if (node == end) { return true; } node.state = Visiting; searched.Enqueue(node); } } } } return false; }
public void TestMatrixGraph() { var emptyGraph = new MatrixGraph<int>(); var root = new GraphNode<int>(10); var expandedGraph = root.MakeEdges<int>(null); }
static void Main(string[] args) { GraphNode rootGraph = new GraphNode(null, "Root"); GraphNode child1 = new GraphNode(null, "Child1"); GraphNode child2 = new GraphNode(null, "Child2"); rootGraph.AddChildNode(child1); rootGraph.AddChildNode(child2); // physics update frame 1 ---------------------------- Console.WriteLine("*** Frame 1 ***"); child2.SetTransform(new Transform(child2.Local.Name)); // simulates some kind of physical force Console.WriteLine("----- Simple traversal -----"); rootGraph.SimpleRender(Transform.Origin); Console.WriteLine(); Console.WriteLine("----- Dirty-flag traversal -----"); rootGraph.DirtyFlagRender(Transform.Origin, rootGraph.Dirty); Console.WriteLine(); Console.WriteLine(); // physics update frame 2 ---------------------------- Console.WriteLine("*** Frame 2 ***"); child1.SetTransform(new Transform(child1.Local.Name)); // simulates some kind of physical force Console.WriteLine(); Console.WriteLine("----- Simple traversal -----"); rootGraph.SimpleRender(Transform.Origin); Console.WriteLine(); Console.WriteLine("----- Dirty-flag traversal -----"); rootGraph.DirtyFlagRender(Transform.Origin, rootGraph.Dirty); Console.WriteLine(); Console.WriteLine(); // physics update frame 3 ---------------------------- Console.WriteLine("*** Frame 3 ***"); rootGraph.SetTransform(new Transform(rootGraph.Local.Name)); // simulates some kind of physical force Console.WriteLine(); Console.WriteLine("----- Simple traversal -----"); rootGraph.SimpleRender(Transform.Origin); Console.WriteLine(); Console.WriteLine("----- Dirty-flag traversal -----"); rootGraph.DirtyFlagRender(Transform.Origin, rootGraph.Dirty); Console.ReadLine(); }
public void AddNode(Vector3 neighborPoint, ref GraphNode currentNode, ref Queue<GraphNode> q ) { RaycastHit hitInfo; Vector3 rayDirection = Vector3.zero; #if USE_XZ rayDirection = new Vector3(0, -1, 0); #else rayDirection = new Vector3(0, 0, 1); #endif //USE_XZ int layerMask = 1 << 8; layerMask = ~layerMask; if ( Physics.Raycast(neighborPoint, rayDirection, out hitInfo, Mathf.Infinity, layerMask) ) { if (hitInfo.transform.tag == "Ground") { GraphNode newNode = new GraphNode(mNumOfNodes, hitInfo.point); // make a new node for this point GraphEdge newEdge = new GraphEdge(currentNode.GetIndex(), newNode.GetIndex()); // creat a new edge int index = 0; bool nodeFound = false; while ( !nodeFound && index <= mNumOfNodes ) { //Debug.Log (index + " out of " + NavigationGraph.Length + " thinks there's only" + mNumOfNodes); nodeFound = ( NavigationGraph[index] == hitInfo.point ); ++index; } if ( !nodeFound ) // if we have not found this node before, add it { Nodes.Add(newNode); NavigationGraph[mNumOfNodes] = hitInfo.point; ++mNumOfNodes; q.Enqueue(newNode); } else { newEdge.SetToIndex(index-1); } // If the raycast hit then we will always want to add the edge, since we want edges // in both directions and there won't ever be duplicates. // check if there is a clear path to add an edge Vector3 heightOffset = Vector3.zero; #if USE_XZ heightOffset = new Vector3(0, 0.5f, 0); #else heightOffset = new Vector3(0, 0, -0.5f); #endif // USE_XZ if ( !Physics.Linecast(currentNode.GetPosition() + heightOffset, newNode.GetPosition() + heightOffset, out hitInfo, layerMask) ) { Edges.Add(newEdge); currentNode.AddEdge(newEdge); } } } }
public void Test_AddChild_CircularReferenceOneLevel() { GraphNode<string> parent = new GraphNode<string>("parent"); GraphNode<string> child = new GraphNode<string>("child"); parent.AddChild(child); Assert.That(() => child.AddChild(parent), Throws.ArgumentException.And.Property("ParamName").EqualTo("graphNode")); }
public int AddNode(Vector3 position) { Nodes.Add(new GraphNode(NextNodeIndex, position)); Edges.Add(new List<GraphEdge>()); GraphNode n = new GraphNode(NextNodeIndex, position); NextNodeIndex++; return NextNodeIndex - 1; }
public void SetState(MshipState s, GraphNode n) { state = s; gn = n; if(s == MshipState.TRAVEL) travelDist = (gn.transform.position - transform.position).magnitude - orbitDist; }
private static async Task AddImplementedSymbols(GraphBuilder graphBuilder, GraphNode node, IEnumerable<ISymbol> implementedSymbols) { foreach (var interfaceType in implementedSymbols) { var interfaceTypeNode = await graphBuilder.AddNodeForSymbolAsync(interfaceType, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(node, CodeLinkCategories.Implements, interfaceTypeNode); } }
void Awake() { foreach (Anchor anchor in GetComponentsInChildren<Anchor>()) { anchorList.Add(anchor); } graphNode = GetComponentInChildren<GraphNode> (); renderers = GetComponentsInChildren<Renderer> (); }
public TripleInfo(GraphNode subjectType, string subject, GraphNode verbType, string verb, GraphNode objectType, string obj) { SubjectType = subjectType; Subject = subject; VerbType = verbType; Verb = verb; ObjectType = objectType; Object = obj; }
/// <summary> /// Creates a new instance of <see cref="Edge"/>. /// </summary> public Edge(GraphNode id, string label, IDictionary<string, GraphNode> properties, GraphNode inV, string inVLabel, GraphNode outV, string outVLabel) : base(id, label, properties) { InV = inV; InVLabel = inVLabel; OutV = outV; OutVLabel = outVLabel; }
public bool LinkToNode(GraphNode to) { if (to.graph != graph) return false; graph.AddLink(this, to); return true; }
/* * Adds a node to the graph, but only if it is not already present. * Returns true if the node is added, false otherwise. */ public bool addNode(GraphNode<StateConfig> node) { if(!this.hasNode(ref node)){ nodes.Add(node); return true; } else { return false; } }
public void ShouldFindShortesPathWhen2PathExists() { //2 paths exist //O A B D T //O A B E D T // ReSharper disable InconsistentNaming var O = new GraphNode<string>("O"); var A = new GraphNode<string>("A"); var B = new GraphNode<string>("B"); var C = new GraphNode<string>("C"); var D = new GraphNode<string>("D"); var E = new GraphNode<string>("E"); var F = new GraphNode<string>("F"); var T = new GraphNode<string>("T"); // ReSharper restore InconsistentNaming O.AddNeighbour(A, 2); O.AddNeighbour(B, 5); O.AddNeighbour(C, 4); A.AddNeighbour(F, 12); A.AddNeighbour(D, 7); A.AddNeighbour(B, 2); B.AddNeighbour(D, 4); B.AddNeighbour(E, 3); B.AddNeighbour(C, 1); C.AddNeighbour(E, 4); D.AddNeighbour(T, 5); D.AddNeighbour(E, 1); E.AddNeighbour(T, 7); F.AddNeighbour(T, 3); var graph = new List<GraphNode<string>> { O, A, B, C, D, E, F, T }; var dijkstra = new Dijkstra<string>(graph); var path = dijkstra.FindShortestPathBetween(O, T); //The other alternate path //path[0].Value.ShouldBe("O"); //path[1].Value.ShouldBe("A"); //path[2].Value.ShouldBe("B"); //path[3].Value.ShouldBe("E"); //path[4].Value.ShouldBe("D"); //path[5].Value.ShouldBe("T"); path[0].Value.ShouldBe("O"); path[1].Value.ShouldBe("A"); path[2].Value.ShouldBe("B"); path[3].Value.ShouldBe("D"); path[4].Value.ShouldBe("T"); }
private DependencyManager( GraphNode<Library> graph, Dictionary<string, Library> librariesByName, Dictionary<string, ISet<Library>> librariesByType) { _graph = graph; _librariesByName = librariesByName; _librariesByType = librariesByType; }
private static System.Collections.IEnumerable/*<GraphNode/*!>/*!*/ Succs(GraphNode n) { Contract.Requires(n != null); Contract.Ensures(Contract.Result<System.Collections.IEnumerable>() != null); List<GraphNode/*!*/>/*!*/ AllEdges = new List<GraphNode/*!*/>(); AllEdges.AddRange(n.ForwardEdges); AllEdges.AddRange(n.BackEdges); return AllEdges; }
public void ShouldDetectNoPath() { var nine = new GraphNode<int>(9); _graph.AddNode(nine); var pather = new Pather<int>(_graph); var path = pather.CalculateShortesPath(one, nine).ToArray(); path.Count().ShouldBe(0); }
public void One_Node_In_Graph_Returns_Valid_Path_Of_Length_One() { var graph = new GraphNode<int> { Value = 1 }; var walker = new GraphWalker<int>(graph); var walkingPath = walker.WalkToNode(1); Assert.AreEqual(true, walkingPath.IsValid); Assert.AreEqual(1, walkingPath.Path.Count, "Path length should be one (node) for single node graph"); }
public void AddLink(GraphNode a, GraphNode b) { List<GraphNode> nodeLinks; if (links.TryGetValue(a, out nodeLinks)) { nodeLinks.Add(b); } else { links.Add(a, new List<GraphNode> { b }); } }
internal static int GetDisplayIndex(GraphNode node) { GraphCategory graphCategory = node.Categories.FirstOrDefault(); if (graphCategory == null) return int.MaxValue; if (graphCategory.Id == PaketCategory.Id) return 1; return int.MaxValue; }
internal bool DFSHasCycles(GraphNode<int> actualNode, GraphNode<int> mainNode) { if(actualNode.Neighbors.Contains(mainNode)) return true; foreach (GraphNode<int> n in actualNode.Neighbors) if (DFSHasCycles(n, mainNode)) return true; return false; }
private void Select(GraphNode node) { BeginSelection(); inspector.Inspect(node); EndSelection(); }
public static GraphNode XmlCodecRoundtrip(GraphNode root) { return(XmlCodecRoundtrip(root, new XmlObjectGraphCodec())); }
private void HandleInput() { var evt = Event.current; // Handle left mouse button actions if (evt.isMouse && evt.button == 0) { switch (evt.type) { case EventType.MouseDown: { var node = GetNodeAtPoint(evt.mousePosition); if (node != null && node.NodeType == NodeType.Normal) { draggingNode = node; isDragging = true; Select(node); } isMouseDown = true; evt.Use(); break; } case EventType.MouseUp: { if (!isDragging) { TrySelectGraphObject(evt.mousePosition); } isMouseDown = false; draggingNode = null; isDragging = false; evt.Use(); break; } case EventType.MouseDrag: { if (isMouseDown && !isDragging && draggingNode != null) { isDragging = true; } if (isDragging) { draggingNode.Position = GetNormalizedPositionOnGraph(evt.mousePosition); Repaint(); } evt.Use(); break; } } } // Handle right mouse button actions else if (evt.type == EventType.ContextClick) { bool hasOpenedContextMenu = false; foreach (var node in Flow.Nodes) { if (GetNodeBounds(node).Contains(evt.mousePosition)) { HandleNodeContextMenu(node); hasOpenedContextMenu = true; contextMenuPosition = evt.mousePosition; break; } } if (!hasOpenedContextMenu) { foreach (var line in Flow.Lines) { if (GetLineBounds(line).Contains(evt.mousePosition)) { HandleLineContextMenu(line); hasOpenedContextMenu = true; contextMenuPosition = evt.mousePosition; break; } } } evt.Use(); } }
public abstract void AppendToOutput(GraphModel model, GraphNode node);
public static GraphNode XmlCodecRoundtrip(GraphNode root, HashSet <ObjectGraphComparisonStrategy> strategies) { return(XmlCodecRoundtrip(root, new XmlObjectGraphCodec(strategies))); }
//finds the distance between two points along right angles float manhattanDist(GraphNode toNode, GraphNode fromNode) { float Distance = Mathf.Abs(toNode.position.x - fromNode.position.x) + Mathf.Abs(toNode.position.y - fromNode.position.y); return(Distance); }
public void FloodFill(GraphNode seed, uint area) { this.graphUpdates.FloodFill(seed, area); }
public static void ObjectToConsole(object value, ObjectGraphFactory factory) { GraphNode root = factory.CreateObjectGraph(value); Console.WriteLine(StringFromGraph(root)); }
public List <Link> GetConnectedRoadLines(Road road, RoadLine line, List <Link> connectedLines, GraphNode node) { for (int i = 0; i < node.ConnectedNodes.Count; i++) { if (road.GetRoadLineByNode(node.ConnectedNodes[i]) != line) { Road tempRoad = GlobalAINavigator.GetRoadByNode(node, node.ConnectedNodes[i]); if (tempRoad != null) { RoadLine tempLine = tempRoad.GetRoadLineByNode(node.ConnectedNodes[i]); if (tempLine != null) { connectedLines.Add(new Link(node, node.ConnectedNodes[i], tempLine)); } } } } return(connectedLines); }
/// <summary> /// Generates search graph containing nodes matching search criteria in Solution Explorer /// and attaches it to correct top level node. /// </summary> private void Search(IGraphContext graphContext) { string searchParametersTypeName = typeof(ISolutionSearchParameters).GUID.ToString(); ISolutionSearchParameters searchParameters = graphContext.GetValue <ISolutionSearchParameters>(searchParametersTypeName); string?searchTerm = searchParameters?.SearchQuery.SearchString; if (searchTerm == null) { return; } var cachedDependencyToMatchingResultsMap = new Dictionary <string, HashSet <IDependency> >(StringComparers.DependencyTreeIds); var searchResultsPerContext = new Dictionary <string, HashSet <IDependency> >(StringComparers.Paths); System.Collections.Generic.IReadOnlyCollection <DependenciesSnapshot> snapshots = AggregateSnapshotProvider.GetSnapshots(); foreach (DependenciesSnapshot snapshot in snapshots) { searchResultsPerContext[snapshot.ProjectPath] = SearchFlat(searchTerm, snapshot); } foreach (DependenciesSnapshot snapshot in snapshots) { IEnumerable <IDependency> allTopLevelDependencies = snapshot.GetFlatTopLevelDependencies(); HashSet <IDependency> matchedDependencies = searchResultsPerContext[snapshot.ProjectPath]; using var scope = new GraphTransactionScope(); foreach (IDependency topLevelDependency in allTopLevelDependencies) { TargetedDependenciesSnapshot targetedSnapshot = snapshot.DependenciesByTargetFramework[topLevelDependency.TargetFramework]; if (!cachedDependencyToMatchingResultsMap.TryGetValue( topLevelDependency.Id, out HashSet <IDependency>?topLevelDependencyMatches)) { IDependenciesGraphViewProvider?viewProvider = FindViewProvider(topLevelDependency); if (viewProvider == null) { continue; } if (!viewProvider.MatchSearchResults( topLevelDependency, searchResultsPerContext, out topLevelDependencyMatches)) { if (matchedDependencies.Count == 0) { continue; } topLevelDependencyMatches = GetMatchingResultsForDependency( topLevelDependency, targetedSnapshot, matchedDependencies, cachedDependencyToMatchingResultsMap); } cachedDependencyToMatchingResultsMap[topLevelDependency.Id] = topLevelDependencyMatches; } if (topLevelDependencyMatches.Count == 0) { continue; } GraphNode topLevelNode = _builder.AddTopLevelGraphNode( graphContext, snapshot.ProjectPath, topLevelDependency.ToViewModel(targetedSnapshot)); foreach (IDependency matchedDependency in topLevelDependencyMatches) { GraphNode matchedDependencyNode = _builder.AddGraphNode( graphContext, snapshot.ProjectPath, topLevelNode, matchedDependency.ToViewModel(targetedSnapshot)); graphContext.Graph.Links.GetOrCreate( topLevelNode, matchedDependencyNode, label: null, GraphCommonSchema.Contains); } if (topLevelNode != null) { // 'node' is a GraphNode for top level dependency (which is part of solution explorer tree) // Setting ProjectItem category (and correct GraphNodeId) ensures that search graph appears // under right solution explorer hierarchy item topLevelNode.AddCategory(CodeNodeCategories.ProjectItem); } } scope.Complete(); } graphContext.OnCompleted(); }
public override bool TryParse(TokenStack tokens, out GraphNode node) { var source = new Queue <Token>(); string blockIdentifier = null; bool isMain = false; if (tokens.ExpectSequence(TokenType.BlockKeyword, TokenType.MainKeyword, TokenType.Identifier, TokenType.OpenCurlyBraceSymbol)) { var blockKeyword = tokens.Pop(); var mainKeyword = tokens.Pop(); var identifier = tokens.Pop(); var openBrace = tokens.Pop(); source.Enqueue(blockKeyword); source.Enqueue(mainKeyword); source.Enqueue(identifier); source.Enqueue(openBrace); blockIdentifier = identifier.Value; isMain = true; } else if (tokens.ExpectSequence(TokenType.BlockKeyword, TokenType.Identifier, TokenType.OpenCurlyBraceSymbol)) { var blockKeyword = tokens.Pop(); var identifier = tokens.Pop(); var openBrace = tokens.Pop(); source.Enqueue(blockKeyword); source.Enqueue(identifier); source.Enqueue(openBrace); blockIdentifier = identifier.Value; } else { while (source.Count > 0) { tokens.Push(source.Dequeue()); } // TODO: syntax error node = null; return(false); } var blockChildren = new List <GraphNode>(); while (tokens.Peek().TokenType != TokenType.CloseCurlyBraceSymbol) { var bodySyntax = new BodySyntax(); if (bodySyntax.TryParse(tokens, out GraphNode body)) { blockChildren.Add(body); } else { while (source.Count > 0) { tokens.Push(source.Dequeue()); } // TODO: syntax error node = null; return(false); } } source.Enqueue(tokens.Pop()); node = new BlockDeclaration(source, blockIdentifier, isMain, blockChildren.ToArray()); return(true); }
public uint GetTraversalCost(Path path, GraphNode node) { // Same as default implementation return(path.GetTagPenalty((int)node.Tag) + node.Penalty); }
private static void UpdatePropertiesForNode(ISymbol symbol, GraphNode node) { // Set accessibility properties switch (symbol.DeclaredAccessibility) { case Accessibility.Public: node[Properties.IsPublic] = true; break; case Accessibility.Internal: node[Properties.IsInternal] = true; break; case Accessibility.Protected: node[Properties.IsProtected] = true; break; case Accessibility.Private: node[Properties.IsPrivate] = true; break; case Accessibility.ProtectedOrInternal: node[Properties.IsProtectedOrInternal] = true; break; case Accessibility.ProtectedAndInternal: node[Properties.IsProtected] = true; node[Properties.IsInternal] = true; break; case Accessibility.NotApplicable: break; } // Set common properties if (symbol.IsAbstract) { node[Properties.IsAbstract] = true; } if (symbol.IsSealed) { // For VB module, do not set IsFinal since it's not inheritable. if (!symbol.IsModuleType()) { node[Properties.IsFinal] = true; } } if (symbol.IsStatic) { node[Properties.IsStatic] = true; } if (symbol.IsVirtual) { node[Properties.IsVirtual] = true; } if (symbol.IsOverride) { // The property name is a misnomer, but this is what the previous providers do. node[Microsoft.VisualStudio.Progression.DgmlProperties.IsOverloaded] = true; } // Set type-specific properties var typeSymbol = symbol as ITypeSymbol; if (typeSymbol != null && typeSymbol.IsAnonymousType) { node[Properties.IsAnonymous] = true; } else if (symbol is IMethodSymbol) { UpdateMethodPropertiesForNode((IMethodSymbol)symbol, node); } }
public async Task <GraphNode> AddNodeForSymbolAsync(ISymbol symbol, Project contextProject, Document contextDocument) { // Figure out what the location for this node should be. We'll arbitrarily pick the // first one, unless we have a contextDocument to restrict it var preferredLocation = symbol.Locations.FirstOrDefault(l => l.SourceTree != null); if (contextDocument != null) { var syntaxTree = await contextDocument.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); // If we have one in that tree, use it preferredLocation = symbol.Locations.FirstOrDefault(l => l.SourceTree == syntaxTree) ?? preferredLocation; } // We may need to look up source code within this solution if (preferredLocation == null && symbol.Locations.Any(loc => loc.IsInMetadata)) { var newSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, contextProject.Solution, _cancellationToken).ConfigureAwait(false); if (newSymbol != null) { preferredLocation = newSymbol.Locations.Where(loc => loc.IsInSource).FirstOrDefault(); } } using (_gate.DisposableWait()) { GraphNode node = await GetOrCreateNodeAsync(_graph, symbol, _solution, _cancellationToken).ConfigureAwait(false); node[RoslynGraphProperties.SymbolId] = (SymbolKey?)symbol.GetSymbolKey(); node[RoslynGraphProperties.ContextProjectId] = GetContextProjectId(contextProject, symbol); node[RoslynGraphProperties.ExplicitInterfaceImplementations] = symbol.ExplicitInterfaceImplementations().Select(s => s.GetSymbolKey()).ToList(); node[RoslynGraphProperties.DeclaredAccessibility] = symbol.DeclaredAccessibility; node[RoslynGraphProperties.SymbolModifiers] = symbol.GetSymbolModifiers(); node[RoslynGraphProperties.SymbolKind] = symbol.Kind; if (contextDocument != null) { node[RoslynGraphProperties.ContextDocumentId] = contextDocument.Id; } if (preferredLocation != null) { var lineSpan = preferredLocation.GetLineSpan(); var sourceLocation = new SourceLocation( preferredLocation.SourceTree.FilePath, new Position(lineSpan.StartLinePosition.Line, lineSpan.StartLinePosition.Character), new Position(lineSpan.EndLinePosition.Line, lineSpan.EndLinePosition.Character)); node[CodeNodeProperties.SourceLocation] = sourceLocation; } // Keep track of this as a node we have added. Note this is a HashSet, so if the node was already added // we won't double-count. _createdNodes.Add(node); _nodeToSymbolMap[node] = symbol; _nodeToContextProjectMap[node] = contextProject; _nodeToContextDocumentMap[node] = contextDocument; return(node); } }
private void ArrangeChild(GraphNode node, bool ignoneSibling = false) { var child = node.Element; var childSize = child.DesiredSize; var childPos = new Point(); #region 容器居中对齐 if (GetAlignHorizontalCenterWithPanel(child)) { childPos.X = (_arrangeSize.Width - childSize.Width) / 2; } if (GetAlignVerticalCenterWithPanel(child)) { childPos.Y = (_arrangeSize.Height - childSize.Height) / 2; } #endregion var alignLeftWithPanel = GetAlignLeftWithPanel(child); var alignTopWithPanel = GetAlignTopWithPanel(child); var alignRightWithPanel = GetAlignRightWithPanel(child); var alignBottomWithPanel = GetAlignBottomWithPanel(child); if (!ignoneSibling) { #region 元素间位置 if (node.LeftOfNode != null) { childPos.X = node.LeftOfNode.Position.X - childSize.Width; } if (node.AboveNode != null) { childPos.Y = node.AboveNode.Position.Y - childSize.Height; } if (node.RightOfNode != null) { childPos.X = node.RightOfNode.Position.X + node.RightOfNode.Element.DesiredSize.Width; } if (node.BelowNode != null) { childPos.Y = node.BelowNode.Position.Y + node.BelowNode.Element.DesiredSize.Height; } #endregion #region 元素居中对齐 if (node.AlignHorizontalCenterWith != null) { childPos.X = node.AlignHorizontalCenterWith.Position.X + (node.AlignHorizontalCenterWith.Element.DesiredSize.Width - childSize.Width) / 2; } if (node.AlignVerticalCenterWith != null) { childPos.Y = node.AlignVerticalCenterWith.Position.Y + (node.AlignVerticalCenterWith.Element.DesiredSize.Height - childSize.Height) / 2; } #endregion #region 元素间对齐 if (node.AlignLeftWithNode != null) { childPos.X = node.AlignLeftWithNode.Position.X; } if (node.AlignTopWithNode != null) { childPos.Y = node.AlignTopWithNode.Position.Y; } if (node.AlignRightWithNode != null) { childPos.X = node.AlignRightWithNode.Element.DesiredSize.Width + node.AlignRightWithNode.Position.X - childSize.Width; } if (node.AlignBottomWithNode != null) { childPos.Y = node.AlignBottomWithNode.Element.DesiredSize.Height + node.AlignBottomWithNode.Position.Y - childSize.Height; } #endregion } #region 容器对齐 if (alignLeftWithPanel) { if (node.AlignRightWithNode != null) { childPos.X = (node.AlignRightWithNode.Element.DesiredSize.Width + node.AlignRightWithNode.Position.X - childSize.Width) / 2; } else { childPos.X = 0; } } if (alignTopWithPanel) { if (node.AlignBottomWithNode != null) { childPos.Y = (node.AlignBottomWithNode.Element.DesiredSize.Height + node.AlignBottomWithNode.Position.Y - childSize.Height) / 2; } else { childPos.Y = 0; } } if (alignRightWithPanel) { if (alignLeftWithPanel) { childPos.X = (_arrangeSize.Width - childSize.Width) / 2; } else if (node.AlignLeftWithNode == null) { childPos.X = _arrangeSize.Width - childSize.Width; } else { childPos.X = (_arrangeSize.Width + node.AlignLeftWithNode.Position.X - childSize.Width) / 2; } } if (alignBottomWithPanel) { if (alignTopWithPanel) { childPos.Y = (_arrangeSize.Height - childSize.Height) / 2; } else if (node.AlignTopWithNode == null) { childPos.Y = _arrangeSize.Height - childSize.Height; } else { childPos.Y = (_arrangeSize.Height + node.AlignLeftWithNode.Position.Y - childSize.Height) / 2; } } #endregion child.Arrange(new Rect(childPos.X, childPos.Y, childSize.Width, childSize.Height)); node.Position = childPos; node.Arranged = true; }
public void AddDirectedEdge(GraphNode <T> from, GraphNode <T> to) { from.Neighbors.Add(to); }
public abstract void BuildGraph( IGraphContext graphContext, string projectPath, IDependency dependency, GraphNode dependencyGraphNode, TargetedDependenciesSnapshot targetedSnapshot);
internal void InitializeNode(GraphNode node) { this.pathProcessor.InitializeNode(node); }
public Link(GraphNode key, GraphNode connectedTo, RoadLine value) { Key = key; Value = value; ConnectedTo = connectedTo; }
public abstract void UpdateIntAttributeValue(GraphModel model, GraphNode parentNode, string name, int val);
internal void DestroyNode(GraphNode node) { this.pathProcessor.DestroyNode(node); }
public GraphNode <T> AddNode(GraphNode <T> node) { // adds a node to the graph nodeSet.Add(node); return(node); }
private void LineContextMenuCallback(object obj) { GraphContextCommand cmd = (GraphContextCommand)obj; switch (cmd) { case GraphContextCommand.AddNode: { GraphNode node = new GraphNode(Flow); node.Label = "New Node"; node.Position = GetNormalizedPositionOnGraph(contextMenuPosition); Flow.Nodes.Add(node); break; } case GraphContextCommand.Delete: { if (Flow.Lines.Count > 1) { int lineIndex = Flow.Lines.IndexOf(contextMenuLine); Flow.Lines.RemoveAt(lineIndex); if (lineIndex == 0) { var replacementLine = Flow.Lines[0]; replacementLine.Position = 0; replacementLine.Length += contextMenuLine.Length; } else { var replacementLine = Flow.Lines[lineIndex - 1]; replacementLine.Length += contextMenuLine.Length; } } break; } case GraphContextCommand.SplitLine: { float position = GetNormalizedPositionOnGraph(contextMenuPosition); float originalLength = contextMenuLine.Length; int index = Flow.Lines.IndexOf(contextMenuLine); float totalLength = 0; for (int i = 0; i < index; i++) { totalLength += Flow.Lines[i].Length; } contextMenuLine.Length = position - totalLength; GraphLine newSegment = new GraphLine(Flow); foreach (var dungeonArchetype in contextMenuLine.DungeonArchetypes) { newSegment.DungeonArchetypes.Add(dungeonArchetype); } newSegment.Position = position; newSegment.Length = originalLength - contextMenuLine.Length; Flow.Lines.Insert(index + 1, newSegment); break; } } }
protected override bool IsVariableTargetNode(GraphNode node) { // Nodes that have relevant attributes and are not travel nodes (+10 int/str/dex) can be selected // as target nodes. return _nodeAttributes[node.Id].Count > 0 && !_areTravelNodes[node.Id]; }
public Task <GraphNode> AddNodeForSymbolAsync(ISymbol symbol, GraphNode relatedNode) { // The lack of a lock here is acceptable, since each of the functions lock, and GetContextProject/GetContextDocument // never change for the same input. return(AddNodeForSymbolAsync(symbol, GetContextProject(relatedNode), GetContextDocument(relatedNode))); }
public abstract void UpdateFloatTensor(GraphModel model, GraphNode parentNode, string name, float[] data, long[] dims);
private static void UpdateLabelsForNode(ISymbol symbol, Solution solution, GraphNode node) { var progressionLanguageService = solution.Workspace.Services.GetLanguageServices(symbol.Language).GetService <IProgressionLanguageService>(); // A call from unittest may not have a proper language service. if (progressionLanguageService != null) { node[RoslynGraphProperties.Description] = progressionLanguageService.GetDescriptionForSymbol(symbol, includeContainingSymbol: false); node[RoslynGraphProperties.DescriptionWithContainingSymbol] = progressionLanguageService.GetDescriptionForSymbol(symbol, includeContainingSymbol: true); node[RoslynGraphProperties.FormattedLabelWithoutContainingSymbol] = progressionLanguageService.GetLabelForSymbol(symbol, includeContainingSymbol: false); node[RoslynGraphProperties.FormattedLabelWithContainingSymbol] = progressionLanguageService.GetLabelForSymbol(symbol, includeContainingSymbol: true); } switch (symbol.Kind) { case SymbolKind.NamedType: var typeSymbol = (INamedTypeSymbol)symbol; if (typeSymbol.IsGenericType) { // Symbol.name does not contain type params for generic types, so we populate them here for some requiring cases like VS properties panel. node.Label = (string)node[RoslynGraphProperties.FormattedLabelWithoutContainingSymbol]; // Some consumers like CodeMap want to show types in an unified way for both C# and VB. // Therefore, populate a common label property using only name and its type parameters. // For example, VB's "Goo(Of T)" or C#'s "Goo<T>(): T" will be shown as "Goo<T>". // This property will be used for drag-and-drop case. var commonLabel = new System.Text.StringBuilder(); commonLabel.Append(typeSymbol.Name); commonLabel.Append("<"); commonLabel.Append(string.Join(", ", typeSymbol.TypeParameters.Select(t => t.Name))); commonLabel.Append(">"); node[Microsoft.VisualStudio.ArchitectureTools.ProgressiveReveal.ProgressiveRevealSchema.CommonLabel] = commonLabel.ToString(); return; } else { node.Label = symbol.Name; } break; case SymbolKind.Method: var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.Constructor) { node.Label = CodeQualifiedIdentifierBuilder.SpecialNames.GetConstructorLabel(methodSymbol.ContainingSymbol.Name); } else if (methodSymbol.MethodKind == MethodKind.StaticConstructor) { node.Label = CodeQualifiedIdentifierBuilder.SpecialNames.GetStaticConstructorLabel(methodSymbol.ContainingSymbol.Name); } else if (methodSymbol.MethodKind == MethodKind.Destructor) { node.Label = CodeQualifiedIdentifierBuilder.SpecialNames.GetFinalizerLabel(methodSymbol.ContainingSymbol.Name); } else { node.Label = methodSymbol.Name; } break; case SymbolKind.Property: node.Label = symbol.MetadataName; var propertySymbol = (IPropertySymbol)symbol; if (propertySymbol.IsIndexer && LanguageNames.CSharp == propertySymbol.Language) { // For C# indexer, we will strip off the "[]" node.Label = symbol.Name.Replace("[]", string.Empty); } break; case SymbolKind.Namespace: // Use a name with its parents (e.g., A.B.C) node.Label = symbol.ToDisplayString(); break; default: node.Label = symbol.Name; break; } // When a node is dragged and dropped from SE to CodeMap, its label could be reset during copying to clipboard. // So, we try to keep its label that we computed above in a common label property, which CodeMap can access later. node[Microsoft.VisualStudio.ArchitectureTools.ProgressiveReveal.ProgressiveRevealSchema.CommonLabel] = node.Label; }
public GraphNode Add(GraphNode node) { node.Next = top; top = node; return(node); }
public static bool Search(GraphNode source, GraphNode destination, ref List <GraphNode> path, int maxSteps) { bool found = false; //A* algorithm SimplePriorityQueue <GraphNode> nodes = new SimplePriorityQueue <GraphNode>(); source.Cost = 0; source.Heuristic = Vector3.Distance(source.transform.position, destination.transform.position); nodes.Enqueue(source, source.Cost); // set the current number of steps int steps = 0; while (!found && nodes.Count > 0 && steps++ < maxSteps) { // <dequeue node> GraphNode node = nodes.Dequeue(); if (node == destination) { // <set found to true> found = true; // <continue, do not execute the rest of this loop> continue; } foreach (GraphNode.Edge edge in node.Edges) { // calculate cost to nodeB = node cost + edge distance (nodeA to nodeB) float cost = node.Cost + Vector3.Distance(edge.nodeA.transform.position, edge.nodeB.transform.position); // if cost < nodeB cost, add to priority queue if (cost < edge.nodeB.Cost) { // <set nodeB cost to cost> edge.nodeB.Cost = cost; // <set nodeB parent to node> edge.nodeB.Parent = node; // calculate heuristic = Vector3.Distance (nodeB <-> destination) edge.nodeB.Heuristic = Vector3.Distance(edge.nodeB.transform.position, destination.transform.position); // <enqueue without duplicates nodeB with nodeB cost + nodeB heuristics as priority> nodes.EnqueueWithoutDuplicates(edge.nodeB, edge.nodeB.Cost + edge.nodeB.Heuristic); } } } // create a list of graph nodes (path) path = new List <GraphNode>(); // if found is true if (found) { GraphNode node = destination; // while node not null while (node != null) { // <add node to path list> path.Add(node); // <set node to node.Parent> node = node.Parent; } // reverse path path.Reverse(); } else { // add all nodes to path while (nodes.Count > 0) { // <add (dequeued node) to path> GraphNode node = nodes.Dequeue(); path.Add(node); } } return(found); }
public int GetNodeIdentifier(GraphNode node) { return(node == null ? -1 : node.NodeIndex); }