A* Pathfinding Project  3.8.5
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
RecastGraph Class Reference

Automatically generates navmesh graphs based on world geometry. More...

Detailed Description

Automatically generates navmesh graphs based on world geometry.

The recast graph is based on Recast (http://code.google.com/p/recastnavigation/).
I have translated a good portion of it to C# to run it natively in Unity. The Recast process is described as follows:

  • The voxel mold is build from the input triangle mesh by rasterizing the triangles into a multi-layer heightfield. Some simple filters are then applied to the mold to prune out locations where the character would not be able to move.
  • The walkable areas described by the mold are divided into simple overlayed 2D regions. The resulting regions have only one non-overlapping contour, which simplifies the final step of the process tremendously.
  • The navigation polygons are peeled off from the regions by first tracing the boundaries and then simplifying them. The resulting polygons are finally converted to convex polygons which makes them perfect for pathfinding and spatial reasoning about the level.

It works exactly like that in the C# version as well, except that everything is triangulated to triangles instead of n-gons. The recast generation process usually works directly on the visiable geometry in the world, this is usually a good thing, because world geometry is usually more detailed than the colliders. You can however specify that colliders should be rasterized, if you have very detailed world geometry, this can speed up the scan.

Check out the second part of the Get Started Tutorial which discusses recast graphs.

Exporting for manual editing

In the editor there is a button for exporting the generated graph to a .obj file. Usually the generation process is good enough for the game directly, but in some cases you might want to edit some minor details. So you can export the graph to a .obj file, open it in your favourite 3D application, edit it, and export it to a mesh which Unity can import. You can then use that mesh in a navmesh graph.

Since many 3D modelling programs use different axis systems (unity uses X=right, Y=up, Z=forward), it can be a bit tricky to get the rotation and scaling right. For blender for example, what you have to do is to first import the mesh using the .obj importer. Don't change anything related to axes in the settings. Then select the mesh, open the transform tab (usually the thin toolbar to the right of the 3D view) and set Scale -> Z to -1. If you transform it using the S (scale) hotkey, it seems to set both Z and Y to -1 for some reason. Then make the edits you need and export it as an .obj file to somewhere in the Unity project. But this time, edit the setting named "Forward" to "Z forward" (not -Z as it is per default).

A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here

Classes

class  NavmeshTile
 

Public Types

enum  RelevantGraphSurfaceMode { DoNotRequire, OnlyForCompletelyInsideTile, RequireForAll }
 

Public Member Functions

Vector3 ClosestPointOnNode (TriangleMeshNode node, Vector3 pos)
 Returns the closest point of the node.
 
bool ContainsPoint (TriangleMeshNode node, Vector3 pos)
 Returns if the point is inside the node in XZ space.
 
override void DeserializeExtraInfo (GraphSerializationContext ctx)
 Deserializes graph type specific node data.
 
override void DeserializeSettingsCompatibility (GraphSerializationContext ctx)
 An old format for serializing settings.
 
void EndBatchTileUpdate ()
 End batch updating of tiles.
 
override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint)
 Returns the nearest node to a position using the specified NNConstraint.
 
override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified constraint .
 
override void GetNodes (GraphNodeDelegateCancelable del)
 Calls a delegate with all nodes in the graph.
 
NavmeshTile GetTile (int x, int z)
 Tile at the specified x, z coordinate pair.
 
Bounds GetTileBounds (IntRect rect)
 Returns an XZ bounds object with the bounds of a group of tiles.
 
Bounds GetTileBounds (int x, int z, int width=1, int depth=1)
 Returns an XZ bounds object with the bounds of a group of tiles.
 
void GetTileCoordinates (int tileIndex, out int x, out int z)
 Returns tile coordinates from a tile index.
 
Int2 GetTileCoordinates (Vector3 p)
 Returns the tile coordinate which contains the point p.
 
int GetTileIndex (int index)
 Returns a tile index from a vertex index.
 
NavmeshTile[] GetTiles ()
 Get all tiles.
 
IntRect GetTouchingTiles (Bounds b)
 Returns a rect containing the indices of all tiles touching the specified bounds.
 
IntRect GetTouchingTilesRound (Bounds b)
 Returns a rect containing the indices of all tiles by rounding the specified bounds to tile borders.
 
Int3 GetVertex (int index)
 Gets the vertex coordinate for the specified index.
 
int GetVertexArrayIndex (int index)
 
bool Linecast (Vector3 origin, Vector3 end)
 
bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit)
 
bool Linecast (Vector3 origin, Vector3 end, GraphNode hint)
 
bool Linecast (Vector3 tmp_origin, Vector3 tmp_end, GraphNode hint, out GraphHitInfo hit, List< GraphNode > trace)
 Returns if there is an obstacle between origin and end on the graph.
 
override void OnDestroy ()
 Function for cleaning up references.
 
override void OnDrawGizmos (bool drawNodes)
 Draw gizmos for the graph.
 
GraphNode PointOnNavmesh (Vector3 position, NNConstraint constraint)
 Finds the first node which contains position.
 
override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix)
 Relocates the nodes in this graph.
 
void ReplaceTile (int x, int z, Int3[] verts, int[] tris, bool worldSpace)
 Replace tile at index with nodes created from specified navmesh.
 
void ReplaceTile (int x, int z, int w, int d, Int3[] verts, int[] tris, bool worldSpace)
 
override IEnumerable< ProgressScanInternal ()
 Internal method to scan the graph.
 
override void SerializeExtraInfo (GraphSerializationContext ctx)
 Serializes Node Info.
 
void SnapForceBoundsToScene ()
 Changes the bounds of the graph to precisely encapsulate all objects in the scene that can be included in the scanning process based on the settings.
 
void StartBatchTileUpdate ()
 Start batch updating of tiles.
 
- Public Member Functions inherited from NavGraph
virtual void Awake ()
 This will be called on the same time as Awake on the gameObject which the AstarPath script is attached to.
 
virtual int CountNodes ()
 Number of nodes in the graph.
 
NNInfoInternal GetNearest (Vector3 position)
 Returns the nearest node to a position using the default NNConstraint.
 
NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified NNConstraint.
 
virtual Color NodeColor (GraphNode node, PathHandler data)
 Color to use for gizmos.
 
virtual void PostDeserialization ()
 Called after all deserialization has been done for all graphs.
 
void Scan ()
 
void ScanGraph ()
 Partially scan the graph.
 
void SetMatrix (Matrix4x4 m)
 Use to set both matrix and inverseMatrix at the same time.
 
- Public Member Functions inherited from INavmesh
void GetNodes (GraphNodeDelegateCancelable del)
 
- Public Member Functions inherited from IRaycastableGraph
bool Linecast (Vector3 start, Vector3 end)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List< GraphNode > trace)
 
- Public Member Functions inherited from IUpdatableGraph
GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o)
 
void UpdateArea (GraphUpdateObject o)
 Updates an area using the specified GraphUpdateObject.
 
void UpdateAreaInit (GraphUpdateObject o)
 May be called on the Unity thread before starting the update.
 
void UpdateAreaPost (GraphUpdateObject o)
 May be called on the Unity thread after executing the update.
 
- Public Member Functions inherited from INavmeshHolder
void GetTileCoordinates (int tileIndex, out int x, out int z)
 
Int3 GetVertex (int i)
 
int GetVertexArrayIndex (int index)
 

Public Attributes

const int BorderVertexMask = 1
 
const int BorderVertexOffset = 31
 
float cellSize = 0.5F
 Voxel sample size (x,z).
 
float characterRadius = 1.5F
 Radius of the agent which will traverse the navmesh.
 
float colliderRasterizeDetail = 10
 Controls detail on rasterization of sphere and capsule colliders.
 
float contourMaxError = 2F
 Max distance from simplified edge to real edge.
 
bool dynamic = true
 Enables graph updating.
 
int editorTileSize = 128
 Size in voxels of a single tile.
 
Vector3 forcedBoundsCenter
 Center of the bounding box.
 
Vector3 forcedBoundsSize = new Vector3(100, 40, 100)
 Size of the bounding box.
 
LayerMask mask = -1
 Layer mask which filters which objects to include.
 
float maxEdgeLength = 20
 Longer edges will be subdivided.
 
float maxSlope = 30
 Max slope in degrees the character can traverse.
 
float minRegionSize = 3
 Minumum region size.
 
bool nearestSearchOnlyXZ
 Perform nearest node searches in XZ space only.
 
bool rasterizeColliders
 Use colliders to calculate the navmesh.
 
bool rasterizeMeshes = true
 Use scene meshes to calculate the navmesh.
 
bool rasterizeTerrain = true
 Include the Terrain in the scene.
 
bool rasterizeTrees = true
 Rasterize tree colliders on terrains.
 
RelevantGraphSurfaceMode relevantGraphSurfaceMode = RelevantGraphSurfaceMode.DoNotRequire
 Require every region to have a RelevantGraphSurface component inside it.
 
bool scanEmptyGraph
 If true, scanning the graph will yield a completely empty graph.
 
bool showMeshOutline = true
 Show an outline of the polygons in the Unity Editor.
 
bool showMeshSurface
 Show the surface of the navmesh.
 
bool showNodeConnections
 Show the connections between the polygons in the Unity Editor.
 
List< string > tagMask = new List<string>()
 Objects tagged with any of these tags will be rasterized.
 
int terrainSampleSize = 3
 Controls how large the sample size for the terrain is.
 
const int TileIndexMask = 0x7FFFF
 
const int TileIndexOffset = 12
 
int tileSizeX = 128
 Size of a tile along the X axis in voxels.
 
int tileSizeZ = 128
 Size of a tile along the Z axis in voxels.
 
int tileXCount
 Number of tiles along the X-axis.
 
int tileZCount
 Number of tiles along the Z-axis.
 
bool useTiles
 If true, divide the graph into tiles, otherwise use a single tile covering the whole graph.
 
const int VertexIndexMask = 0xFFF
 
float walkableClimb = 0.5F
 Height the character can climb.
 
float walkableHeight = 2F
 Character height.
 
- Public Attributes inherited from NavGraph
AstarPath active
 Reference to the AstarPath object in the scene.
 
bool drawGizmos = true
 Enable to draw gizmos in the Unity scene view.
 
uint graphIndex
 Index of the graph, used for identification purposes.
 
Guid guid
 Used as an ID of the graph, considered to be unique.
 
bool infoScreenOpen
 Used in the editor to check if the info screen is open.
 
uint initialPenalty
 Default penalty to apply to all nodes.
 
Matrix4x4 inverseMatrix = Matrix4x4.identity
 Inverse of matrix.
 
Matrix4x4 matrix = Matrix4x4.identity
 A matrix for translating/rotating/scaling the graph.
 
string name
 Name of the graph.
 
bool open
 Is the graph open in the editor.
 

Protected Member Functions

NavmeshTile BuildTileMesh (Voxelize vox, int x, int z, int threadIndex=0)
 
IEnumerable< ProgressScanAllTiles ()
 

Properties

float CellHeight [get]
 
int CharacterRadiusInVoxels [get]
 Convert character radius to a number of voxels.
 
Bounds forcedBounds [get]
 World bounds for the graph.
 
int TileBorderSizeInVoxels [get]
 Number of extra voxels on each side of a tile to ensure accurate navmeshes near the tile border.
 
float TileBorderSizeInWorldUnits [get]
 

Events

System.Action< NavmeshTile[]> OnRecalculatedTiles
 Called when tiles have been completely recalculated.
 

Private Member Functions

void BuildTiles (Queue< Int2 > tileQueue, List< RasterizationMesh >[] meshBuckets, ManualResetEvent doneEvent, int threadIndex)
 
Bounds CalculateTileBoundsWithBorder (int x, int z)
 
GraphUpdateThreading
IUpdatableGraph. 
CanUpdateAsync (GraphUpdateObject o)
 
void ClearTiles (int x, int z, int w, int d)
 Clear all tiles within the rectangle with one corner at (x,z), width w and depth d.
 
List< RasterizationMeshCollectMeshes (Bounds bounds)
 
void ConnectTiles (Queue< Int2 > tileQueue, ManualResetEvent doneEvent)
 
void ConnectTiles (NavmeshTile tile1, NavmeshTile tile2)
 Generate connections between the two tiles.
 
void ConnectTileWithNeighbours (NavmeshTile tile, bool onlyUnflagged=false)
 
void CreateNodeConnections (TriangleMeshNode[] nodes)
 Create connections between all nodes.
 
NavmeshTile CreateTile (Voxelize vox, VoxelMesh mesh, int x, int z, int threadIndex=0)
 Create a tile at tile index x, z from the mesh.
 
void FillWithEmptyTiles ()
 Fills graph with tiles created by NewEmptyTile.
 
void InitializeTileInfo ()
 
List< RasterizationMesh >[] PutMeshesIntoTileBuckets (List< RasterizationMesh > meshes)
 Creates a list for every tile and adds every mesh that touches a tile to the corresponding list.
 
void RemoveConnectionsFromTile (NavmeshTile tile)
 
void RemoveConnectionsFromTo (NavmeshTile a, NavmeshTile b)
 
void IUpdatableGraph. UpdateArea (GraphUpdateObject guo)
 
void IUpdatableGraph. UpdateAreaInit (GraphUpdateObject o)
 
void IUpdatableGraph. UpdateAreaPost (GraphUpdateObject guo)
 Called on the Unity thread to complete a graph update.
 

Static Private Member Functions

static NavmeshTile NewEmptyTile (int x, int z)
 Creates a single new empty tile.
 

Private Attributes

bool batchTileUpdate
 Currently updating tiles in a batch.
 
List< int > batchUpdatedTiles = new List<int>()
 List of tiles updating during batch.
 
Voxelize globalVox
 
List< NavmeshTilestagingTiles = new List<NavmeshTile>()
 List of tiles that have been calculated in a graph update, but have not yet been added to the graph.
 
NavmeshTile[] tiles
 All tiles.
 

Additional Inherited Members

- Static Public Member Functions inherited from NavGraph
static bool InSearchTree (GraphNode node, Path path)
 Returns if the node is in the search tree of the path.
 
- Package Functions inherited from NavGraph
virtual void UnloadGizmoMeshes ()
 Called when temporary meshes used in OnDrawGizmos need to be unloaded to prevent memory leaks.
 

Member Enumeration Documentation

Enumerator:
DoNotRequire 
OnlyForCompletelyInsideTile 
RequireForAll 

Member Function Documentation

NavmeshTile BuildTileMesh ( Voxelize  vox,
int  x,
int  z,
int  threadIndex = 0 
)
protected
void BuildTiles ( Queue< Int2 tileQueue,
List< RasterizationMesh >[]  meshBuckets,
ManualResetEvent  doneEvent,
int  threadIndex 
)
private
Bounds CalculateTileBoundsWithBorder ( int  x,
int  z 
)
private
GraphUpdateThreading IUpdatableGraph. CanUpdateAsync ( GraphUpdateObject  o)
private
void ClearTiles ( int  x,
int  z,
int  w,
int  d 
)
private

Clear all tiles within the rectangle with one corner at (x,z), width w and depth d.

Vector3 ClosestPointOnNode ( TriangleMeshNode  node,
Vector3  pos 
)

Returns the closest point of the node.

List<RasterizationMesh> CollectMeshes ( Bounds  bounds)
private
void ConnectTiles ( Queue< Int2 tileQueue,
ManualResetEvent  doneEvent 
)
private
void ConnectTiles ( NavmeshTile  tile1,
NavmeshTile  tile2 
)
private

Generate connections between the two tiles.

The tiles must be adjacent.

void ConnectTileWithNeighbours ( NavmeshTile  tile,
bool  onlyUnflagged = false 
)
private
bool ContainsPoint ( TriangleMeshNode  node,
Vector3  pos 
)

Returns if the point is inside the node in XZ space.

void CreateNodeConnections ( TriangleMeshNode[]  nodes)
private

Create connections between all nodes.

Version
Since 3.7.6 the implementation is thread safe
NavmeshTile CreateTile ( Voxelize  vox,
VoxelMesh  mesh,
int  x,
int  z,
int  threadIndex = 0 
)
private

Create a tile at tile index x, z from the mesh.

Version
Since version 3.7.6 the implementation is thread safe
override void DeserializeExtraInfo ( GraphSerializationContext  ctx)
virtual

Deserializes graph type specific node data.

See Also
SerializeExtraInfo

Reimplemented from NavGraph.

override void DeserializeSettingsCompatibility ( GraphSerializationContext  ctx)
virtual

An old format for serializing settings.

Deprecated:
This is deprecated now, but the deserialization code is kept to avoid loosing data when upgrading from older versions.

Reimplemented from NavGraph.

void EndBatchTileUpdate ( )

End batch updating of tiles.

During batch updating, tiles will not be connected if they are updating with ReplaceTile. When ending batching, all affected tiles will be connected. This is faster than not using batching.

void FillWithEmptyTiles ( )
private

Fills graph with tiles created by NewEmptyTile.

override NNInfoInternal GetNearest ( Vector3  position,
NNConstraint  constraint,
GraphNode  hint 
)
virtual

Returns the nearest node to a position using the specified NNConstraint.

Parameters
positionThe position to try to find a close node to
hintCan be passed to enable some graph generators to find the nearest node faster.
constraintCan for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce.

Reimplemented from NavGraph.

override NNInfoInternal GetNearestForce ( Vector3  position,
NNConstraint  constraint 
)
virtual

Returns the nearest node to a position using the specified constraint .

Returns
an NNInfo. This method will only return an empty NNInfo if there are no nodes which comply with the specified constraint.

Reimplemented from NavGraph.

override void GetNodes ( GraphNodeDelegateCancelable  del)
virtual

Calls a delegate with all nodes in the graph.

This is the primary way of iterating through all nodes in a graph.

Do not change the graph structure inside the delegate.

myGraph.GetNodes (node => {
Debug.Log ("I found a node at position " + (Vector3)node.Position);
return true;
});

Implements NavGraph.

NavmeshTile GetTile ( int  x,
int  z 
)

Tile at the specified x, z coordinate pair.

The first tile is at (0,0), the last tile at (tileXCount-1, tileZCount-1).

Bounds GetTileBounds ( IntRect  rect)

Returns an XZ bounds object with the bounds of a group of tiles.

The bounds object is defined in world units.

Bounds GetTileBounds ( int  x,
int  z,
int  width = 1,
int  depth = 1 
)

Returns an XZ bounds object with the bounds of a group of tiles.

The bounds object is defined in world units.

void GetTileCoordinates ( int  tileIndex,
out int  x,
out int  z 
)

Returns tile coordinates from a tile index.

Int2 GetTileCoordinates ( Vector3  p)

Returns the tile coordinate which contains the point p.

Is not necessarily a valid tile (i.e it could be out of bounds).

int GetTileIndex ( int  index)

Returns a tile index from a vertex index.

NavmeshTile [] GetTiles ( )

Get all tiles.

Warning
Do not modify this array
IntRect GetTouchingTiles ( Bounds  b)

Returns a rect containing the indices of all tiles touching the specified bounds.

IntRect GetTouchingTilesRound ( Bounds  b)

Returns a rect containing the indices of all tiles by rounding the specified bounds to tile borders.

This is different from GetTouchingTiles in that the tiles inside the rectangle returned from this method may not contain the whole bounds, while that is guaranteed for GetTouchingTiles.

Int3 GetVertex ( int  index)

Gets the vertex coordinate for the specified index.

Exceptions
IndexOutOfRangeExceptionif the vertex index is invalid.
NullReferenceExceptionif the tile the vertex is in is not calculated.
See Also
NavmeshTile.GetVertex
int GetVertexArrayIndex ( int  index)
void InitializeTileInfo ( )
private
bool Linecast ( Vector3  origin,
Vector3  end 
)
bool Linecast ( Vector3  origin,
Vector3  end,
GraphNode  hint,
out GraphHitInfo  hit 
)
bool Linecast ( Vector3  origin,
Vector3  end,
GraphNode  hint 
)
bool Linecast ( Vector3  tmp_origin,
Vector3  tmp_end,
GraphNode  hint,
out GraphHitInfo  hit,
List< GraphNode trace 
)

Returns if there is an obstacle between origin and end on the graph.

Parameters
[in]tmp_originPoint to start from
[in]tmp_endPoint to linecast to
[out]hitContains info on what was hit, see GraphHitInfo
[in]hintYou need to pass the node closest to the start point, if null, a search for the closest node will be done
traceIf a list is passed, then it will be filled with all nodes the linecast traverses This is not the same as Physics.Linecast, this function traverses the graph and looks for collisions instead of checking for collider intersection.
A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here
static NavmeshTile NewEmptyTile ( int  x,
int  z 
)
staticprivate

Creates a single new empty tile.

override void OnDestroy ( )
virtual

Function for cleaning up references.

This will be called on the same time as OnDisable on the gameObject which the AstarPath script is attached to (remember, not in the editor). Use for any cleanup code such as cleaning up static variables which otherwise might prevent resources from being collected. Use by creating a function overriding this one in a graph class, but always call base.OnDestroy () in that function. All nodes should be destroyed in this function otherwise a memory leak will arise.

Reimplemented from NavGraph.

override void OnDrawGizmos ( bool  drawNodes)
virtual

Draw gizmos for the graph.

Reimplemented from NavGraph.

GraphNode PointOnNavmesh ( Vector3  position,
NNConstraint  constraint 
)

Finds the first node which contains position.

"Contains" is defined as position is inside the triangle node when seen from above. So only XZ space matters. In case of a multilayered environment, which node of the possibly several nodes containing the point is undefined.

Returns null if there was no node containing the point. This serves as a quick check for "is this point on the navmesh or not".

Note that the behaviour of this method is distinct from the GetNearest method. The GetNearest method will return the closest node to a point, which is not necessarily the one which contains it in XZ space.

See Also
GetNearest
List<RasterizationMesh> [] PutMeshesIntoTileBuckets ( List< RasterizationMesh meshes)
private

Creates a list for every tile and adds every mesh that touches a tile to the corresponding list.

override void RelocateNodes ( Matrix4x4  oldMatrix,
Matrix4x4  newMatrix 
)
virtual

Relocates the nodes in this graph.

Assumes the nodes are already transformed using the "oldMatrix", then transforms them such that it will look like they have only been transformed using the "newMatrix".

The matrix the graph is transformed with is typically stored in the matrix field, so the typical usage for this method is

var myNewMatrix = Matrix4x4.TRS (...);
myGraph.RelocateNodes (myGraph.matrix, myNewMatrix);

So for example if you want to move all your nodes in e.g a recast graph 10 units along the X axis from the initial position

var graph = AstarPath.astarData.recastGraph;
var m = Matrix4x4.TRS (new Vector3(10,0,0), Quaternion.identity, Vector3.one);
graph.RelocateNodes (graph.matrix, m);
Warning
This method is lossy, so calling it many times may cause node positions to lose precision. For example if you set the scale to 0 in one call, and then to 1 in the next call, it will not be able to recover the correct positions since when the scale was 0, all nodes were scaled/moved to the same point. The same thing happens for other - less extreme - values as well, but to a lesser degree.
Version
Prior to version 3.6.1 the oldMatrix and newMatrix parameters were reversed by mistake.

Reimplemented from NavGraph.

void RemoveConnectionsFromTile ( NavmeshTile  tile)
private
void RemoveConnectionsFromTo ( NavmeshTile  a,
NavmeshTile  b 
)
private
void ReplaceTile ( int  x,
int  z,
Int3[]  verts,
int[]  tris,
bool  worldSpace 
)

Replace tile at index with nodes created from specified navmesh.

See Also
StartBatchTileUpdating
void ReplaceTile ( int  x,
int  z,
int  w,
int  d,
Int3[]  verts,
int[]  tris,
bool  worldSpace 
)
IEnumerable<Progress> ScanAllTiles ( )
protected
override IEnumerable<Progress> ScanInternal ( )
virtual

Internal method to scan the graph.

Called from AstarPath.ScanAsync. Override this function to implement custom scanning logic. Progress objects can be yielded to show progress info in the editor and to split up processing over several frames when using async scanning.

Implements NavGraph.

override void SerializeExtraInfo ( GraphSerializationContext  ctx)
virtual

Serializes Node Info.

Should serialize:

  • Base
    • Node Flags
    • Node Penalties
    • Node
  • Node Positions (if applicable)
  • Any other information necessary to load the graph in-game All settings marked with json attributes (e.g JsonMember) have already been saved as graph settings and do not need to be handled here.

It is not necessary for this implementation to be forward or backwards compatible.

See Also

Reimplemented from NavGraph.

void SnapForceBoundsToScene ( )

Changes the bounds of the graph to precisely encapsulate all objects in the scene that can be included in the scanning process based on the settings.

Which objects are used depends on the settings. If an object would have affected the graph with the current settings if it would have been inside the bounds of the graph, it will be detected and the bounds will be expanded to contain that object.

This method corresponds to the 'Snap bounds to scene' button in the inspector.

See Also
rasterizeMeshes
rasterizeTerrain
rasterizeColliders
mask
tagMask
forcedBoundsCenter
forcedBoundsSize
void StartBatchTileUpdate ( )

Start batch updating of tiles.

During batch updating, tiles will not be connected if they are updating with ReplaceTile. When ending batching, all affected tiles will be connected. This is faster than not using batching.

void IUpdatableGraph. UpdateArea ( GraphUpdateObject  guo)
private
void IUpdatableGraph. UpdateAreaInit ( GraphUpdateObject  o)
private
void IUpdatableGraph. UpdateAreaPost ( GraphUpdateObject  guo)
private

Called on the Unity thread to complete a graph update.

Member Data Documentation

bool batchTileUpdate
private

Currently updating tiles in a batch.

List<int> batchUpdatedTiles = new List<int>()
private

List of tiles updating during batch.

const int BorderVertexMask = 1
const int BorderVertexOffset = 31
float cellSize = 0.5F

Voxel sample size (x,z).

Lower values will yield higher quality navmeshes, however the graph will be slower to scan.

float characterRadius = 1.5F

Radius of the agent which will traverse the navmesh.

The navmesh will be eroded with this radius.

float colliderRasterizeDetail = 10

Controls detail on rasterization of sphere and capsule colliders.

This controls the number of rows and columns on the generated meshes. A higher value does not necessarily increase quality of the mesh, but a lower value will often speed it up.

You should try to keep this value as low as possible without affecting the mesh quality since that will yield the fastest scan times.

See Also
rasterizeColliders
float contourMaxError = 2F

Max distance from simplified edge to real edge.

bool dynamic = true

Enables graph updating.

Uses more memory if enabled.

int editorTileSize = 128

Size in voxels of a single tile.

This is the width of the tile.

A large tile size can be faster to initially scan (but beware of out of memory issues if you try with a too large tile size in a large world) smaller tile sizes are (much) faster to update.

Different tile sizes can affect the quality of paths. It is often good to split up huge open areas into several tiles for better quality paths, but too small tiles can lead to effects looking like invisible obstacles.

Vector3 forcedBoundsCenter

Center of the bounding box.

Scanning will only be done inside the bounding box

Vector3 forcedBoundsSize = new Vector3(100, 40, 100)

Size of the bounding box.

Voxelize globalVox
private
LayerMask mask = -1

Layer mask which filters which objects to include.

See Also
tagMask
float maxEdgeLength = 20

Longer edges will be subdivided.

Reducing this value can improve path quality since similarly sized polygons yield better paths than really large and really small next to each other

float maxSlope = 30

Max slope in degrees the character can traverse.

float minRegionSize = 3

Minumum region size.

Small regions will be removed from the navmesh. Measured in square world units (square meters in most games).

If a region is adjacent to a tile border, it will not be removed even though it is small since the adjacent tile might join it to form a larger region.

bool nearestSearchOnlyXZ

Perform nearest node searches in XZ space only.

bool rasterizeColliders

Use colliders to calculate the navmesh.

bool rasterizeMeshes = true

Use scene meshes to calculate the navmesh.

bool rasterizeTerrain = true

Include the Terrain in the scene.

bool rasterizeTrees = true

Rasterize tree colliders on terrains.

If the tree prefab has a collider, that collider will be rasterized. Otherwise a simple box collider will be used and the script will try to adjust it to the tree's scale, it might not do a very good job though so an attached collider is preferable.

See Also
rasterizeTerrain
colliderRasterizeDetail
RelevantGraphSurfaceMode relevantGraphSurfaceMode = RelevantGraphSurfaceMode.DoNotRequire

Require every region to have a RelevantGraphSurface component inside it.

A RelevantGraphSurface component placed in the scene specifies that the navmesh region it is inside should be included in the navmesh.

If this is set to OnlyForCompletelyInsideTile a navmesh region is included in the navmesh if it has a RelevantGraphSurface inside it, or if it is adjacent to a tile border. This can leave some small regions which you didn't want to have included because they are adjacent to tile borders, but it removes the need to place a component in every single tile, which can be tedious (see below).

If this is set to RequireForAll a navmesh region is included only if it has a RelevantGraphSurface inside it. Note that even though the navmesh looks continous between tiles, the tiles are computed individually and therefore you need a RelevantGraphSurface component for each region and for each tile.

In the above image, the mode OnlyForCompletelyInsideTile was used. Tile borders are highlighted in black. Note that since all regions are adjacent to a tile border, this mode didn't remove anything in this case and would give the same result as DoNotRequire. The RelevantGraphSurface component is shown using the green gizmo in the top-right of the blue plane.

In the above image, the mode RequireForAll was used. No tiles were used. Note that the small region at the top of the orange cube is now gone, since it was not the in the same region as the relevant graph surface component. The result would have been identical with OnlyForCompletelyInsideTile since there are no tiles (or a single tile, depending on how you look at it).

The mode RequireForAll was used here. Since there is only a single RelevantGraphSurface component, only the region it was in, in the tile it is placed in, will be enabled. If there would have been several RelevantGraphSurface in other tiles, those regions could have been enabled as well.

Here another tile size was used along with the OnlyForCompletelyInsideTile. Note that the region on top of the orange cube is gone now since the region borders do not intersect that region (and there is no RelevantGraphSurface component inside it).

Note
When not using tiles. OnlyForCompletelyInsideTile is equivalent to RequireForAll.
bool scanEmptyGraph

If true, scanning the graph will yield a completely empty graph.

Useful if you want to replace the graph with a custom navmesh for example

bool showMeshOutline = true

Show an outline of the polygons in the Unity Editor.

bool showMeshSurface

Show the surface of the navmesh.

bool showNodeConnections

Show the connections between the polygons in the Unity Editor.

List<NavmeshTile> stagingTiles = new List<NavmeshTile>()
private

List of tiles that have been calculated in a graph update, but have not yet been added to the graph.

When updating the graph in a separate thread, large changes cannot be made directly to the graph as other scripts might use the graph data structures at the same time in another thread. So the tiles are calculated, but they are not yet connected to the existing tiles that will be done in UpdateAreaPost which runs in the Unity thread.

List<string> tagMask = new List<string>()

Objects tagged with any of these tags will be rasterized.

Note that this extends the layer mask, so if you only want to use tags, set mask to 'Nothing'.

See Also
mask
int terrainSampleSize = 3

Controls how large the sample size for the terrain is.

A higher value is faster to scan but less accurate

const int TileIndexMask = 0x7FFFF
const int TileIndexOffset = 12
NavmeshTile [] tiles
private

All tiles.

A tile can be got from a tile coordinate as tiles[x + z*tileXCount]

int tileSizeX = 128

Size of a tile along the X axis in voxels.

Warning
Do not modify, it is set from editorTileSize at Scan
int tileSizeZ = 128

Size of a tile along the Z axis in voxels.

Warning
Do not modify, it is set from editorTileSize at Scan
int tileXCount

Number of tiles along the X-axis.

int tileZCount

Number of tiles along the Z-axis.

bool useTiles

If true, divide the graph into tiles, otherwise use a single tile covering the whole graph.

const int VertexIndexMask = 0xFFF
float walkableClimb = 0.5F

Height the character can climb.

float walkableHeight = 2F

Character height.

Property Documentation

float CellHeight
getprivate
int CharacterRadiusInVoxels
getprivate

Convert character radius to a number of voxels.

Bounds forcedBounds
get

World bounds for the graph.

Defined as a bounds object with size forcedBoundsSize and centered at forcedBoundsCenter

int TileBorderSizeInVoxels
getprivate

Number of extra voxels on each side of a tile to ensure accurate navmeshes near the tile border.

The width of a tile is expanded by 2 times this value (1x to the left and 1x to the right)

float TileBorderSizeInWorldUnits
getprivate

Event Documentation

System.Action<NavmeshTile[]> OnRecalculatedTiles

Called when tiles have been completely recalculated.

This is called after scanning the graph and after performing graph updates that completely recalculate tiles (not ones that simply modify e.g penalties). It is not called after NavmeshCut updates.


The documentation for this class was generated from the following file: