summaryrefslogtreecommitdiff
path: root/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Graphs/Navmesh/Jobs/JobBuildTileMeshFromVoxels.cs
blob: a6ca868005110663f4c0944f9b8098d15aaf0678 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
using Pathfinding.Jobs;
using Pathfinding.Util;
using Pathfinding.Graphs.Navmesh.Voxelization.Burst;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine;
using Unity.Profiling;

namespace Pathfinding.Graphs.Navmesh.Jobs {
	/// <summary>
	/// Scratch space for building navmesh tiles using voxelization.
	///
	/// This uses quite a lot of memory, so it is used by a single worker thread for multiple tiles in order to minimize allocations.
	/// </summary>
	public struct TileBuilderBurst : IArenaDisposable {
		public LinkedVoxelField linkedVoxelField;
		public CompactVoxelField compactVoxelField;
		public NativeList<ushort> distanceField;
		public NativeQueue<Int3> tmpQueue1;
		public NativeQueue<Int3> tmpQueue2;
		public NativeList<VoxelContour> contours;
		public NativeList<int> contourVertices;
		public VoxelMesh voxelMesh;

		public TileBuilderBurst (int width, int depth, int voxelWalkableHeight, int maximumVoxelYCoord) {
			linkedVoxelField = new LinkedVoxelField(width, depth, maximumVoxelYCoord);
			compactVoxelField = new CompactVoxelField(width, depth, voxelWalkableHeight, Allocator.Persistent);
			tmpQueue1 = new NativeQueue<Int3>(Allocator.Persistent);
			tmpQueue2 = new NativeQueue<Int3>(Allocator.Persistent);
			distanceField = new NativeList<ushort>(0, Allocator.Persistent);
			contours = new NativeList<VoxelContour>(Allocator.Persistent);
			contourVertices = new NativeList<int>(Allocator.Persistent);
			voxelMesh = new VoxelMesh {
				verts = new NativeList<Int3>(Allocator.Persistent),
				tris = new NativeList<int>(Allocator.Persistent),
				areas = new NativeList<int>(Allocator.Persistent),
			};
		}

		void IArenaDisposable.DisposeWith (DisposeArena arena) {
			arena.Add(linkedVoxelField);
			arena.Add(compactVoxelField);
			arena.Add(distanceField);
			arena.Add(tmpQueue1);
			arena.Add(tmpQueue2);
			arena.Add(contours);
			arena.Add(contourVertices);
			arena.Add(voxelMesh);
		}
	}

	/// <summary>
	/// Builds tiles from a polygon soup using voxelization.
	///
	/// This job takes the following steps:
	/// - Voxelize the input meshes
	/// - Filter and process the resulting voxelization in various ways to remove unwanted artifacts and make it better suited for pathfinding.
	/// - Extract a walkable surface from the voxelization.
	/// - Triangulate this surface and create navmesh tiles from it.
	///
	/// This job uses work stealing to distribute the work between threads. The communication happens using a shared queue and the <see cref="currentTileCounter"/> atomic variable.
	/// </summary>
	[BurstCompile(CompileSynchronously = true)]
	// TODO: [BurstCompile(FloatMode = FloatMode.Fast)]
	public struct JobBuildTileMeshFromVoxels : IJob {
		public TileBuilderBurst tileBuilder;
		[ReadOnly]
		public TileBuilder.BucketMapping inputMeshes;
		[ReadOnly]
		public NativeArray<Bounds> tileGraphSpaceBounds;
		public Matrix4x4 voxelToTileSpace;

		/// <summary>
		/// Limits of the graph space bounds for the whole graph on the XZ plane.
		///
		/// Used to crop the border tiles to exactly the limits of the graph's bounding box.
		/// </summary>
		public Vector2 graphSpaceLimits;

		[NativeDisableUnsafePtrRestriction]
		public unsafe TileMesh.TileMeshUnsafe* outputMeshes;

		/// <summary>Max number of tiles to process in this job</summary>
		public int maxTiles;

		public int voxelWalkableClimb;
		public uint voxelWalkableHeight;
		public float cellSize;
		public float cellHeight;
		public float maxSlope;
		public RecastGraph.DimensionMode dimensionMode;
		public RecastGraph.BackgroundTraversability backgroundTraversability;
		public Matrix4x4 graphToWorldSpace;
		public int characterRadiusInVoxels;
		public int tileBorderSizeInVoxels;
		public int minRegionSize;
		public float maxEdgeLength;
		public float contourMaxError;
		[ReadOnly]
		public NativeArray<JobBuildRegions.RelevantGraphSurfaceInfo> relevantGraphSurfaces;
		public RecastGraph.RelevantGraphSurfaceMode relevantGraphSurfaceMode;

		[NativeDisableUnsafePtrRestriction]
		public unsafe int* currentTileCounter;

		public void SetOutputMeshes (NativeArray<TileMesh.TileMeshUnsafe> arr) {
			unsafe {
				outputMeshes = (TileMesh.TileMeshUnsafe*)arr.GetUnsafeReadOnlyPtr();
			}
		}

		public void SetCounter (NativeReference<int> counter) {
			unsafe {
				// Note: The pointer cast is only necessary when using early versions of the collections package.
				currentTileCounter = (int*)counter.GetUnsafePtr();
			}
		}

		private static readonly ProfilerMarker MarkerVoxelize = new ProfilerMarker("Voxelize");
		private static readonly ProfilerMarker MarkerFilterLedges = new ProfilerMarker("FilterLedges");
		private static readonly ProfilerMarker MarkerFilterLowHeightSpans = new ProfilerMarker("FilterLowHeightSpans");
		private static readonly ProfilerMarker MarkerBuildCompactField = new ProfilerMarker("BuildCompactField");
		private static readonly ProfilerMarker MarkerBuildConnections = new ProfilerMarker("BuildConnections");
		private static readonly ProfilerMarker MarkerErodeWalkableArea = new ProfilerMarker("ErodeWalkableArea");
		private static readonly ProfilerMarker MarkerBuildDistanceField = new ProfilerMarker("BuildDistanceField");
		private static readonly ProfilerMarker MarkerBuildRegions = new ProfilerMarker("BuildRegions");
		private static readonly ProfilerMarker MarkerBuildContours = new ProfilerMarker("BuildContours");
		private static readonly ProfilerMarker MarkerBuildMesh = new ProfilerMarker("BuildMesh");
		private static readonly ProfilerMarker MarkerConvertAreasToTags = new ProfilerMarker("ConvertAreasToTags");
		private static readonly ProfilerMarker MarkerRemoveDuplicateVertices = new ProfilerMarker("RemoveDuplicateVertices");
		private static readonly ProfilerMarker MarkerTransformTileCoordinates = new ProfilerMarker("TransformTileCoordinates");

		public void Execute () {
			for (int k = 0; k < maxTiles; k++) {
				// Grab the next tile index that we should calculate
				int i;
				unsafe {
					i = System.Threading.Interlocked.Increment(ref UnsafeUtility.AsRef<int>(currentTileCounter)) - 1;
				}
				if (i >= tileGraphSpaceBounds.Length) return;

				tileBuilder.linkedVoxelField.ResetLinkedVoxelSpans();
				if (dimensionMode == RecastGraph.DimensionMode.Dimension2D && backgroundTraversability == RecastGraph.BackgroundTraversability.Walkable) {
					tileBuilder.linkedVoxelField.SetWalkableBackground();
				}

				var bucketStart = i > 0 ? inputMeshes.bucketRanges[i-1] : 0;
				var bucketEnd = inputMeshes.bucketRanges[i];
				MarkerVoxelize.Begin();
				new JobVoxelize {
					inputMeshes = inputMeshes.meshes,
					bucket = inputMeshes.pointers.GetSubArray(bucketStart, bucketEnd - bucketStart),
					voxelWalkableClimb = voxelWalkableClimb,
					voxelWalkableHeight = voxelWalkableHeight,
					cellSize = cellSize,
					cellHeight = cellHeight,
					maxSlope = maxSlope,
					graphTransform = graphToWorldSpace,
					graphSpaceBounds = tileGraphSpaceBounds[i],
					graphSpaceLimits = graphSpaceLimits,
					voxelArea = tileBuilder.linkedVoxelField,
				}.Execute();
				MarkerVoxelize.End();



				MarkerFilterLedges.Begin();
				new JobFilterLedges {
					field = tileBuilder.linkedVoxelField,
					voxelWalkableClimb = voxelWalkableClimb,
					voxelWalkableHeight = voxelWalkableHeight,
					cellSize = cellSize,
					cellHeight = cellHeight,
				}.Execute();
				MarkerFilterLedges.End();

				MarkerFilterLowHeightSpans.Begin();
				new JobFilterLowHeightSpans {
					field = tileBuilder.linkedVoxelField,
					voxelWalkableHeight = voxelWalkableHeight,
				}.Execute();
				MarkerFilterLowHeightSpans.End();

				MarkerBuildCompactField.Begin();
				new JobBuildCompactField {
					input = tileBuilder.linkedVoxelField,
					output = tileBuilder.compactVoxelField,
				}.Execute();
				MarkerBuildCompactField.End();

				MarkerBuildConnections.Begin();
				new JobBuildConnections {
					field = tileBuilder.compactVoxelField,
					voxelWalkableHeight = (int)voxelWalkableHeight,
					voxelWalkableClimb = voxelWalkableClimb,
				}.Execute();
				MarkerBuildConnections.End();

				MarkerErodeWalkableArea.Begin();
				new JobErodeWalkableArea {
					field = tileBuilder.compactVoxelField,
					radius = characterRadiusInVoxels,
				}.Execute();
				MarkerErodeWalkableArea.End();

				MarkerBuildDistanceField.Begin();
				new JobBuildDistanceField {
					field = tileBuilder.compactVoxelField,
					output = tileBuilder.distanceField,
				}.Execute();
				MarkerBuildDistanceField.End();

				MarkerBuildRegions.Begin();
				new JobBuildRegions {
					field = tileBuilder.compactVoxelField,
					distanceField = tileBuilder.distanceField,
					borderSize = tileBorderSizeInVoxels,
					minRegionSize = Mathf.RoundToInt(minRegionSize),
					srcQue = tileBuilder.tmpQueue1,
					dstQue = tileBuilder.tmpQueue2,
					relevantGraphSurfaces = relevantGraphSurfaces,
					relevantGraphSurfaceMode = relevantGraphSurfaceMode,
					cellSize = cellSize,
					cellHeight = cellHeight,
					graphTransform = graphToWorldSpace,
					graphSpaceBounds = tileGraphSpaceBounds[i],
				}.Execute();
				MarkerBuildRegions.End();

				MarkerBuildContours.Begin();
				new JobBuildContours {
					field = tileBuilder.compactVoxelField,
					maxError = contourMaxError,
					maxEdgeLength = maxEdgeLength,
					buildFlags = VoxelUtilityBurst.RC_CONTOUR_TESS_WALL_EDGES | VoxelUtilityBurst.RC_CONTOUR_TESS_TILE_EDGES,
					cellSize = cellSize,
					outputContours = tileBuilder.contours,
					outputVerts = tileBuilder.contourVertices,
				}.Execute();
				MarkerBuildContours.End();

				MarkerBuildMesh.Begin();
				new JobBuildMesh {
					contours = tileBuilder.contours,
					contourVertices = tileBuilder.contourVertices,
					mesh = tileBuilder.voxelMesh,
					field = tileBuilder.compactVoxelField,
				}.Execute();
				MarkerBuildMesh.End();

				unsafe {
					TileMesh.TileMeshUnsafe* outputTileMesh = outputMeshes + i;
					*outputTileMesh = new TileMesh.TileMeshUnsafe {
						verticesInTileSpace = new UnsafeAppendBuffer(0, 4, Allocator.Persistent),
						triangles = new UnsafeAppendBuffer(0, 4, Allocator.Persistent),
						tags = new UnsafeAppendBuffer(0, 4, Allocator.Persistent),
					};

					MarkerConvertAreasToTags.Begin();
					new JobConvertAreasToTags {
						areas = tileBuilder.voxelMesh.areas,
					}.Execute();
					MarkerConvertAreasToTags.End();

					MarkerRemoveDuplicateVertices.Begin();
					new MeshUtility.JobRemoveDuplicateVertices {
						vertices = tileBuilder.voxelMesh.verts.AsArray(),
						triangles = tileBuilder.voxelMesh.tris.AsArray(),
						tags = tileBuilder.voxelMesh.areas.AsArray(),
						outputTags = &outputTileMesh->tags,
						outputVertices = &outputTileMesh->verticesInTileSpace,
						outputTriangles = &outputTileMesh->triangles,
					}.Execute();
					MarkerRemoveDuplicateVertices.End();

					MarkerTransformTileCoordinates.Begin();
					new JobTransformTileCoordinates {
						vertices = &outputTileMesh->verticesInTileSpace,
						matrix = voxelToTileSpace,
					}.Execute();
					MarkerTransformTileCoordinates.End();
				}
			}
		}
	}
}