// Copyright (c) 2013-2014 Robert Rouhani and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System.Collections.Generic; namespace SharpNav { /// /// Link all nodes together. Store indices in hash map. /// public class NodePool { //private int hashSize; private List nodes; private Dictionary nodeDict; private int maxNodes; /// /// Initializes a new instance of the class. /// /// The maximum number of nodes that can be stored /// The maximum number of elements in the hash table public NodePool(int maxNodes, int hashSize) { this.maxNodes = maxNodes; //this.hashSize = hashSize; nodes = new List(maxNodes); nodeDict = new Dictionary(new IntNodeIdComparer(hashSize)); } /// /// Reset all the data. /// public void Clear() { nodes.Clear(); nodeDict.Clear(); } /// /// Try to find a node. /// /// Node's id /// The node, if found. Null, if otherwise. public Node FindNode(int id) { Node node; if (nodeDict.TryGetValue(id, out node)) { return node; } return null; } /// /// Try to find the node. If it doesn't exist, create a new node. /// /// Node's id /// The node public Node GetNode(int id) { Node node; if (nodeDict.TryGetValue(id, out node)) { return node; } if (nodes.Count >= maxNodes) return null; Node newNode = new Node(); newNode.ParentIdx = 0; newNode.cost = 0; newNode.total = 0; newNode.Id = id; newNode.Flags = 0; nodes.Add(newNode); nodeDict.Add(id, newNode); return newNode; } /// /// Gets the id of the node. /// /// The node /// The id public int GetNodeIdx(Node node) { if (node == null) return 0; for (int i = 0; i < nodes.Count; i++) { if (nodes[i] == node) return i + 1; } return 0; } /// /// Return a node at a certain index. If index is out-of-bounds, return null. /// /// Node index /// public Node GetNodeAtIdx(int idx) { if (idx <= 0 || idx > nodes.Count) return null; return nodes[idx - 1]; } /// /// Determine whether two nodes are equal /// private class IntNodeIdComparer : IEqualityComparer { private int hashSize; /// /// Initializes a new instance of the class. /// /// The maximum number of elements in the hash table public IntNodeIdComparer(int hashSize) { this.hashSize = hashSize; } /// /// Determines whether two objects or equal or now /// /// The first object /// The second object /// True if equal, false if not equal public bool Equals(int left, int right) { return left == right; } /// /// Gets the hash code for this object /// /// The object /// The hash code public int GetHashCode(int obj) { obj += ~(obj << 15); obj ^= obj >> 10; obj += obj << 3; obj ^= obj >> 6; obj += ~(obj << 11); obj ^= obj >> 16; return obj & (hashSize - 1); } } } }