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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
|
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
using Pathfinding;
using Pathfinding.Drawing;
using Pathfinding.Util;
using Unity.Burst;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Jobs;
using Unity.Collections.LowLevel.Unsafe;
using Pathfinding.Graphs.Util;
/// <summary>
/// Navmesh cutting is used for fast recast/navmesh graph updates.
///
/// Navmesh cutting is used to cut holes into an existing navmesh generated by a recast or navmesh graph.
/// Recast/navmesh graphs usually only allow either just changing parameters on existing nodes (e.g make a whole triangle unwalkable) which is not very flexible or recalculate a whole tile which is pretty slow.
/// With navmesh cutting you can remove (cut) parts of the navmesh that is blocked by obstacles such as a new building in an RTS game however you cannot add anything new to the navmesh or change
/// the positions of the nodes. This is significantly faster than recalculating whole tiles from scratch in a recast graph.
///
/// [Open online documentation to see videos]
///
/// The NavmeshCut component uses a 2D shape to cut the navmesh with. This shape can be produced by either one of the built-in 2D shapes (rectangle/circle) or one of the 3D shapes (cube/sphere/capsule)
/// which will be projected down to a 2D shape when cutting happens. You can also specify a custom 2D mesh to use as a cut.
///
/// [Open online documentation to see images]
///
/// Note that the rectangle/circle shapes are not 3D. If you rotate them, you will see that the 2D shape will be rotated and then just projected down on the XZ plane.
/// Therefore it is recommended to use the 3D shapes (cube/sphere/capsule) in most cases since those are easier to use.
///
/// In the scene view the NavmeshCut looks like an extruded 2D shape because a navmesh cut also has a height. It will only cut the part of the
/// navmesh which it touches. For performance reasons it only checks the bounding boxes of the triangles in the navmesh, so it may cut triangles
/// whoose bounding boxes it intersects even if the triangle does not intersect the extruded shape. However in most cases this does not make a large difference.
///
/// It is also possible to set the navmesh cut to dual mode by setting the <see cref="isDual"/> field to true. This will prevent it from cutting a hole in the navmesh
/// and it will instead just split the navmesh along the border but keep both the interior and the exterior. This can be useful if you for example
/// want to change the penalty of some region which does not neatly line up with the navmesh triangles. It is often combined with the GraphUpdateScene component
/// (however note that the GraphUpdateScene component will not automatically reapply the penalty if the graph is updated again).
///
/// By default the navmesh cut does not take rotation or scaling into account. If you want to do that, you can set the <see cref="useRotationAndScale"/> field to true.
///
/// <b>Custom meshes</b>
/// For most purposes you can use the built-in shapes, however in some cases a custom cutting mesh may be useful.
/// The custom mesh should be a flat 2D shape like in the image below. The script will then find the contour of that mesh and use that shape as the cut.
/// Make sure that all normals are smooth and that the mesh contains no UV information. Otherwise Unity might split a vertex and then the script will not
/// find the correct contour. You should not use a very high polygon mesh since that will create a lot of nodes in the navmesh graph and slow
/// down pathfinding because of that. For very high polygon meshes it might even cause more suboptimal paths to be generated if it causes many
/// thin triangles to be added to the navmesh.
/// [Open online documentation to see images]
///
/// <b>Update frequency</b>
///
/// Navmesh cuts are typically pretty fast, so you may be tempted to make them update the navmesh very often (once every few frames perhaps), just because you can spare the CPU power.
/// However, updating the navmesh too often can also have consequences for agents that are following paths on the graph.
///
/// If a navmesh cut updates the graph near an agent, it will usually have to recalculate its path. If this happens too often, this can lead to the pathfinding
/// worker threads being overwhelmed by pathfinding requests, causing higher latency for individual pathfinding requests. This can, in turn, make agents less responsive.
///
/// So it's recommended to keep the update frequency reasonable. After all, a player is unlikely to notice if the navmesh was updated 20 times per second or 2 times per second (or even less often).
///
/// You can primarily control this using the <see cref="updateDistance"/> and <see cref="updateRotationDistance"/> fields. But you can also control the global frequency of updates. This is explained in the next section.
///
/// <b>Control updates through code</b>
/// Navmesh cuts are applied periodically, but sometimes you may want to ensure the graph is up to date right now.
/// Then you can use the following code.
/// <code>
/// // Schedule pending updates to be done as soon as the pathfinding threads
/// // are done with what they are currently doing.
/// AstarPath.active.navmeshUpdates.ForceUpdate();
/// // Block until the updates have finished
/// AstarPath.active.FlushGraphUpdates();
/// </code>
///
/// You can also control how often the scripts check for if any navmesh cut has changed.
/// If you have a very large number of cuts it may be good for performance to not check it as often.
/// <code>
/// // Check every frame (the default)
/// AstarPath.active.navmeshUpdates.updateInterval = 0;
///
/// // Check every 0.1 seconds
/// AstarPath.active.navmeshUpdates.updateInterval = 0.1f;
///
/// // Never check for changes
/// AstarPath.active.navmeshUpdates.updateInterval = -1;
/// // You will have to schedule updates manually using
/// AstarPath.active.navmeshUpdates.ForceUpdate();
/// </code>
///
/// You can also find this setting in the AstarPath inspector under Settings.
/// [Open online documentation to see images]
///
/// <b>Navmesh cutting and tags/penalties</b>
/// Navmesh cuts can only preserve tags for updates which happen when the graph is first scanned, or when a recast graph tile is recalculated from scratch.
///
/// This means that any tags that you apply dynamically using e.g. a <see cref="GraphUpdateScene"/> component may be lost when a navmesh cut is applied.
/// If you need to combine tags and navmesh cutting, it is therefore strongly recommended to use the <see cref="RecastMeshObj"/> component to apply the tags,
/// as that will work smoothly with navmesh cutting.
///
/// Internally, what happens is that when a graph is scanned, the navmesh cutting subsystem will take a snapshot of all triangles in the graph, including tags. This data will then be referenced
/// every time cutting happens and the tags from the snapshot will be copied to the new triangles after cutting has taken place.
///
/// You can also apply tags and penalties using a graph update after cutting has taken place. For example by subclassing a navmesh cut and overriding the <see cref="UsedForCut"/> method.
/// However, it is recommended to use the <see cref="RecastMeshObj"/> as mentioned before, as this is a more robust solution.
///
/// See: http://www.arongranberg.com/2013/08/navmesh-cutting/
/// </summary>
[AddComponentMenu("Pathfinding/Navmesh/Navmesh Cut")]
[ExecuteAlways]
[HelpURL("https://arongranberg.com/astar/documentation/stable/navmeshcut.html")]
public class NavmeshCut : NavmeshClipper {
public enum MeshType {
/// <summary>A 2D rectangle</summary>
Rectangle,
/// <summary>A 2D circle</summary>
Circle,
CustomMesh,
/// <summary>A 3D box which will be projected down to a 2D outline</summary>
Box,
/// <summary>A 3D sphere which will be projected down to a 2D outline</summary>
Sphere,
/// <summary>A 3D capsule which will be projected down to a 2D outline</summary>
Capsule,
}
public enum RadiusExpansionMode {
/// <summary>
/// If DontExpand is used then the cut will be exactly as specified with no modifications.
/// It will be the same for all graphs.
/// </summary>
DontExpand,
/// <summary>
/// If ExpandByAgentRadius is used then the cut will be expanded by the agent's radius (set in the recast graph settings)
/// in every direction. For navmesh graphs (which do not have a character radius) this is equivalent to DontExpand.
///
/// This is especially useful if you have multiple graphs for different unit sizes and want the cuts to be sized according to
/// the different units.
/// </summary>
ExpandByAgentRadius,
}
/// <summary>Shape of the cut</summary>
[Tooltip("Shape of the cut")]
public MeshType type = MeshType.Box;
/// <summary>
/// Custom mesh to use.
/// The contour(s) of the mesh will be extracted.
/// If you get the "max perturbations" error when cutting with this, check the normals on the mesh.
/// They should all point in the same direction. Try flipping them if that does not help.
///
/// This mesh should only be a 2D surface, not a volume.
/// </summary>
[Tooltip("The contour(s) of the mesh will be extracted. This mesh should only be a 2D surface, not a volume (see documentation).")]
public Mesh mesh;
/// <summary>Size of the rectangle</summary>
public Vector2 rectangleSize = new Vector2(1, 1);
/// <summary>Radius of the circle</summary>
public float circleRadius = 1;
/// <summary>Number of vertices on the circle</summary>
public int circleResolution = 6;
/// <summary>The cut will be extruded to this height</summary>
public float height = 1;
/// <summary>Scale of the custom mesh, if used</summary>
[Tooltip("Scale of the custom mesh")]
public float meshScale = 1;
public Vector3 center;
/// <summary>
/// How much the cut must move before the navmesh is updated.
/// A smaller distance gives better accuracy, but requires more updates when moving the object over time,
/// so it is often slower.
///
/// Even if the graph update itself is fast, having a low value can make agents have to recalculate their paths a lot more often,
/// leading to lower performance.
/// </summary>
[Tooltip("Distance between positions to require an update of the navmesh\nA smaller distance gives better accuracy, but requires more updates when moving the object over time, so it is often slower.")]
public float updateDistance = 0.4f;
/// <summary>
/// Only makes a split in the navmesh, but does not remove the geometry to make a hole.
/// This is slower than a normal cut
/// </summary>
[Tooltip("Only makes a split in the navmesh, but does not remove the geometry to make a hole")]
public bool isDual;
/// <summary>
/// If the cut should be expanded by the agent radius or not.
///
/// See <see cref="RadiusExpansionMode"/> for more details.
/// </summary>
public RadiusExpansionMode radiusExpansionMode = RadiusExpansionMode.ExpandByAgentRadius;
/// <summary>
/// Cuts geometry added by a NavmeshAdd component.
/// You rarely need to change this
/// </summary>
public bool cutsAddedGeom = true;
/// <summary>
/// How many degrees the object must rotate before the navmesh is updated.
/// Should be between 0 and 180.
/// </summary>
[Tooltip("How many degrees rotation that is required for an update to the navmesh. Should be between 0 and 180.")]
public float updateRotationDistance = 10;
/// <summary>
/// Includes rotation and scale in calculations.
///
/// If this is disabled, the object's rotation and scale is not taken into account when determining the shape of the cut.
///
/// Enabling this is a bit slower, since a lot more matrix multiplications are needed.
/// </summary>
[Tooltip("Includes rotation in calculations. This is slower since a lot more matrix multiplications are needed but gives more flexibility.")]
[UnityEngine.Serialization.FormerlySerializedAsAttribute("useRotation")]
public bool useRotationAndScale;
NativeList<float3> meshContourVertices;
NativeList<ContourBurst> meshContours;
/// <summary>cached transform component</summary>
protected Transform tr;
Mesh lastMesh;
protected override void Awake () {
base.Awake();
tr = transform;
}
protected override void OnDisable () {
// This needs to run in the editor as well which is why it is in OnDisable.
// OnDestroy will not necessarily get called in editor mode.
if (this.meshContourVertices.IsCreated) this.meshContourVertices.Dispose();
if (this.meshContours.IsCreated) this.meshContours.Dispose();
lastMesh = null;
base.OnDisable();
}
/// <summary>Cached variable, to avoid allocations</summary>
static readonly Dictionary<Int2, int> edges = new Dictionary<Int2, int>();
/// <summary>Cached variable, to avoid allocations</summary>
static readonly Dictionary<int, int> pointers = new Dictionary<int, int>();
/// <summary>
/// Forces this navmesh cut to update the navmesh.
///
/// This update is not instant, it is done the next time it is checked if it needs updating.
/// See: <see cref="NavmeshUpdates.updateInterval"/>
/// See: <see cref="NavmeshUpdates.ForceUpdate"/>
/// </summary>
public override void ForceUpdate () {
if (AstarPath.active != null) AstarPath.active.navmeshUpdates.ForceUpdateAround(this);
}
/// <summary>
/// Returns true if this object has moved so much that it requires an update.
/// When an update to the navmesh has been done, call NotifyUpdated to be able to get
/// relavant output from this method again.
/// </summary>
public override bool RequiresUpdate (GridLookup<NavmeshClipper>.Root previousState) {
return (tr.position-previousState.previousPosition).sqrMagnitude > updateDistance*updateDistance || (useRotationAndScale && (Quaternion.Angle(previousState.previousRotation, tr.rotation) > updateRotationDistance));
}
/// <summary>
/// Called whenever this navmesh cut is used to update the navmesh.
/// Called once for each tile the navmesh cut is in.
/// You can override this method to execute custom actions whenever this happens.
/// </summary>
public virtual void UsedForCut () {
}
/// <summary>Internal method to notify the NavmeshCut that it has just been used to update the navmesh</summary>
internal override void NotifyUpdated (GridLookup<NavmeshClipper>.Root previousState) {
previousState.previousPosition = tr.position;
if (useRotationAndScale) {
previousState.previousRotation = tr.rotation;
}
}
void CalculateMeshContour () {
if (mesh == null) return;
edges.Clear();
pointers.Clear();
Vector3[] verts = mesh.vertices;
int[] tris = mesh.triangles;
for (int i = 0; i < tris.Length; i += 3) {
// Make sure it is clockwise
if (VectorMath.IsClockwiseXZ(verts[tris[i+0]], verts[tris[i+1]], verts[tris[i+2]])) {
int tmp = tris[i+0];
tris[i+0] = tris[i+2];
tris[i+2] = tmp;
}
edges[new Int2(tris[i+0], tris[i+1])] = i;
edges[new Int2(tris[i+1], tris[i+2])] = i;
edges[new Int2(tris[i+2], tris[i+0])] = i;
}
// Construct a list of pointers along all edges
for (int i = 0; i < tris.Length; i += 3) {
for (int j = 0; j < 3; j++) {
if (!edges.ContainsKey(new Int2(tris[i+((j+1)%3)], tris[i+((j+0)%3)]))) {
pointers[tris[i+((j+0)%3)]] = tris[i+((j+1)%3)];
}
}
}
var contourVertexBuffer = new NativeList<float3>(Allocator.Persistent);
var contourBuffer = new NativeList<ContourBurst>(Allocator.Persistent);
// Follow edge pointers to generate the contours
for (int i = 0; i < verts.Length; i++) {
if (pointers.ContainsKey(i)) {
var startIndex = contourVertexBuffer.Length;
int s = i;
do {
int tmp = pointers[s];
//This path has been taken before
if (tmp == -1) break;
pointers[s] = -1;
contourVertexBuffer.Add(verts[s]);
s = tmp;
} while (s != i);
if (contourVertexBuffer.Length != startIndex) {
contourBuffer.Add(new ContourBurst {
startIndex = startIndex,
endIndex = contourVertexBuffer.Length,
ymin = 0,
ymax = 0,
});
}
}
}
if (this.meshContourVertices.IsCreated) this.meshContourVertices.Dispose();
if (this.meshContours.IsCreated) this.meshContours.Dispose();
this.meshContourVertices = contourVertexBuffer;
this.meshContours = contourBuffer;
}
/// <summary>
/// Bounds in XZ space after transforming using the *inverse* transform of the inverseTransform parameter.
/// The transformation will typically transform the vertices to graph space and this is used to
/// figure out which tiles the cut intersects.
/// </summary>
public override Rect GetBounds (GraphTransform inverseTransform, float radiusMargin) {
var buffers = ListPool<Contour>.Claim();
GetContour(buffers, inverseTransform.inverseMatrix, radiusMargin);
Rect r = new Rect();
for (int i = 0; i < buffers.Count; i++) {
var buffer = buffers[i].contour;
for (int k = 0; k < buffer.Count; k++) {
var p = buffer[k];
if (k == 0 && i == 0) {
r = new Rect(p.x, p.y, 0, 0);
} else {
r.xMax = System.Math.Max(r.xMax, p.x);
r.yMax = System.Math.Max(r.yMax, p.y);
r.xMin = System.Math.Min(r.xMin, p.x);
r.yMin = System.Math.Min(r.yMin, p.y);
}
}
ListPool<Vector2>.Release(ref buffer);
}
ListPool<Contour>.Release(ref buffers);
return r;
}
public struct Contour {
public float ymin;
public float ymax;
public List<Vector2> contour;
}
public struct ContourBurst {
public int startIndex;
public int endIndex;
public float ymin;
public float ymax;
}
Matrix4x4 contourTransformationMatrix {
get {
// Take rotation and scaling into account
if (useRotationAndScale) {
return tr.localToWorldMatrix * Matrix4x4.Translate(center);
} else {
return Matrix4x4.Translate(tr.position + center);
}
}
}
/// <summary>
/// Contour of the navmesh cut.
/// Fills the specified buffer with all contours.
/// The cut may contain several contours which is why the buffer is a list of lists.
/// </summary>
/// <param name="buffer">Will be filled with the result</param>
/// <param name="matrix">All points will be transformed using this matrix. They are in world space before the transformation. Typically this a transform that maps from world space to graph space.</param>
/// <param name="radiusMargin">The obstacle will be expanded by this amount. Typically this is the character radius for the graph. The MeshType.CustomMesh does not support this.
/// If #radiusExpansionMode is RadiusExpansionMode.DontExpand then this parameter is ignored.</param>
public void GetContour (List<Contour> buffer, Matrix4x4 matrix, float radiusMargin) {
var outputVertices = new UnsafeList<float2>(0, Allocator.Temp);
var outputContours = new UnsafeList<ContourBurst>(1, Allocator.Temp);
unsafe {
GetContourBurst(&outputVertices, &outputContours, matrix, radiusMargin);
}
for (int i = 0; i < outputContours.Length; i++) {
var list = ListPool<Vector2>.Claim();
var contour = outputContours[i];
for (int j = contour.startIndex; j < contour.endIndex; j++) {
list.Add(outputVertices[j]);
}
buffer.Add(new Contour {
ymin = contour.ymin,
ymax = contour.ymax,
contour = list,
});
}
outputVertices.Dispose();
outputContours.Dispose();
}
/// <summary>
/// Contour of the navmesh cut.
/// Fills the specified buffer with all contours.
/// The cut may contain several contours.
/// </summary>
/// <param name="outputVertices">Will be filled with all vertices</param>
/// <param name="outputContours">Will be filled with all contours that reference the outputVertices list.</param>
/// <param name="matrix">All points will be transformed using this matrix. They are in world space before the transformation. Typically this a matrix that maps from world space to graph space.</param>
/// <param name="radiusMargin">The obstacle will be expanded by this amount. Typically this is the character radius for the graph. The MeshType.CustomMesh does not support this.</param>
public unsafe void GetContourBurst (UnsafeList<float2>* outputVertices, UnsafeList<ContourBurst>* outputContours, Matrix4x4 matrix, float radiusMargin) {
if (radiusExpansionMode == RadiusExpansionMode.DontExpand) {
radiusMargin = 0;
}
if (type == MeshType.CustomMesh && (mesh != lastMesh || !meshContours.IsCreated || !meshContourVertices.IsCreated)) {
CalculateMeshContour();
lastMesh = mesh;
}
var job = new NavmeshCutJobs.JobCalculateContour {
outputVertices = outputVertices,
outputContours = outputContours,
matrix = matrix,
localToWorldMatrix = contourTransformationMatrix,
radiusMargin = radiusMargin,
circleResolution = circleResolution,
circleRadius = circleRadius,
rectangleSize = rectangleSize,
height = height,
meshType = type,
meshContours = (UnsafeList<ContourBurst>*) this.meshContours.GetUnsafeList(),
meshContourVertices = (UnsafeList<float3>*) this.meshContourVertices.GetUnsafeList(),
meshScale = meshScale,
};
NavmeshCutJobsCached.CalculateContourBurst(&job);
}
public static readonly Color GizmoColor = new Color(37.0f/255, 184.0f/255, 239.0f/255);
public static readonly Color GizmoColor2 = new Color(169.0f/255, 92.0f/255, 242.0f/255);
public override void DrawGizmos () {
if (tr == null) tr = transform;
bool selected = GizmoContext.InActiveSelection(tr);
var graph = AstarPath.active != null ? (AstarPath.active.data.recastGraph as NavmeshBase ?? AstarPath.active.data.navmesh) : null;
var matrix = graph != null ? graph.transform : GraphTransform.identityTransform;
var characterRadius = graph != null ? graph.NavmeshCuttingCharacterRadius : 0;
var contourVertices = new UnsafeList<float2>(0, Allocator.Temp);
var contours = new UnsafeList<NavmeshCut.ContourBurst>(0, Allocator.Temp);
unsafe {
GetContourBurst(&contourVertices, &contours, matrix.inverseMatrix, characterRadius);
}
var col = Color.Lerp(GizmoColor, Color.white, 0.5f);
col.a *= 0.5f;
using (Draw.WithColor(col)) {
// Draw all contours
for (int i = 0; i < contours.Length; i++) {
var contour = contours[i];
var ymid = (contour.ymin + contour.ymax)*0.5f;
var count = contour.endIndex - contour.startIndex;
for (int j = 0; j < count; j++) {
var v1 = contourVertices[contour.startIndex + j];
var v2 = contourVertices[contour.startIndex + (j+1) % count];
var p1 = new Vector3(v1.x, ymid, v1.y);
var p2 = new Vector3(v2.x, ymid, v2.y);
// Note: Drawn with a stronger color
Draw.Line(matrix.Transform(p1), matrix.Transform(p2), GizmoColor);
if (selected) {
Vector3 p1low = p1, p2low = p2, p1high = p1, p2high = p2;
p1low.y = p2low.y = contour.ymin;
p1high.y = p2high.y = contour.ymax;
Draw.Line(matrix.Transform(p1low), matrix.Transform(p2low));
Draw.Line(matrix.Transform(p1high), matrix.Transform(p2high));
Draw.Line(matrix.Transform(p1low), matrix.Transform(p1high));
}
}
}
}
if (selected) {
switch (type) {
case MeshType.Box:
using (Draw.WithMatrix(contourTransformationMatrix * Matrix4x4.Scale(new Vector3(rectangleSize.x, height, rectangleSize.y)))) {
Draw.WireBox(Vector3.zero, Vector3.one, GizmoColor2);
}
break;
case MeshType.Capsule: {
var m = contourTransformationMatrix;
var height = Mathf.Max(this.height, circleRadius * 2);
var scaleFactorX = math.length(m.GetColumn(0));
var scaleFactorZ = math.length(m.GetColumn(2));
var radius = this.circleRadius * math.max(scaleFactorX, scaleFactorZ);
var mainAxis = ((Vector3)m.GetColumn(1)).normalized;
var hemispherePos1 = contourTransformationMatrix.MultiplyPoint3x4(new Vector3(0, height*0.5f, 0)) - mainAxis * radius;
var hemispherePos2 = contourTransformationMatrix.MultiplyPoint3x4(-new Vector3(0, height*0.5f, 0)) + mainAxis * radius;
Draw.WireCapsule(hemispherePos1, hemispherePos2, radius, GizmoColor2);
break;
}
case MeshType.Sphere: {
var uniformScaleFactor = useRotationAndScale ? math.cmax(tr.lossyScale) : 1;
var sphereMatrix = Matrix4x4.TRS(tr.position, useRotationAndScale ? tr.rotation : Quaternion.identity, Vector3.one * uniformScaleFactor) * Matrix4x4.Translate(center);
using (Draw.WithMatrix(sphereMatrix)) {
Draw.WireSphere(Vector3.zero, circleRadius, GizmoColor2);
}
break;
}
case MeshType.CustomMesh: {
if (mesh != null) {
using (Draw.WithMatrix(contourTransformationMatrix * Matrix4x4.Scale(Vector3.one * meshScale))) {
Draw.WireMesh(mesh, GizmoColor2);
}
}
break;
}
}
}
contourVertices.Dispose();
contours.Dispose();
}
protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) {
if (migrations.TryMigrateFromLegacyFormat(out var legacyVersion)) {
if (legacyVersion < 2) {
this.radiusExpansionMode = RadiusExpansionMode.DontExpand;
}
}
}
}
internal static class NavmeshCutJobsCached {
/// <summary>Cached delegate to a burst function pointer for running <see cref="NavmeshCutJobs.CalculateContour"/></summary>
public readonly static unsafe NavmeshCutJobs.CalculateContourDelegate CalculateContourBurst = BurstCompiler.CompileFunctionPointer<NavmeshCutJobs.CalculateContourDelegate>(NavmeshCutJobs.CalculateContour).Invoke;
}
[BurstCompile]
internal static class NavmeshCutJobs {
public unsafe delegate void CalculateContourDelegate(JobCalculateContour* job);
[BurstCompile(FloatPrecision.Standard, FloatMode.Fast)]
[AOT.MonoPInvokeCallback(typeof(CalculateContourDelegate))]
public static unsafe void CalculateContour (JobCalculateContour* job) {
job->Execute();
}
static readonly float4[] BoxCorners = new float4[] {
new float4(-0.5f, -0.5f, -0.5f, 1.0f),
new float4(+0.5f, -0.5f, -0.5f, 1.0f),
new float4(-0.5f, +0.5f, -0.5f, 1.0f),
new float4(+0.5f, +0.5f, -0.5f, 1.0f),
new float4(-0.5f, -0.5f, +0.5f, 1.0f),
new float4(+0.5f, -0.5f, +0.5f, 1.0f),
new float4(-0.5f, +0.5f, +0.5f, 1.0f),
new float4(+0.5f, +0.5f, +0.5f, 1.0f),
};
public struct JobCalculateContour {
public unsafe Unity.Collections.LowLevel.Unsafe.UnsafeList<float2>* outputVertices;
public unsafe Unity.Collections.LowLevel.Unsafe.UnsafeList<NavmeshCut.ContourBurst>* outputContours;
public unsafe Unity.Collections.LowLevel.Unsafe.UnsafeList<NavmeshCut.ContourBurst>* meshContours;
public unsafe Unity.Collections.LowLevel.Unsafe.UnsafeList<float3>* meshContourVertices;
public float4x4 matrix;
public float4x4 localToWorldMatrix;
public float radiusMargin;
public int circleResolution;
public float circleRadius;
public float2 rectangleSize;
public float height;
public float meshScale;
public NavmeshCut.MeshType meshType;
public unsafe void Execute () {
circleResolution = math.max(circleResolution, 3);
// Take rotation and scaling into account
var localToGraphMatrix = math.mul(this.matrix, this.localToWorldMatrix);
// radiusMargin should not be affected by the matrices at all. So we need to compensate for that.
var scaleFactorX = math.length(localToGraphMatrix.c0);
var scaleFactorY = math.length(localToGraphMatrix.c1);
var scaleFactorZ = math.length(localToGraphMatrix.c2);
switch (meshType) {
case NavmeshCut.MeshType.Rectangle: {
rectangleSize = new float2(math.abs(rectangleSize.x), math.abs(rectangleSize.y)) + math.rcp(new float2(scaleFactorX, scaleFactorZ))*radiusMargin*2;
outputVertices->Add(math.transform(localToGraphMatrix, new float3(-rectangleSize.x, 0, -rectangleSize.y)*0.5f).xz);
outputVertices->Add(math.transform(localToGraphMatrix, new float3(rectangleSize.x, 0, -rectangleSize.y)*0.5f).xz);
outputVertices->Add(math.transform(localToGraphMatrix, new float3(rectangleSize.x, 0, rectangleSize.y)*0.5f).xz);
outputVertices->Add(math.transform(localToGraphMatrix, new float3(-rectangleSize.x, 0, rectangleSize.y)*0.5f).xz);
// matrix.c3.y is just the y coordinate of the translation part of the matrix
var y0 = localToGraphMatrix.c3.y;
outputContours->Add(new NavmeshCut.ContourBurst {
// Make sure the height of the cut is also increased if the user scales the object along the y axis
ymin = y0 - this.height * 0.5f * scaleFactorY,
ymax = y0 + this.height * 0.5f * scaleFactorY,
startIndex = outputVertices->Length - 4,
endIndex = outputVertices->Length,
});
break;
}
case NavmeshCut.MeshType.Sphere: {
circleRadius = math.abs(circleRadius);
// For a sphere we ignore all rotation and non-uniform scaling.
// Instead we only use the translation part of the localToWorldMatrix
localToGraphMatrix = math.mul(this.matrix, float4x4.Translate(this.localToWorldMatrix.c3.xyz));
// Then we scale using a uniform scaling.
// This corresponds to what for example the unity sphere collider does when the object is scaled
// using a non-uniform scale.
var uniformScaleFactor = math.max(scaleFactorX, math.max(scaleFactorY, scaleFactorZ));
scaleFactorX = scaleFactorY = scaleFactorZ = uniformScaleFactor;
localToGraphMatrix = math.mul(localToGraphMatrix, float4x4.Scale(uniformScaleFactor));
var radius = circleRadius + radiusMargin/uniformScaleFactor;
radius = ApproximateCircleWithPolylineRadius(radius, circleResolution);
var step = (2*Mathf.PI)/circleResolution;
for (int i = 0; i < circleResolution; i++) {
math.sincos(i*step, out float sin, out float cos);
outputVertices->Add(math.transform(localToGraphMatrix, new float3(cos * radius, 0, sin*radius)).xz);
}
var y0 = localToGraphMatrix.c3.y;
outputContours->Add(new NavmeshCut.ContourBurst {
ymin = y0 - radius * uniformScaleFactor,
ymax = y0 + radius * uniformScaleFactor,
startIndex = outputVertices->Length - circleResolution,
endIndex = outputVertices->Length,
});
break;
}
case NavmeshCut.MeshType.Circle: {
circleRadius = math.abs(circleRadius);
var height = this.height + radiusMargin/scaleFactorY;
var radiusX = circleRadius + radiusMargin/scaleFactorX;
var radiusZ = circleRadius + radiusMargin/scaleFactorZ;
var step = (2*Mathf.PI)/circleResolution;
for (int i = 0; i < circleResolution; i++) {
math.sincos(i*step, out float sin, out float cos);
outputVertices->Add(math.transform(localToGraphMatrix, new float3(cos * radiusX, 0, sin*radiusZ)).xz);
}
var y0 = localToGraphMatrix.c3.y;
outputContours->Add(new NavmeshCut.ContourBurst {
ymin = y0 - height * 0.5f * scaleFactorY,
ymax = y0 + height * 0.5f * scaleFactorY,
startIndex = outputVertices->Length - circleResolution,
endIndex = outputVertices->Length,
});
break;
}
case NavmeshCut.MeshType.CustomMesh: {
if (meshContours != null && meshContourVertices != null && meshScale > 0) {
localToGraphMatrix = math.mul(localToGraphMatrix, float4x4.Scale(new float3(meshScale)));
var startIndex = outputVertices->Length;
for (int i = 0; i < meshContourVertices->Length; i++) {
outputVertices->Add(math.transform(localToGraphMatrix, meshContourVertices->ElementAt(i)).xz);
}
var y0 = localToGraphMatrix.c3.y;
for (int i = 0; i < meshContours->Length; i++) {
outputContours->Add(new NavmeshCut.ContourBurst {
ymin = y0 - this.height * 0.5f * scaleFactorY,
ymax = y0 + this.height * 0.5f * scaleFactorY,
startIndex = startIndex + meshContours->ElementAt(i).startIndex,
endIndex = startIndex + meshContours->ElementAt(i).endIndex,
});
}
}
break;
}
case NavmeshCut.MeshType.Box: {
// radiusMargin should not be affected by the matrices at all. So we need to compensate for that.
var boxSize = new float3(rectangleSize.x, height, rectangleSize.y) + math.rcp(new float3(scaleFactorX, scaleFactorY, scaleFactorZ))*radiusMargin*2;
localToGraphMatrix = math.mul(localToGraphMatrix, float4x4.Scale(boxSize));
NavmeshCutJobs.BoxConvexHullXZ(localToGraphMatrix, outputVertices, out int numPoints, out float ymin, out float ymax);
outputContours->Add(new NavmeshCut.ContourBurst {
ymin = ymin,
ymax = ymax,
startIndex = outputVertices->Length - numPoints,
endIndex = outputVertices->Length,
});
break;
}
case NavmeshCut.MeshType.Capsule: {
circleResolution = math.max(circleResolution, 6);
var r = this.circleRadius;
// Capsule
float h = this.height;
// When scaling along the Y axis we apply this as a height to the capsule instead of just doing a raw scale.
// This matches what the capsule collider in unity does.
h *= scaleFactorY;
localToGraphMatrix = math.mul(localToGraphMatrix, float4x4.Scale(new float3(1.0f, 1.0f/scaleFactorY, 1.0f)));
NavmeshCutJobs.CapsuleConvexHullXZ(localToGraphMatrix, outputVertices, h, r, radiusMargin, circleResolution, out int numPoints, out float ymin, out float ymax);
outputContours->Add(new NavmeshCut.ContourBurst {
ymin = ymin,
ymax = ymax,
startIndex = outputVertices->Length - numPoints,
endIndex = outputVertices->Length,
});
break;
}
}
for (int i = 0; i < outputContours->Length; i++) {
var contour = outputContours->ElementAt(i);
WindCounterClockwise(outputVertices, contour.startIndex, contour.endIndex);
}
}
/// <summary>Winds the vertices correctly. The particular winding doesn't matter, but all cuts must have the same winding order.</summary>
private unsafe void WindCounterClockwise (UnsafeList<float2>* vertices, int startIndex, int endIndex) {
int leftmostIndex = 0;
float2 leftmost = new float2(float.PositiveInfinity, float.PositiveInfinity);
for (int i = startIndex; i < endIndex; i++) {
float2 p = vertices->ElementAt(i);
if (p.x < leftmost.x || (p.x == leftmost.x && p.y < leftmost.y)) {
leftmostIndex = i;
leftmost = p;
}
}
var len = endIndex - startIndex;
var a = (*vertices)[((leftmostIndex-1 - startIndex + len) % len) + startIndex];
var b = leftmost;
var c = (*vertices)[((leftmostIndex+1 - startIndex) % len) + startIndex];
var clockwise = (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y) > 0;
if (clockwise) {
// Reverse vertices
for (int i = startIndex, j = endIndex - 1; i < j; i++, j--) {
var tmp = vertices->ElementAt(i);
vertices->ElementAt(i) = vertices->ElementAt(j);
vertices->ElementAt(j) = tmp;
}
}
}
}
/// <summary>
/// Adjust the radius so that the contour better approximates a circle.
/// Instead of all points laying exactly on the circle, which means all of the contour is inside the circle,
/// we change it so that half of the contour is inside and half is outside.
///
/// Returns the new radius
/// </summary>
static float ApproximateCircleWithPolylineRadius (float radius, int resolution) {
return radius / (1 - (1 - math.cos(math.PI / resolution)) * 0.5f);
}
public static unsafe void CapsuleConvexHullXZ (float4x4 matrix, UnsafeList<float2>* points, float height, float radius, float radiusMargin, int circleResolution, out int numPoints, out float minY, out float maxY) {
// Calculate the points of the capsule and project them to the XZ plane
height = math.max(height, radius*2);
// The contour is split into 2 semicircles.
var halfRes = circleResolution/2;
radius = ApproximateCircleWithPolylineRadius(radius, halfRes*2);
// Figure out the scale factors for the x/z dimensions (width) of the capsule.
// Pick the largest one in case it is non-uniformly scaled.
var scaleFactorX = math.length(matrix.c0.xyz);
var scaleFactorZ = math.length(matrix.c2.xyz);
radius *= math.max(scaleFactorX, scaleFactorZ);
var mainAxis = math.normalizesafe(matrix.c1.xyz);
var start = math.transform(matrix, new float3(0, -height*0.5f, 0)) + mainAxis * radius;
var end = math.transform(matrix, new float3(0, height*0.5f, 0)) - mainAxis * radius;
var startXZ = start.xz;
var endXZ = end.xz;
float2 axis1;
bool circle = false;
if (math.lengthsq(startXZ - endXZ) < 0.005f) {
// Circle
axis1 = new float2(1.0f, 0.0f);
circle = true;
} else {
axis1 = math.normalize(endXZ - startXZ);
}
var axis2 = new float2(-axis1.y, axis1.x);
// The additional margin is applied last. This will be in graph space.
radius += radiusMargin;
axis1 *= radius;
axis2 *= radius;
minY = math.min(start.y, end.y) - radius;
maxY = math.max(start.y, end.y) + radius;
var step = math.PI / halfRes;
if (circle) {
// Special case the circle to avoid multiple vertices being placed at the same spot
numPoints = halfRes*2;
var startIndex = points->Length;
points->Resize(points->Length + numPoints, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < halfRes; i++) {
var t = i * step;
math.sincos(t, out float sin, out float cos);
var dir = sin * axis1 + cos * axis2;
var p1 = startXZ - dir;
var p2 = endXZ + dir;
points->ElementAt(startIndex + i) = p1;
points->ElementAt(startIndex + i + halfRes) = p2;
}
} else {
// We split into two semicircles.
// We need to duplicate 2 points for this to work
numPoints = (halfRes+1)*2;
var startIndex = points->Length;
points->Resize(points->Length + numPoints, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < halfRes + 1; i++) {
var t = i * step;
math.sincos(t, out float sin, out float cos);
var dir = sin * axis1 + cos * axis2;
var p1 = startXZ - dir;
var p2 = endXZ + dir;
points->ElementAt(startIndex + i) = p1;
points->ElementAt(startIndex + i + halfRes + 1) = p2;
}
}
}
public static unsafe void BoxConvexHullXZ (float4x4 matrix, UnsafeList<float2>* points, out int numPoints, out float minY, out float maxY) {
// Calculate the 8 points of the box and project them to the XZ plane
minY = float.PositiveInfinity;
maxY = float.NegativeInfinity;
var startIndex = points->Length;
points->Resize(points->Length + BoxCorners.Length, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < BoxCorners.Length; i++) {
var p = math.mul(matrix, BoxCorners[i]);
minY = math.min(minY, p.y);
maxY = math.max(maxY, p.y);
points->ElementAt(startIndex + i) = p.xz;
}
numPoints = ConvexHull(points->Ptr + startIndex, BoxCorners.Length, 0.01f);
// Remove garbage at the end
points->Length = startIndex + numPoints;
}
struct AngleComparator : IComparer<float2> {
public float2 origin;
public int Compare (float2 lhs, float2 rhs) {
// cross product of (lhs - origin) and (rhs - origin)
var a = lhs - origin;
var b = rhs - origin;
var cross = a.x*b.y - a.y*b.x;
if (cross == 0) {
var la = math.lengthsq(a);
var lb = math.lengthsq(b);
return la < lb ? 1 : (lb < la ? -1 : 0);
} else {
return cross < 0 ? 1 : -1;
}
}
}
/// <summary>
/// Calculates the convex hull of a point set using the graham scan algorithm.
///
/// The `points` array will be modified to contain the convex hull.
/// The number of vertices on the hull is returned by this function.
///
/// Vertices on the hull closer than `vertexMergeDistance` will be merged together.
///
/// From KTH ACM Contest Template Library (2015 version)
/// </summary>
public static unsafe int ConvexHull (float2* points, int nPoints, float vertexMergeDistance) {
// Point with lowest x coordinate. Breaks ties along the y axis.
var startingIndex = 0;
for (int i = 0; i < nPoints; i++) {
if (points[i].x < points[startingIndex].x || (points[i].x == points[startingIndex].x && points[i].y < points[startingIndex].y)) {
startingIndex = i;
}
}
NativeSortExtension.Sort(points, nPoints, new AngleComparator {
origin = points[startingIndex]
});
var writeIndex = 0;
for (int i = 0; i < nPoints; i++) {
var p = points[i];
while (writeIndex >= 2) {
var a = points[writeIndex-1] - p;
var b = points[writeIndex-2] - p;
var cross = a.x*b.y - a.y*b.x;
if (cross >= 0 || math.lengthsq(a) < vertexMergeDistance) {
writeIndex--;
} else {
break;
}
}
// Important to make sure 2 identical points at the start don't end up in the output
if (writeIndex == 1 && math.lengthsq(points[writeIndex-1] - p) < vertexMergeDistance) {
writeIndex--;
}
points[writeIndex] = p;
writeIndex++;
}
return writeIndex;
}
}
}
|