PathForge — API Reference
Every public type and method. For a guided start, see Getting Started.
Requirements: Unity 6 (6000.0 or later), Mono or IL2CPP. Native plugins ship for Windows x64, macOS 11 or later (Intel and Apple Silicon), Linux x64 and ARM64, and Android ARM64. The plugin loads automatically — no setup.
All Base types are in the global namespace. The shared-field types (marked Pro) are in
the PathForge.Pro namespace and need the PathForge Pro package.
| Type | Tier | Purpose |
|---|---|---|
DnskSolver |
Base | Builds a graph and answers route queries; dynamic maps; save and load |
PathResult |
Base | Result of a route query |
HeuristicMode |
Base | Build option (one value) |
IGraphSource |
Base | Interface for your own graph |
| Graph adapters | Base | Grid, Tilemap, Hex, Waypoint, Mesh, NavMesh |
DnskPathFollower |
Base | MonoBehaviour that walks an agent along a route |
| Target helpers | Base | Pick target cells in a ring, rectangle or circle |
DnskNative, DnskLogger, DnskPlugin |
Base | Plugin check, diagnostics, log routing |
DnskField |
Pro | Shared fields for crowds |
FieldStep, DnskFieldMetrics |
Pro | Field results |
DnskFieldCache |
Pro | Cache of computed fields |
DnskProRequiredException |
Pro | Thrown by field calls on a Base-only install |
DnskSolver
Owns one graph in native memory. Implements IDisposable — call Dispose() in OnDestroy().
| Member | Description |
|---|---|
DnskSolver(uint numVertices) |
Create a solver for vertex IDs 0 .. numVertices-1. Throws InvalidOperationException if the C# package and the native plugin are different versions. |
AddEdges(uint[] sources, uint[] targets, uint[] weights) |
Add directed edges (three arrays of equal length) before Build(). Rule: every weight 1 .. MaxEdgeWeight, every vertex ID below the vertex count — otherwise ArgumentException naming the rule, and no edge of that call is added. |
Build(HeuristicMode mode = Landmarks) |
Finish the graph. Call once. |
BuildFrom(IGraphSource source, HeuristicMode mode = Landmarks) |
AddEdges + Build from a graph source (any adapter, or your own). One-way edges and different costs per direction are fine. |
QueryPath(uint source, uint target, uint[] pathBuffer) |
Shortest route from source to target, written into pathBuffer (vertex IDs, source first). Returns PathResult. No managed allocation. A buffer shorter than the route cuts the route off — size it cols × rows (or NumVertices) to be safe. |
GetCounters() |
Statistics of the last QueryPath as DnskNative.QueryCounters: nodeExpansions, edgeScans, heapOps, pathCost, elapsedTimeNs, plus two internal bookkeeping counters (activeWrites, sealedCount). The sample scenes show them live. |
SetEdgeWeight(uint source, uint target, uint weight) |
Dynamic maps: set the cost of edge source → target. Also reopens a closed edge. See rules. |
CloseEdge(uint source, uint target) |
Dynamic maps: close one direction of an edge (door, one-way gate). Reopen with SetEdgeWeight. |
BlockVertex(uint vertex) / UnblockVertex(uint vertex) |
Dynamic maps: close / reopen every edge of a vertex. Safe to repeat; block + unblock restores every route exactly. Unblocking keeps edges to still-blocked vertices and closed edges closed. |
SaveGraph() |
The built graph as byte[], including its current dynamic-map state. See saving and loading. |
LoadGraph(byte[] buffer) |
Replace the graph with saved bytes. The solver can answer queries right away — no Build(). |
Dispose() |
Free native memory, including every field created from this solver. Afterwards every call throws ObjectDisposedException. |
GraphVersion (uint) |
0 before Build() / LoadGraph(), 1 after, +1 for every dynamic-map call that changed a weight. It changes exactly when results can change — use it as the cache key for fields. |
MaxEdgeWeight (const uint) |
536 870 912. Edge weights are 1 .. MaxEdgeWeight. |
VerboseFfiLogging (static bool) |
Log every native call through DnskLogger.Log (debugging only; off by default because it costs far more than the calls). Errors are always logged. |
Dynamic maps rules
- Build the graph as the base: every cell that can ever be walkable, each edge at the
lowest cost it can ever have. The builders’
dynamicCelloption does this for you. - At runtime, without a rebuild: block and unblock vertices, close edges, and set any edge
cost between its base cost and
MaxEdgeWeight. Every route and field stays exact; the calls allocate nothing. - A cost below the base, or new vertices or connections, need a new solver
(
SetEdgeWeightbelow the base throwsArgumentOutOfRangeException). - A cost set on an edge of a blocked vertex takes effect once both ends are unblocked.
- Fields computed before a change are stale: reading one throws
InvalidOperationException(“field is stale”) until you compute it again.GraphVersiontells you when. - If distances in your graph reach 1 073 741 824 (2^30), the dynamic-map calls throw
InvalidOperationException— scale the weights down.
Saving and loading
byte[] saved = solver.SaveGraph(); // once, when the map is final
File.WriteAllBytes(path, saved);
var solver2 = new DnskSolver(numVertices); // at startup
solver2.LoadGraph(File.ReadAllBytes(path));
var result = solver2.QueryPath(source, target, pathBuffer); // works immediately
- A loaded graph answers every query exactly like the solver that saved it.
SaveGraph()needs a built or loaded graph. CallLoadGraph()on a fresh solver.- The saved state is the new base: a vertex blocked before saving stays blocked after
loading, a raised cost becomes the lowest cost. Save before blocking if you need to reopen
after a load.
GraphVersionstarts again at 1.
PathResult
Returned by QueryPath.
| Field | Type | Description |
|---|---|---|
Reachable |
bool |
true if a route exists. |
PathLength |
int |
Vertices written into the buffer, source and target included. |
Distance |
uint |
Total cost (sum of edge weights); uint.MaxValue if unreachable. |
HeuristicMode
One value, Landmarks — the default. Pass it or leave the argument out; routes are always
shortest paths, on every graph.
IGraphSource
Your own graph, for BuildFrom. Engine-free (no UnityEngine). Details and examples:
Bring Your Graph.
| Member | Description |
|---|---|
uint NumVertices |
Vertex count; IDs are 0 .. NumVertices-1. |
uint NumEdges |
Exact number of directed edges. |
void FillEdges(uint[] sources, uint[] targets, uint[] weights) |
Write all edges into the three arrays (length NumEdges). Two-way connections are two edges. Weights 1 .. MaxEdgeWeight. |
bool IsBlocked(uint vertex) |
Whether a vertex is impassable (used by the helpers, not by the solver). |
Graph adapters
All implement IGraphSource.
GridGraphBuilder — Tilemap, tile = wall
| Member | Description |
|---|---|
GridGraphBuilder(Grid grid, Tilemap tilemap) |
Size from tilemap.cellBounds, 4 neighbours. |
GridGraphBuilder(Grid grid, Tilemap tilemap, uint cols, uint rows) |
Explicit size, 4 neighbours. |
GridGraphBuilder(Grid grid, Tilemap tilemap, uint cols, uint rows, bool diagonal) |
diagonal: true = 8 neighbours (straight steps cost 10, diagonal 14; no cutting corners). |
GridGraphBuilder(..., bool diagonal, Func<uint,uint,bool>? dynamicCell) |
Cells where dynamicCell(x, y) is true can open and close at runtime. |
VertexToWorld(uint vertex) |
World position of the cell centre. |
ApplyDynamicCells(DnskSolver solver) |
After BuildFrom: close the dynamic cells that are walls right now. Call once. |
RefreshCell(DnskSolver solver, uint x, uint y) |
After you change the tile of dynamic cell (x, y): apply it, no rebuild. Diagonals past its corners follow. |
Vertex ID = x + y * cols.
TilemapGraphBuilder — Tilemap, tile = walkable, costs per tile
| Member | Description |
|---|---|
TilemapGraphBuilder(Tilemap tilemap) |
Bounds from the tilemap, 4 neighbours. |
TilemapGraphBuilder(Tilemap tilemap, BoundsInt bounds) |
Explicit bounds, 4 neighbours. |
TilemapGraphBuilder(Tilemap tilemap, BoundsInt bounds, bool diagonal) |
Optional 8 neighbours. |
TilemapGraphBuilder(..., bool diagonal, Func<uint,uint,bool>? dynamicCell) |
Dynamic cells: tiles placed, removed or swapped at runtime; dynamic cells start at cost 1. |
SetTileWeight(TileBase tile, uint weight) |
Cost of a tile type (default 1). Valid 1 .. 536 870 912; with diagonals 1 .. 38 347 922 (a diagonal step costs weight × 14). Otherwise ArgumentOutOfRangeException. |
ApplyDynamicCells(DnskSolver solver) / RefreshCell(DnskSolver solver, uint x, uint y) |
As for GridGraphBuilder. |
HexGraphBuilder — pointy-top hex grid (odd rows offset)
| Member | Description |
|---|---|
HexGraphBuilder(uint cols, uint rows, Func<uint,uint,bool> blocked, float cellWidth = 1, float rowHeight = 0.866) |
Blocked cells from a predicate; up to 6 neighbours, equal cost. |
HexGraphBuilder(uint cols, uint rows, Func<uint,uint,bool> blocked, Func<uint,uint,bool>? dynamicCell, float cellWidth = 1, float rowHeight = 0.866) |
With dynamic cells. |
HexToWorld(uint vertex) |
World position of the hex centre. |
ApplyDynamicCells(DnskSolver solver) / RefreshCell(DnskSolver solver, uint x, uint y) |
As for GridGraphBuilder (block / unblock). |
WaypointGraphBuilder — points you place
| Member | Description |
|---|---|
WaypointGraphBuilder(Transform[] waypoints) |
Connects waypoints closer than 100 units. |
WaypointGraphBuilder(Transform[] waypoints, float connectionDistance) |
Connects waypoints closer than connectionDistance. Cost = distance, rounded up, at least 1. |
VertexToWorld(uint vertex) |
Position of the waypoint. |
MeshGraphBuilder — any triangle mesh
Each triangle is a vertex; triangles that share an edge are connected.
| Member | Description |
|---|---|
MeshGraphBuilder(Mesh mesh) |
All triangles walkable. |
MeshGraphBuilder(Mesh mesh, Func<int,bool>? triangleBlocked) |
Triangle index → blocked. |
TriangleCentroid(uint vertex) |
Triangle centre in mesh-local space (apply the object’s transform for world space). |
NavMeshGraphBuilder — Unity’s baked NavMesh
| Member | Description |
|---|---|
NavMeshGraphBuilder() |
All areas walkable. |
NavMeshGraphBuilder(Func<int,bool>? areaBlocked) |
NavMesh area index → blocked. |
TriangleCentroid(uint vertex) |
Triangle centre in world space. |
Polyline(uint[] trianglePath) |
The walkable line through a triangle route, straightened around corners (world space); null for an empty route. This is what an agent should walk. |
DnskPathFollower
MonoBehaviour that queries a route and moves its GameObject along it. Set it up from code —
Solver and the converter can’t be set in the Inspector.
| Member | Description |
|---|---|
Solver (DnskSolver) |
The solver to query. |
StartVertex, TargetVertex (uint) |
Route start and goal. |
MoveSpeed (float) |
World units per second (default 5). |
IsFollowing (bool) |
true while moving. |
PathRemaining (int) |
Steps left. |
SetVertexToWorld(Func<uint,Vector3> converter) |
Vertex → world position, e.g. builder.VertexToWorld. Required before StartPath(). |
SetPathBuffer(uint[] buffer) |
Replace the route buffer (default 256 vertices) for longer routes. |
StartPath() / StartPath(uint startVertex) |
Query and start moving. Throws InvalidOperationException if Solver or the converter is missing. |
Target helpers
Grid helpers that return walkable cells as target candidates (cols = grid width).
| Member | Description |
|---|---|
RingTargetGenerator.GenerateRing(IGraphSource graph, uint cols, uint centerX, uint centerY, uint radius, uint maxSlots) |
Up to maxSlots cells at walking distance radius from the centre, spread evenly. |
TargetAreaSampler.SampleRegion(IGraphSource graph, uint cols, uint xMin, uint xMax, uint yMin, uint yMax) |
Walkable cells in a rectangle. |
TargetAreaSampler.SampleCircle(IGraphSource graph, uint cols, uint centerX, uint centerY, uint radius) |
Walkable cells in a circle. |
Diagnostics and logging
| Member | Description |
|---|---|
DnskNative.Available (bool) |
true if the native plugin loaded and matches this package version. |
DnskNative.LoadError (string?) |
Why loading failed; null if it loaded. |
DnskNative.Diagnose() |
Full report: where the plugin was looked for, what was found, the system error. Start here when the plugin won’t load. |
DnskNative.OK, InvalidInput, Panic, BelowBase, Unsupported |
Status codes 0–4 in error messages: success, invalid input, internal error in the native plugin (reported as an exception, never a crash), cost below the base, graph not supported for dynamic changes. |
DnskLogger.Log, LogWarning, LogError (Action<string>) |
Where PathForge sends its messages. Assign your own handlers (for example Debug.LogWarning) to see them. |
DnskPlugin.AddSearchRoot(string root) |
Add a folder to search for the native plugin. Not needed for a normal install — DnskPluginLocator.Register() does it automatically before the first scene loads. |
Other public types — DnskHandle, PinnedHandle, GridEdgeEnumerator, HexEdgeEnumerator,
DynamicGridCells, MeshTriangleAdjacency, NavMeshFunnel, and the remaining DnskNative
members — are building blocks of PathForge’s own assemblies; game code does not need them. The
SampleKit types belong to the sample scenes.
DnskField (Pro)
Shared fields: one computation tells every agent its next step toward one target or the nearest of many. Create it from a built solver:
using PathForge.Pro;
var field = solver.CreateField();
The field shares the solver’s memory — dispose the solver, not the field.
| Method | Description |
|---|---|
ComputeField(uint target, uint[] distancesOut, bool[]? exploredOut = null) |
Field toward one target. distancesOut[v] = cost from v to the target, uint.MaxValue if unreachable. exploredOut (optional) marks reachable vertices. |
ComputeWeightedField(uint[] targets, uint[]? costs, uint[] distancesOut, uint[] rootsOut) |
Field toward the nearest of several targets. rootsOut[v] = the target vertex v heads to. costs (one per target, optional) makes some targets less attractive; null = equal. |
ComputeFieldWatched(uint target, byte[] watchedBitmap, uint watchedLeft, uint[] distancesOut) |
Field that stops as soon as every watched vertex is reached. watchedBitmap[v] = 1 marks a watched vertex; watchedLeft = how many are watched. null and 0 compute the full field. |
NextStep(uint vertex) |
Next vertex toward the target, as FieldStep. Throws InvalidOperationException on a blocked or unreachable vertex. |
BatchNextStep(uint[] vertices, uint[] nextOut, bool[] terminalOut) |
Next step for many agents in one call (three arrays of equal length). Returns how many results are valid; blocked or unreachable vertices are skipped. |
ExtractPath(uint start, uint[] pathBuffer, uint maxSteps) |
Whole route from start along the field; returns the number of vertices written (at most maxSteps). |
Root(uint vertex) |
After ComputeWeightedField: the target this vertex heads to. |
BatchQuery(uint[] sources, uint[] targets, uint[] distancesOut, uint[]? rootsOut = null) |
Costs for many source → target pairs in one call (arrays of equal length). rootsOut (optional) returns the nearest target per pair. |
GetMetrics(DnskNative.QueryCounters counters) |
DnskFieldMetrics of the last field, combined with solver.GetCounters(). |
After a dynamic-map change, compute the field again — reading the old one throws
InvalidOperationException (“field is stale”).
FieldStep (Pro)
| Field | Type | Description |
|---|---|---|
NextVertex |
uint |
The next vertex toward the target. |
IsTerminal |
bool |
true if this vertex is the target. |
DnskFieldMetrics (Pro)
| Field | Type | Description |
|---|---|---|
RootsUsed |
uint |
Targets that at least one vertex heads to (weighted field). |
MaxAgentsPerRoot |
uint |
Most vertices heading to one target. |
BuildTimeNs |
ulong |
Time of the computation in nanoseconds. |
NodeExpansions, EdgeScans |
ulong |
Work done by the computation. |
DnskFieldCache (Pro)
Caches computed fields by target, graph version and mode.
| Member | Description |
|---|---|
GetOrCompute(FieldSignature sig, Func<FieldSignature,FieldData> compute) |
Cached field, or compute and cache it. |
SyncGraphVersion(uint graphVersion) |
Pass solver.GraphVersion (e.g. once per frame); a new version drops every cached field. |
Invalidate() |
Drop every cached field. |
IncrementGraphVersion() |
Count up the cached version and drop every cached field. |
HitCount, MissCount (int), GraphVersion (uint) |
Cache statistics and current version. |
FieldSignature(uint target, uint graphVersion, HeuristicMode mode) is the key;
FieldData(uint[] distances, uint[] roots, DnskFieldMetrics metrics) the cached value
(Distances, Roots, Metrics).
DnskProRequiredException (Pro)
Thrown by every field call when PathForge Pro is not installed, with a message telling you to
install it. Derives from InvalidOperationException.
Errors
| What happened | What you get |
|---|---|
| No route exists | QueryPath returns Reachable = false, Distance = uint.MaxValue |
| The route is longer than your buffer | The route is cut off at the buffer length — use a larger buffer |
A weight of 0 or above MaxEdgeWeight, or a vertex ID ≥ the vertex count, in AddEdges / BuildFrom |
ArgumentException naming the rule; no edge of that call is added |
A query, field call or SaveGraph() before Build() / LoadGraph(); Build() twice |
InvalidOperationException |
LoadGraph(null) |
ArgumentNullException |
LoadGraph with damaged or truncated bytes |
InvalidOperationException; the solver is unchanged |
SetEdgeWeight below the edge’s base cost |
ArgumentOutOfRangeException — build a new solver with the lower cost |
A dynamic-map call with an unknown vertex or edge, or a weight outside 1 .. MaxEdgeWeight |
ArgumentException; nothing changes |
| A dynamic-map call on a graph whose distances reach 2^30 | InvalidOperationException — scale the weights down |
| Reading a field after a dynamic-map change | InvalidOperationException “field is stale” — compute the field again |
NextStep on a blocked or unreachable vertex |
InvalidOperationException (BatchNextStep skips such vertices) |
| A field call without PathForge Pro | DnskProRequiredException |
| Any call on a disposed solver | ObjectDisposedException |
| The C# package and the native plugin are different versions | InvalidOperationException when creating a DnskSolver — reinstall the package |
| Any other native failure | InvalidOperationException with the status code |