Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 22.38 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Pathfinding.WindowsStore;
  5. #if UNITY_WINRT && !UNITY_EDITOR
  6. //using MarkerMetro.Unity.WinLegacy.IO;
  7. //using MarkerMetro.Unity.WinLegacy.Reflection;
  8. #endif
  9.  
  10. namespace Pathfinding {
  11.     [System.Serializable]
  12.     /** Stores the navigation graphs for the A* Pathfinding System.
  13.      * \ingroup relevant
  14.      *
  15.      * An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the #graphs variable.\n
  16.      * This class also handles a lot of the high level serialization.
  17.      */
  18.     public class AstarData {
  19.         /** Shortcut to AstarPath.active */
  20.         public static AstarPath active {
  21.             get {
  22.                 return AstarPath.active;
  23.             }
  24.         }
  25.  
  26.         #region Fields
  27.         /** Shortcut to the first NavMeshGraph.
  28.          * Updated at scanning time
  29.          */
  30.         public NavMeshGraph navmesh { get; private set; }
  31.  
  32. #if !ASTAR_NO_GRID_GRAPH
  33.         /** Shortcut to the first GridGraph.
  34.          * Updated at scanning time
  35.          */
  36.         public GridGraph gridGraph { get; private set; }
  37.  
  38. #if !AstarFree
  39.         /** Shortcut to the first LayerGridGraph.
  40.          * Updated at scanning time.
  41.          * \astarpro
  42.          */
  43.         public LayerGridGraph layerGridGraph { get; private set; }
  44. #endif
  45. #endif
  46.  
  47. #if !ASTAR_NO_POINT_GRAPH
  48.         /** Shortcut to the first PointGraph.
  49.          * Updated at scanning time
  50.          */
  51.         public PointGraph pointGraph { get; private set; }
  52. #endif
  53.  
  54. #if !AstarFree
  55.         /** Shortcut to the first RecastGraph.
  56.          * Updated at scanning time.
  57.          * \astarpro
  58.          */
  59.         public RecastGraph recastGraph { get; private set; }
  60. #endif
  61.  
  62.         /** All supported graph types.
  63.          * Populated through reflection search
  64.          */
  65.         public System.Type[] graphTypes { get; private set; }
  66.  
  67. #if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
  68.         /** Graph types to use when building with Fast But No Exceptions for iPhone.
  69.          * If you add any custom graph types, you need to add them to this hard-coded list.
  70.          */
  71.         public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
  72. #if !ASTAR_NO_GRID_GRAPH
  73.             typeof(GridGraph),
  74. #if !AstarFree
  75.             typeof(LayerGridGraph),
  76. #endif
  77. #endif
  78. #if !ASTAR_NO_POINT_GRAPH
  79.             typeof(PointGraph),
  80. #endif
  81.             typeof(NavMeshGraph),
  82. #if !AstarFree
  83.             typeof(RecastGraph),
  84. #endif
  85.         };
  86. #endif
  87.  
  88.         /** All graphs this instance holds.
  89.          * This will be filled only after deserialization has completed.
  90.          * May contain null entries if graph have been removed.
  91.          */
  92.         [System.NonSerialized]
  93.         public NavGraph[] graphs = new NavGraph[0];
  94.  
  95.         //Serialization Settings
  96.  
  97.         /** Serialized data for all graphs and settings.
  98.          * Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
  99.          *
  100.          * This can be accessed as a byte array from the #data property.
  101.          *
  102.          * \since 3.6.1
  103.          */
  104.         [SerializeField]
  105.         string dataString;
  106.  
  107.         /** Data from versions from before 3.6.1.
  108.          * Used for handling upgrades
  109.          * \since 3.6.1
  110.          */
  111.         [SerializeField]
  112.         [UnityEngine.Serialization.FormerlySerializedAs("data")]
  113.         private byte[] upgradeData;
  114.  
  115.         /** Serialized data for all graphs and settings */
  116.         private byte[] data {
  117.             get {
  118.                 // Handle upgrading from earlier versions than 3.6.1
  119.                 if (upgradeData != null && upgradeData.Length > 0) {
  120.                     data = upgradeData;
  121.                     upgradeData = null;
  122.                 }
  123.                 return dataString != null ? System.Convert.FromBase64String(dataString) : null;
  124.             }
  125.             set {
  126.                 dataString = value != null ? System.Convert.ToBase64String(value) : null;
  127.             }
  128.         }
  129.  
  130.         /** Serialized data for cached startup.
  131.          * If set, on start the graphs will be deserialized from this file.
  132.          */
  133.         public TextAsset file_cachedStartup;
  134.  
  135.         /** Serialized data for cached startup.
  136.          *
  137.          * \deprecated Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
  138.          */
  139.         public byte[] data_cachedStartup;
  140.  
  141.         /** Should graph-data be cached.
  142.          * Caching the startup means saving the whole graphs - not only the settings - to a file (#file_cachedStartup) which can
  143.          * be loaded when the game starts. This is usually much faster than scanning the graphs when the game starts. This is configured from the editor under the "Save & Load" tab.
  144.          *
  145.          * \see \ref save-load-graphs
  146.          */
  147.         [SerializeField]
  148.         public bool cacheStartup;
  149.  
  150.         //End Serialization Settings
  151.  
  152.         List<bool> graphStructureLocked = new List<bool>();
  153.  
  154.         #endregion
  155.  
  156.         public byte[] GetData () {
  157.             return data;
  158.         }
  159.  
  160.         public void SetData (byte[] data) {
  161.             this.data = data;
  162.         }
  163.  
  164.         /** Loads the graphs from memory, will load cached graphs if any exists */
  165.         public void Awake () {
  166.             graphs = new NavGraph[0];
  167.  
  168.             if (cacheStartup && file_cachedStartup != null) {
  169.                 LoadFromCache();
  170.             } else {
  171.                 DeserializeGraphs();
  172.             }
  173.         }
  174.  
  175.         /** Prevent the graph structure from changing during the time this lock is held.
  176.          * This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
  177.          * This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
  178.          *
  179.          * Each call to this method *must* be paired with exactly one call to #UnlockGraphStructure.
  180.          * The calls may be nested.
  181.          */
  182.         internal void LockGraphStructure (bool allowAddingGraphs = false) {
  183.             graphStructureLocked.Add(allowAddingGraphs);
  184.         }
  185.  
  186.         /** Allows the graph structure to change again.
  187.          * \see #LockGraphStructure
  188.          */
  189.         internal void UnlockGraphStructure () {
  190.             if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
  191.             graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
  192.         }
  193.  
  194.         PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
  195.             if (graphStructureLocked.Count > 0) {
  196.                 bool allowAdding = true;
  197.                 for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
  198.                 if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
  199.             }
  200.  
  201.             // Pause the pathfinding threads
  202.             var graphLock = active.PausePathfinding();
  203.             if (!active.IsInsideWorkItem) {
  204.                 // Make sure all graph updates and other callbacks are done
  205.                 // Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
  206.                 // There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
  207.                 active.FlushWorkItems();
  208.  
  209.                 // Paths that are already calculated and waiting to be returned to the Seeker component need to be
  210.                 // processed immediately as their results usually depend on graphs that currently exist. If this was
  211.                 // not done then after destroying a graph one could get a path result with destroyed nodes in it.
  212.                 active.pathReturnQueue.ReturnPaths(false);
  213.             }
  214.             return graphLock;
  215.         }
  216.  
  217.         /** Calls the \a callback with every node in all graphs.
  218.          * This is the easiest way to iterate through every existing node.
  219.          *
  220.          * \snippet MiscSnippets.cs AstarData.GetNodes1
  221.          *
  222.          * \see #Pathfinding.NavGraph.GetNodes for getting the nodes of a single graph instead of all.
  223.          * \see \ref graph-updates
  224.          */
  225.         public void GetNodes (System.Action<GraphNode> callback) {
  226.             for (int i = 0; i < graphs.Length; i++) {
  227.                 if (graphs[i] != null) graphs[i].GetNodes(callback);
  228.             }
  229.         }
  230.  
  231.         /** Updates shortcuts to the first graph of different types.
  232.          * Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
  233.          * But these references ease the use of the system, so I decided to keep them.
  234.          */
  235.         public void UpdateShortcuts () {
  236.             navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
  237.  
  238. #if !ASTAR_NO_GRID_GRAPH
  239.             gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
  240. #if !AstarFree
  241.             layerGridGraph = (LayerGridGraph)FindGraphOfType(typeof(LayerGridGraph));
  242. #endif
  243. #endif
  244.  
  245. #if !ASTAR_NO_POINT_GRAPH
  246.             pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
  247. #endif
  248.  
  249. #if !AstarFree
  250.             recastGraph = (RecastGraph)FindGraphOfType(typeof(RecastGraph));
  251. #endif
  252.         }
  253.  
  254.         /** Load from data from #file_cachedStartup */
  255.         public void LoadFromCache () {
  256.             var graphLock = AssertSafe();
  257.  
  258.             if (file_cachedStartup != null) {
  259.                 var bytes = file_cachedStartup.bytes;
  260.                 DeserializeGraphs(bytes);
  261.  
  262.                 GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
  263.             } else {
  264.                 Debug.LogError("Can't load from cache since the cache is empty");
  265.             }
  266.             graphLock.Release();
  267.         }
  268.  
  269.         #region Serialization
  270.  
  271.         /** Serializes all graphs settings to a byte array.
  272.          * \see DeserializeGraphs(byte[])
  273.          */
  274.         public byte[] SerializeGraphs () {
  275.             return SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings);
  276.         }
  277.  
  278.         /** Serializes all graphs settings and optionally node data to a byte array.
  279.          * \see DeserializeGraphs(byte[])
  280.          * \see Pathfinding.Serialization.SerializeSettings
  281.          */
  282.         public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) {
  283.             uint checksum;
  284.  
  285.             return SerializeGraphs(settings, out checksum);
  286.         }
  287.  
  288.         /** Main serializer function.
  289.          * Serializes all graphs to a byte array
  290.          * A similar function exists in the AstarPathEditor.cs script to save additional info */
  291.         public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
  292.             var graphLock = AssertSafe();
  293.             var sr = new Pathfinding.Serialization.AstarSerializer(this, settings);
  294.  
  295.             sr.OpenSerialize();
  296.             sr.SerializeGraphs(graphs);
  297.             sr.SerializeExtraInfo();
  298.             byte[] bytes = sr.CloseSerialize();
  299.             checksum = sr.GetChecksum();
  300.     #if ASTARDEBUG
  301.             Debug.Log("Got a whole bunch of data, "+bytes.Length+" bytes");
  302.     #endif
  303.             graphLock.Release();
  304.             return bytes;
  305.         }
  306.  
  307.         /** Deserializes graphs from #data */
  308.         public void DeserializeGraphs () {
  309.             if (data != null) {
  310.                 DeserializeGraphs(data);
  311.             }
  312.         }
  313.  
  314.         /** Destroys all graphs and sets graphs to null */
  315.         void ClearGraphs () {
  316.             if (graphs == null) return;
  317.             for (int i = 0; i < graphs.Length; i++) {
  318.                 if (graphs[i] != null) {
  319.                     ((IGraphInternals)graphs[i]).OnDestroy();
  320.                     graphs[i].active = null;
  321.                 }
  322.             }
  323.             graphs = null;
  324.             UpdateShortcuts();
  325.         }
  326.  
  327.         public void OnDestroy () {
  328.             ClearGraphs();
  329.         }
  330.  
  331.         /** Deserializes graphs from the specified byte array.
  332.          * An error will be logged if deserialization fails.
  333.          */
  334.         public void DeserializeGraphs (byte[] bytes) {
  335.             var graphLock = AssertSafe();
  336.  
  337.             ClearGraphs();
  338.             DeserializeGraphsAdditive(bytes);
  339.             graphLock.Release();
  340.         }
  341.  
  342.         /** Deserializes graphs from the specified byte array additively.
  343.          * An error will be logged if deserialization fails.
  344.          * This function will add loaded graphs to the current ones.
  345.          */
  346.         public void DeserializeGraphsAdditive (byte[] bytes) {
  347.             var graphLock = AssertSafe();
  348.  
  349.             try {
  350.                 if (bytes != null) {
  351.                     var sr = new Pathfinding.Serialization.AstarSerializer(this);
  352.  
  353.                     if (sr.OpenDeserialize(bytes)) {
  354.                         DeserializeGraphsPartAdditive(sr);
  355.                         sr.CloseDeserialize();
  356.                     } else {
  357.                         Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
  358.                     }
  359.                 } else {
  360.                     throw new System.ArgumentNullException("bytes");
  361.                 }
  362.                 active.VerifyIntegrity();
  363.             } catch (System.Exception e) {
  364.                 Debug.LogError("Caught exception while deserializing data.\n"+e);
  365.                 graphs = new NavGraph[0];
  366.             }
  367.  
  368.             UpdateShortcuts();
  369.             graphLock.Release();
  370.         }
  371.  
  372.         /** Helper function for deserializing graphs */
  373.         void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) {
  374.             if (graphs == null) graphs = new NavGraph[0];
  375.  
  376.             var gr = new List<NavGraph>(graphs);
  377.  
  378.             // Set an offset so that the deserializer will load
  379.             // the graphs with the correct graph indexes
  380.             sr.SetGraphIndexOffset(gr.Count);
  381.  
  382.             gr.AddRange(sr.DeserializeGraphs());
  383.             graphs = gr.ToArray();
  384.  
  385.             sr.DeserializeEditorSettingsCompatibility();
  386.             sr.DeserializeExtraInfo();
  387.  
  388.             //Assign correct graph indices.
  389.             for (int i = 0; i < graphs.Length; i++) {
  390.                 if (graphs[i] == null) continue;
  391.                 graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
  392.             }
  393.  
  394.             for (int i = 0; i < graphs.Length; i++) {
  395.                 for (int j = i+1; j < graphs.Length; j++) {
  396.                     if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
  397.                         Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
  398.                         graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
  399.                         break;
  400.                     }
  401.                 }
  402.             }
  403.  
  404.             sr.PostDeserialization();
  405.             active.hierarchicalGraph.RecalculateIfNecessary();
  406.         }
  407.  
  408.         #endregion
  409.  
  410.         /** Find all graph types supported in this build.
  411.          * Using reflection, the assembly is searched for types which inherit from NavGraph. */
  412.         public void FindGraphTypes () {
  413. #if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
  414.             var graphList = new List<System.Type>();
  415.             foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
  416.                 System.Type types = null;
  417.                 try {
  418.                     types = assembly.GetTypes();
  419.                 } catch {
  420.                     continue;
  421.                 }
  422.  
  423.                 foreach (var type in types) {
  424. #if NETFX_CORE && !UNITY_EDITOR
  425.                     System.Type baseType = type.GetTypeInfo().BaseType;
  426. #else
  427.                     var baseType = type.BaseType;
  428. #endif
  429.                     while (baseType != null) {
  430.                         if (System.Type.Equals(baseType, typeof(NavGraph))) {
  431.                             graphList.Add(type);
  432.  
  433.                             break;
  434.                         }
  435.  
  436. #if NETFX_CORE && !UNITY_EDITOR
  437.                         baseType = baseType.GetTypeInfo().BaseType;
  438. #else
  439.                         baseType = baseType.BaseType;
  440. #endif
  441.                     }
  442.                 }
  443.             }
  444.  
  445.             graphTypes = graphList.ToArray();
  446.  
  447. #if ASTARDEBUG
  448.             Debug.Log("Found "+graphTypes.Length+" graph types");
  449. #endif
  450. #else
  451.             graphTypes = DefaultGraphTypes;
  452. #endif
  453.         }
  454.  
  455.         #region GraphCreation
  456.         /**
  457.          * \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned
  458.          *
  459.          * \deprecated
  460.          */
  461.         [System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
  462.         public System.Type GetGraphType (string type) {
  463.             for (int i = 0; i < graphTypes.Length; i++) {
  464.                 if (graphTypes[i].Name == type) {
  465.                     return graphTypes[i];
  466.                 }
  467.             }
  468.             return null;
  469.         }
  470.  
  471.         /** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned
  472.          * \returns The created graph
  473.          * \see #CreateGraph(System.Type)
  474.          *
  475.          * \deprecated
  476.          */
  477.         [System.Obsolete("Use CreateGraph(System.Type) instead")]
  478.         public NavGraph CreateGraph (string type) {
  479.             Debug.Log("Creating Graph of type '"+type+"'");
  480.  
  481.             for (int i = 0; i < graphTypes.Length; i++) {
  482.                 if (graphTypes[i].Name == type) {
  483.                     return CreateGraph(graphTypes[i]);
  484.                 }
  485.             }
  486.             Debug.LogError("Graph type ("+type+") wasn't found");
  487.             return null;
  488.         }
  489.  
  490.         /** Creates a new graph instance of type \a type
  491.          * \see #CreateGraph(string)
  492.          */
  493.         internal NavGraph CreateGraph (System.Type type) {
  494.             var graph = System.Activator.CreateInstance(type) as NavGraph;
  495.  
  496.             graph.active = active;
  497.             return graph;
  498.         }
  499.  
  500.         /** Adds a graph of type \a type to the #graphs array
  501.          *
  502.          * \deprecated
  503.          */
  504.         [System.Obsolete("Use AddGraph(System.Type) instead")]
  505.         public NavGraph AddGraph (string type) {
  506.             NavGraph graph = null;
  507.  
  508.             for (int i = 0; i < graphTypes.Length; i++) {
  509.                 if (graphTypes[i].Name == type) {
  510.                     graph = CreateGraph(graphTypes[i]);
  511.                 }
  512.             }
  513.  
  514.             if (graph == null) {
  515.                 Debug.LogError("No NavGraph of type '"+type+"' could be found");
  516.                 return null;
  517.             }
  518.  
  519.             AddGraph(graph);
  520.  
  521.             return graph;
  522.         }
  523.  
  524.         /** Adds a graph of type \a type to the #graphs array.
  525.          * \see \ref runtime-graphs
  526.          */
  527.         public NavGraph AddGraph (System.Type type) {
  528.             NavGraph graph = null;
  529.  
  530.             for (int i = 0; i < graphTypes.Length; i++) {
  531.                 if (System.Type.Equals(graphTypes[i], type)) {
  532.                     graph = CreateGraph(graphTypes[i]);
  533.                 }
  534.             }
  535.  
  536.             if (graph == null) {
  537.                 Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
  538.                 return null;
  539.             }
  540.  
  541.             AddGraph(graph);
  542.  
  543.             return graph;
  544.         }
  545.  
  546.         /** Adds the specified graph to the #graphs array */
  547.         void AddGraph (NavGraph graph) {
  548.             // Make sure to not interfere with pathfinding
  549.             var graphLock = AssertSafe(true);
  550.  
  551.             // Try to fill in an empty position
  552.             bool foundEmpty = false;
  553.  
  554.             for (int i = 0; i < graphs.Length; i++) {
  555.                 if (graphs[i] == null) {
  556.                     graphs[i] = graph;
  557.                     graph.graphIndex = (uint)i;
  558.                     foundEmpty = true;
  559.                     break;
  560.                 }
  561.             }
  562.  
  563.             if (!foundEmpty) {
  564.                 if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
  565.                     throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
  566.                 }
  567.  
  568.                 // Add a new entry to the list
  569.                 var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
  570.                 graphList.Add(graph);
  571.                 graphs = graphList.ToArray();
  572.                 graph.graphIndex = (uint)(graphs.Length-1);
  573.             }
  574.  
  575.             UpdateShortcuts();
  576.             graph.active = active;
  577.             graphLock.Release();
  578.         }
  579.  
  580.         /** Removes the specified graph from the #graphs array and Destroys it in a safe manner.
  581.          * To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
  582.          * of actually removing it from the array.
  583.          * The empty position will be reused if a new graph is added.
  584.          *
  585.          * \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise.
  586.          *
  587.          * \version Changed in 3.2.5 to call SafeOnDestroy before removing
  588.          * and nulling it in the array instead of removing the element completely in the #graphs array.
  589.          */
  590.         public bool RemoveGraph (NavGraph graph) {
  591.             // Make sure the pathfinding threads are stopped
  592.             // If we don't wait until pathfinding that is potentially running on
  593.             // this graph right now we could end up with NullReferenceExceptions
  594.             var graphLock = AssertSafe();
  595.  
  596.             ((IGraphInternals)graph).OnDestroy();
  597.             graph.active = null;
  598.  
  599.             int i = System.Array.IndexOf(graphs, graph);
  600.             if (i != -1) graphs[i] = null;
  601.  
  602.             UpdateShortcuts();
  603.             graphLock.Release();
  604.             return i != -1;
  605.         }
  606.  
  607.         #endregion
  608.  
  609.         #region GraphUtility
  610.  
  611.         /** Returns the graph which contains the specified node.
  612.          * The graph must be in the #graphs array.
  613.          *
  614.          * \returns Returns the graph which contains the node. Null if the graph wasn't found
  615.          */
  616.         public static NavGraph GetGraph (GraphNode node) {
  617.             if (node == null) return null;
  618.  
  619.             AstarPath script = AstarPath.active;
  620.             if (script == null) return null;
  621.  
  622.             AstarData data = script.data;
  623.             if (data == null || data.graphs == null) return null;
  624.  
  625.             uint graphIndex = node.GraphIndex;
  626.  
  627.             if (graphIndex >= data.graphs.Length) {
  628.                 return null;
  629.             }
  630.  
  631.             return data.graphs[(int)graphIndex];
  632.         }
  633.  
  634.         /** Returns the first graph which satisfies the predicate. Returns null if no graph was found. */
  635.         public NavGraph FindGraph (System.Func<NavGraph, bool> predicate) {
  636.             if (graphs != null) {
  637.                 for (int i = 0; i < graphs.Length; i++) {
  638.                     if (graphs[i] != null && predicate(graphs[i])) {
  639.                         return graphs[i];
  640.                     }
  641.                 }
  642.             }
  643.             return null;
  644.         }
  645.  
  646.         /** Returns the first graph of type \a type found in the #graphs array. Returns null if no graph was found. */
  647.         public NavGraph FindGraphOfType (System.Type type) {
  648.             return FindGraph(graph => System.Type.Equals(graph.GetType(), type));
  649.         }
  650.  
  651.         /** Returns the first graph which inherits from the type \a type. Returns null if no graph was found. */
  652.         public NavGraph FindGraphWhichInheritsFrom (System.Type type) {
  653.             return FindGraph(graph => WindowsStoreCompatibility.GetTypeInfo(type).IsAssignableFrom(WindowsStoreCompatibility.GetTypeInfo(graph.GetType())));
  654.         }
  655.  
  656.         /** Loop through this function to get all graphs of type 'type'
  657.          * \code
  658.          * foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
  659.          *     //Do something with the graph
  660.          * }
  661.          * \endcode
  662.          * \see AstarPath.RegisterSafeNodeUpdate */
  663.         public IEnumerable FindGraphsOfType (System.Type type) {
  664.             if (graphs == null) yield break;
  665.             for (int i = 0; i < graphs.Length; i++) {
  666.                 if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
  667.                     yield return graphs[i];
  668.                 }
  669.             }
  670.         }
  671.  
  672.         /** All graphs which implements the UpdateableGraph interface
  673.          * \code foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
  674.          *  //Do something with the graph
  675.          * } \endcode
  676.          * \see AstarPath.AddWorkItem
  677.          * \see Pathfinding.IUpdatableGraph */
  678.         public IEnumerable GetUpdateableGraphs () {
  679.             if (graphs == null) yield break;
  680.             for (int i = 0; i < graphs.Length; i++) {
  681.                 if (graphs[i] is IUpdatableGraph) {
  682.                     yield return graphs[i];
  683.                 }
  684.             }
  685.         }
  686.  
  687.         /** All graphs which implements the UpdateableGraph interface
  688.          * \code foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
  689.          *  //Do something with the graph
  690.          * } \endcode
  691.          * \see Pathfinding.IRaycastableGraph
  692.          * \deprecated Deprecated because it is not used by the package internally and the use cases are few. Iterate through the #graphs array instead.
  693.          */
  694.         [System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
  695.         public IEnumerable GetRaycastableGraphs () {
  696.             if (graphs == null) yield break;
  697.             for (int i = 0; i < graphs.Length; i++) {
  698.                 if (graphs[i] is IRaycastableGraph) {
  699.                     yield return graphs[i];
  700.                 }
  701.             }
  702.         }
  703.  
  704.         /** Gets the index of the NavGraph in the #graphs array */
  705.         public int GetGraphIndex (NavGraph graph) {
  706.             if (graph == null) throw new System.ArgumentNullException("graph");
  707.  
  708.             var index = -1;
  709.             if (graphs != null) {
  710.                 index = System.Array.IndexOf(graphs, graph);
  711.                 if (index == -1) Debug.LogError("Graph doesn't exist");
  712.             }
  713.             return index;
  714.         }
  715.  
  716.         #endregion
  717.     }
  718. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement