-
Notifications
You must be signed in to change notification settings - Fork 1
/
NavMeshQuery.js
2990 lines (2610 loc) · 100 KB
/
NavMeshQuery.js
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
Recast4J Copyright (c) 2015 Piotr Piastucki piotr@jtilia.org
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
import NodePool from "./NodePool.js"
import NodeQueue from "./NodeQueue.js"
import DetourCommon from "./DetourCommon.js"
import FindNearestPolyResult from "./FindNearestPolyResult.js"
import NavMesh from "./NavMesh.js"
import Poly from "./Poly.js"
import ClosestPointOnPolyResult from "./ClosestPointOnPolyResult.js"
import QueryData from "./QueryData.js"
import Status from "./Status.js"
import Node from "./Node.js"
import UpdateSlicedPathResult from "./UpdateSlicedPathResult.js"
import FindPathResult from "./FindPathResult.js"
import FindLocalNeighbourhoodResult from "./FindLocalNeighbourhoodResult.js"
import GetPolyWallSegmentsResult from "./GetPolyWallSegmentsResult.js"
import StraightPathItem from "./StraightPathItem.js"
import MoveAlongSurfaceResult from "./MoveAlongSurfaceResult.js"
import RaycastHit from "./RaycastHit.js"
import IntersectResult from "./IntersectResult.js"
function or(v1, v2) {
var hi = 0x80000000;
var low = 0x7fffffff;
var hi1 = ~~(v1 / hi);
var hi2 = ~~(v2 / hi);
var low1 = v1 & low;
var low2 = v2 & low;
var h = hi1 | hi2;
var l = low1 | low2;
return h * hi + l;
}
class PortalResult {
left;
right;
fromType;
toType;
constructor(left, right, fromType, toType) {
this.left = left;
this.right = right;
this.fromType = fromType;
this.toType = toType;
}
}
function arraycopy(one, oneStart, two, twoStart, len) {
for (let i = 0; i < len; i++) {
two[twoStart + i] = one[oneStart + i];
}
}
class NavMeshQuery {
/**
* Use raycasts during pathfind to "shortcut" (raycast still consider costs)
* Options for NavMeshQuery::initSlicedFindPath and updateSlicedFindPath
*/
static DT_FINDPATH_ANY_ANGLE = 0x02;
/** Raycast should calculate movement cost aPoly the ray and fill RaycastHit::cost */
static DT_RAYCAST_USE_COSTS = 0x01;
/// Vertex flags returned by findStraightPath.
/** The vertex is the start position in the path. */
static DT_STRAIGHTPATH_START = 0x01;
/** The vertex is the end position in the path. */
static DT_STRAIGHTPATH_END = 0x02;
/** The vertex is the start of an off-mesh connection. */
static DT_STRAIGHTPATH_OFFMESH_CONNECTION = 0x04;
/// Options for findStraightPath.
static DT_STRAIGHTPATH_AREA_CROSSINGS = 0x01; ///< Add a vertex at every polygon edge crossing where area changes.
static DT_STRAIGHTPATH_ALL_CROSSINGS = 0x02; ///< Add a vertex at every polygon edge crossing.
static H_SCALE = 0.999; // Search heuristic scale.
m_nav;
m_nodePool;
m_tinyNodePool;
m_openList;
m_query; /// < Sliced query state.
constructor(nav) {
this.m_nav = nav;
this.m_nodePool = new NodePool();
this.m_tinyNodePool = new NodePool();
this.m_openList = new NodeQueue();
}
static FRand = class FRand {
constructor() {
return Math.random();
}
}
/**
* Returns random location on navmesh.
* Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
* @param filter The polygon filter to apply to the query.
* @param frand Function returning a random number [0..1).
* @return Random location
*/
findRandomPoint(filter, frand) {
// Randomly pick one tile. Assume that all tiles cover roughly the same area.
tile = null;
tsum = 0.0;
for (let i = 0; i < this.m_nav.getMaxTiles(); i++) {
let t = this.m_nav.getTile(i);
if (t == null || t.data == null || t.data.header == null)
continue;
// Choose random tile using reservoi sampling.
area = 1.0; // Could be tile area too.
tsum += area;
u = frand.frand();
if (u * tsum <= area)
tile = t;
}
if (tile == null)
return new FindRandomPointResult(Status.FAILURE, 0, null);
// Randomly pick one polygon weighted by polygon area.
let poly = null;
let polyRef = 0;
let base = this.m_nav.getPolyRefBase(tile);
areaSum = 0.0;
for (let i = 0; i < tile.data.header.polyCount; ++i) {
let p = tile.data.polys[i];
// Do not return off-mesh connection polygons.
if (p.getType() != Poly.DT_POLYTYPE_GROUND)
continue;
// Must pass filter
let ref = this.or(base, i);
if (!filter.passFilter(ref, tile, p))
continue;
// Calc area of the polygon.
polyArea = 0.0;
for (let j = 2; j < p.vertCount; ++j) {
let va = p.verts[0] * 3;
let vb = p.verts[j - 1] * 3;
let vc = p.verts[j] * 3;
polyArea += DetourCommon.triArea2D4(tile.data.verts, va, vb, vc);
}
// Choose random polygon weighted by area, using reservoi sampling.
areaSum += polyArea;
u = frand.frand();
if (u * areaSum <= polyArea) {
poly = p;
polyRef = ref;
}
}
if (poly == null)
return new FindRandomPointResult(Status.FAILURE, 0, null);
// Randomly pick poPoly on polygon.
let verts = new Array(3 * this.m_nav.getMaxVertsPerPoly());
let areas = new Array(this.m_nav.getMaxVertsPerPoly());
arraycopy(tile.data.verts, poly.verts[0] * 3, verts, 0, 3);
for (let j = 1; j < poly.vertCount; ++j) {
arraycopy(tile.data.verts, poly.verts[j] * 3, verts, j * 3, 3);
}
s = frand.frand();
t = frand.frand();
let pt = DetourCommon.randomPointInConvexPoly(verts, poly.vertCount, areas, s, t);
pt[1] = getPolyHeight(polyRef, pt);
return new FindRandomPointResult(Status.SUCCSESS, polyRef, pt);
}
/**
* Returns random location on navmesh within the reach of specified location.
* Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
* The location is not exactly constrained by the circle, but it limits the visited polygons.
*
* @param startRef The reference id of the polygon where the search starts.
* @param centerPos The center of the search circle. [(x, y, z)]
* @param maxRadius
* @param filter The polygon filter to apply to the query.
* @param frand Function returning a random number [0..1).
* @return Random location
*/
findRandomPointAroundCircle(startRef, centerPos, maxRadius,
filter, frand) {
// Validate input
if (startRef == 0 || !this.m_nav.isValidPolyRef(startRef))
throw new IllegalArgumentException("Invalid start ref");
let tileAndPoly = this.m_nav.getTileAndPolyByRefUnsafe(startRef);
let startTile = tileAndPoly[0];
let startPoly = tileAndPoly[1];
if (!filter.passFilter(startRef, startTile, startPoly))
throw new IllegalArgumentException("Invalid start");
m_nodePool = [];
this.m_openList = [];
let startNode = m_nodePool.getNode(startRef);
DetourCommon.vCopy(startNode.pos, centerPos);
startNode.pidx = 0;
startNode.cost = 0;
startNode.total = 0;
startNode.id = startRef;
startNode.flags = DT_NODE_OPEN;
this.m_openList.push(startNode);
radiusSqr = maxRadius * maxRadius;
areaSum = 0.0;
let randomTile = null;
let randomPoly = null;
let randomPolyRef = 0;
while (!this.m_openList.length == 0) {
let bestNode = this.m_openList.pop();
bestNode.flags &= ~DT_NODE_OPEN;
bestNode.flags |= DT_NODE_CLOSED;
// Get let and tile.
// The API input has been cheked already, skip checking internal data.
let bestRef = bestNode.id;
let bestTilePoly = this.m_nav.getTileAndPolyByRefUnsafe(bestRef);
let bestTile = bestTilePoly[0];
let bestPoly = bestTilePoly[1];
// Place random locations on on ground.
if (bestPoly.getType() == Poly.DT_POLYTYPE_GROUND) {
// Calc area of the polygon.
polyArea = 0.0;
for (let j = 2; j < bestPoly.vertCount; ++j) {
let va = bestPoly.verts[0] * 3;
let vb = bestPoly.verts[j - 1] * 3;
let vc = bestPoly.verts[j] * 3;
polyArea += DetourCommon.triArea2D4(bestTile.data.verts, va, vb, vc);
}
// Choose random polygon weighted by area, using reservoi sampling.
areaSum += polyArea;
u = frand.frand();
if (u * areaSum <= polyArea) {
randomTile = bestTile;
randomPoly = bestPoly;
randomPolyRef = bestRef;
}
}
// Get parent let and tile.
let parentRef = 0;
if (bestNode.pidx != 0)
parentRef = m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef != 0) {
let parentTilePoly = this.m_nav.getTileAndPolyByRefUnsafe(parentRef);
let parentTile = parentTilePoly[0];
let parentPoly = parentTilePoly[1];
}
for (let i = bestPoly.firstLink; i != NavMesh.DT_NULL_LINK; i = bestTile.links[i].next) {
let link = bestTile.links[i];
let neighbourRef = link.ref;
// Skip invalid neighbours and do not follow back to parent.
if (neighbourRef == 0 || neighbourRef == parentRef)
continue;
// Expand to neighbour
let neighbourTilePoly = this.m_nav.getTileAndPolyByRefUnsafe(neighbourRef);
let neighbourTile = neighbourTilePoly[0];
let neighbourPoly = neighbourTilePoly[1];
// Do not advance if the polygon is excluded by the filter.
if (!filter.passFilter(neighbourRef, neighbourTile, neighbourPoly))
continue;
// Find edge and calc distance to the edge.
let portalpoints = this.getPortalPoints7(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly,
neighbourTile, 0, 0);
let va = portalpoints.left;
let vb = portalpoints.right;
// If the circle is not touching the next polygon, skip it.
let distseg = DetourCommon.distancePtSegSqr2D3(centerPos, va, vb);
distSqr = distseg[0];
if (distSqr > radiusSqr)
continue;
let neighbourNode = m_nodePool.getNode(neighbourRef);
if ((neighbourNode.flags & Node.DT_NODE_CLOSED) != 0)
continue;
// Cost
if (neighbourNode.flags == 0)
neighbourNode.pos = DetourCommon.vLerp3(va, vb, 0.5);
total = bestNode.total + DetourCommon.vDist2(bestNode.pos, neighbourNode.pos);
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0 && total >= neighbourNode.total)
continue;
neighbourNode.id = neighbourRef;
neighbourNode.flags = (neighbourNode.flags & ~Node.DT_NODE_CLOSED);
neighbourNode.pidx = m_nodePool.getNodeIdx(bestNode);
neighbourNode.total = total;
if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0) {
this.m_openList.modify(neighbourNode);
} else {
neighbourNode.flags = Node.DT_NODE_OPEN;
this.m_openList.push(neighbourNode);
}
}
}
if (randomPoly == null)
return new FindRandomPointResult(Status.FAILURE, 0, null);
// Randomly pick poPoly on polygon.
let verts = new Array(3 * this.m_nav.getMaxVertsPerPoly());
let areas = new Array(this.m_nav.getMaxVertsPerPoly());
arraycopy(randomTile.data.verts, randomPoly.verts[0] * 3, verts, 0, 3);
for (let j = 1; j < randomPoly.vertCount; ++j) {
arraycopy(randomTile.data.verts, randomPoly.verts[j] * 3, verts, j * 3, 3);
}
s = frand.frand();
t = frand.frand();
let pt = DetourCommon.randomPointInConvexPoly(verts, randomPoly.vertCount, areas, s, t);
pt[1] = getPolyHeight(randomPolyRef, pt);
return new FindRandomPointResult(Status.SUCCSESS, randomPolyRef, pt);
}
//////////////////////////////////////////////////////////////////////////////////////////
/// @par
///
/// Uses the detail polygons to find the surface height. (Most accurate.)
///
/// @p pos does not have to be within the bounds of the polygon or navigation mesh.
///
/// See closestPointOnPolyBoundary() for a limited but faster option.
///
/// Finds the closest poPoly on the specified polygon.
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest
/// @param[out] posOverPoly
/// @returns The status flags for the query.
closestPointOnPoly(ref, pos) {
let tileAndPoly = this.m_nav.getTileAndPolyByRef(ref);
let tile = tileAndPoly[0];
let poly = tileAndPoly[1];
// Off-mesh connections don't have detail polygons.
if (poly.getType() == Poly.DT_POLYTYPE_OFFMESH_CONNECTION) {
let v0 = poly.verts[0] * 3;
let v1 = poly.verts[1] * 3;
let d0 = DetourCommon.vDist3(pos, tile.data.verts, v0);
let d1 = DetourCommon.vDist3(pos, tile.data.verts, v1);
let u = d0 / (d0 + d1);
let closest = DetourCommon.vLerp4(tile.data.verts, v0, v1, u);
return new ClosesPointOnPolyResult(false, closest);
}
// Clamp poPoly to be inside the polygon.
let verts = new Array(this.m_nav.getMaxVertsPerPoly() * 3);
let edged = new Array(this.m_nav.getMaxVertsPerPoly());
let edget = new Array(this.m_nav.getMaxVertsPerPoly());
let nv = poly.vertCount;
for (let i = 0; i < nv; ++i)
arraycopy(tile.data.verts, poly.verts[i] * 3, verts, i * 3, 3);
let posOverPoly = false;
let closest = new Array(3);
DetourCommon.vCopy(closest, pos);
if (!DetourCommon.distancePtPolyEdgesSqr(pos, verts, nv, edged, edget)) {
// PoPoly is outside the polygon, dtClamp to nearest edge.
let dmin = edged[0];
let imin = 0;
for (let i = 1; i < nv; ++i) {
if (edged[i] < dmin) {
dmin = edged[i];
imin = i;
}
}
let va = imin * 3;
let vb = ((imin + 1) % nv) * 3;
closest = DetourCommon.vLerp4(verts, va, vb, edget[imin]);
posOverPoly = false;
} else {
posOverPoly = true;
}
let ip = poly.index;
if (tile.data.detailMeshes != null && tile.data.detailMeshes.length > ip) {
let pd = tile.data.detailMeshes[ip];
// Find height at the location.
for (let j = 0; j < pd.triCount; ++j) {
let t = (pd.triBase + j) * 4;
let v = new Array(3); //Was new Array(3)[]
for (let k = 0; k < 3; ++k) {
if (tile.data.detailTris[t + k] < poly.vertCount) {
let index = poly.verts[tile.data.detailTris[t + k]] * 3;
v[k] = [tile.data.verts[index], tile.data.verts[index + 1],
tile.data.verts[index + 2]];
} else {
let index = (pd.vertBase + (tile.data.detailTris[t + k] - poly.vertCount)) * 3;
v[k] = [tile.data.detailVerts[index], tile.data.detailVerts[index + 1],
tile.data.detailVerts[index + 2]];
}
}
let heightResult = DetourCommon.closestHeightPointTriangle(closest, v[0], v[1], v[2]);
if (heightResult[0]) {
closest[1] = heightResult[1];
break;
}
}
}
return new ClosestPointOnPolyResult(posOverPoly, closest);
}
/// @par
///
/// Much faster than closestPointOnPoly().
///
/// If the provided position lies within the polygon's xz-bounds (above or below),
/// then @p pos and @p closest will be equal.
///
/// The height of @p closest will be the polygon boundary. The height detail is not used.
///
/// @p pos does not have to be within the bounds of the polybon or the navigation mesh.
///
/// Returns a poPoly on the boundary closest to the source poPoly if the source poPoly is outside the
/// polygon's xz-bounds.
/// @param[in] ref The reference id to the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest The closest point. [(x, y, z)]
/// @returns The status flags for the query.
closestPointOnPolyBoundary(ref, pos) {
let tileAndPoly = this.m_nav.getTileAndPolyByRef(ref);
let tile = tileAndPoly[0];
let poly = tileAndPoly[1];
// Collect vertices.
let verts = new Array(this.m_nav.getMaxVertsPerPoly() * 3);
let edged = new Array(this.m_nav.getMaxVertsPerPoly());
let edget = new Array(this.m_nav.getMaxVertsPerPoly());
let nv = poly.vertCount;
for (let i = 0; i < nv; ++i)
arraycopy(tile.data.verts, poly.verts[i] * 3, verts, i * 3, 3);
let closest;
if (DetourCommon.distancePtPolyEdgesSqr(pos, verts, nv, edged, edget)) {
closest = DetourCommon.vCopy_return(pos);
} else {
// PoPoly is outside the polygon, dtClamp to nearest edge.
let dmin = edged[0];
let imin = 0;
for (let i = 1; i < nv; ++i) {
if (edged[i] < dmin) {
dmin = edged[i];
imin = i;
}
}
let va = imin * 3;
let vb = ((imin + 1) % nv) * 3;
closest = DetourCommon.vLerp4(verts, va, vb, edget[imin]);
}
return closest;
}
/// @par
///
/// Will return #DT_FAILURE if the provided position is outside the xz-bounds
/// of the polygon.
///
/// Gets the height of the polygon at the provided position using the height detail. (Most accurate.)
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos A position within the xz-bounds of the polygon. [(x, y, z)]
/// @param[out] height The height at the surface of the polygon.
/// @returns The status flags for the query.
getPolyHeight(ref, pos) {
let tileAndPoly = this.m_nav.getTileAndPolyByRef(ref);
let tile = tileAndPoly[0];
let poly = tileAndPoly[1];
if (poly.getType() == Poly.DT_POLYTYPE_OFFMESH_CONNECTION) {
let i = poly.verts[0] * 3;
i = poly.verts[1] * 3;
letv1 = [tile.data.verts[i], tile.data.verts[i + 1], tile.data.verts[i + 2]];
d0 = DetourCommon.vDist2D(pos, v0);
d1 = DetourCommon.vDist2D(pos, v1);
u = d0 / (d0 + d1);
return v0[1] + (v1[1] - v0[1]) * u;
} else {
let ip = poly.index;
let pd = tile.data.detailMeshes[ip];
for (let j = 0; j < pd.triCount; ++j) {
let t = (pd.triBase + j) * 4;
let v = new Array(3);//new Array(3)[];
for (let k = 0; k < 3; ++k) {
if (tile.data.detailTris[t + k] < poly.vertCount) {
let index = poly.verts[tile.data.detailTris[t + k]] * 3;
v[k] = [tile.data.verts[index], tile.data.verts[index + 1],
tile.data.verts[index + 2]];
} else {
let index = (pd.vertBase + (tile.data.detailTris[t + k] - poly.vertCount)) * 3;
v[k] = [tile.data.detailVerts[index], tile.data.detailVerts[index + 1],
tile.data.detailVerts[index + 2]];
}
}
let heightResult = DetourCommon.closestHeightPointTriangle(pos, v[0], v[1], v[2]);
if (heightResult[0]) {
return heightResult[1];
}
}
}
throw new IllegalArgumentException("Invalid ref " + ref + " pos " + Arrays.toString(pos));
}
/// @par
///
/// @note If the search box does not intersect any polygons the search will
/// return #DT_SUCCESS, but @p nearestRef will be zero. So if in doubt, check
/// @p nearestRef before using @p nearestPt.
///
/// @}
/// @name Local Query Functions
///@{
/// Finds the polygon nearest to the specified center point.
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] extents The search distance aPoly each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @returns The status flags for the query.
findNearestPoly(center, extents, filter) {
let nearestPt = null;
// Get nearby polygons from proximity grid.
let polys = this.queryPolygons(center, extents, filter);
// Find nearest polygon amongst the nearby polygons.
let nearest = 0;
let nearestDistanceSqr = Number.MAX_VALUE;
for (let i = 0; i < polys.length; ++i) {
let ref = polys[i];
let closest = this.closestPointOnPoly(ref, center);
let posOverPoly = closest.isPosOverPoly();
let closestPtPoly = closest.getClosest();
// If a poPoly is directly over a polygon and closer than
// climb height, favor that instead of straight line nearest point.
let d = 0;
let diff = DetourCommon.vSub(center, closestPtPoly);
if (posOverPoly) {
let tilaAndPoly = this.m_nav.getTileAndPolyByRefUnsafe(polys[i]);
let tile = tilaAndPoly[0];
d = Math.abs(diff[1]) - tile.data.header.walkableClimb;
d = d > 0 ? d * d : 0;
} else {
d = DetourCommon.vLenSqr(diff);
}
if (d < nearestDistanceSqr) {
nearestPt = closestPtPoly;
nearestDistanceSqr = d;
nearest = ref;
}
}
return new FindNearestPolyResult(nearest, nearestPt);
}
and(v1, v2) {
var hi = 0x80000000;
var low = 0x7fffffff;
var hi1 = ~~(v1 / hi);
var hi2 = ~~(v2 / hi);
var low1 = v1 & low;
var low2 = v2 & low;
var h = hi1 & hi2;
var l = low1 & low2;
return h * hi + l;
}
or(v1, v2) {
var hi = 0x80000000;
var low = 0x7fffffff;
var hi1 = ~~(v1 / hi);
var hi2 = ~~(v2 / hi);
var low1 = v1 & low;
var low2 = v2 & low;
var h = hi1 | hi2;
var l = low1 | low2;
return h * hi + l;
}
// FIXME: (PP) duplicate?
queryPolygonsInTile(tile, qmin, qmax, filter) {
let polys = [];
if (tile.data.bvTree != null) {
let nodeIndex = 0;
let tbmin = tile.data.header.bmin;
let tbmax = tile.data.header.bmax;
let qfac = tile.data.header.bvQuantFactor;
// Calculate quantized box
let bmin = new Array(3);
let bmax = new Array(3);
// dtClamp query box to world box.
let minx = DetourCommon.clamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
let miny = DetourCommon.clamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
let minz = DetourCommon.clamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
let maxx = DetourCommon.clamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
let maxy = DetourCommon.clamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
let maxz = DetourCommon.clamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
// Quantize
bmin[0] = this.and(Math.floor((qfac * minx)), 0xfffe);
bmin[1] = this.and(Math.floor((qfac * miny)), 0xfffe);
bmin[2] = this.and(Math.floor((qfac * minz)), 0xfffe);
bmax[0] = this.or(Math.floor((qfac * maxx + 1)), 1);
bmax[1] = this.or(Math.floor((qfac * maxy + 1)), 1);
bmax[2] = this.or(Math.floor((qfac * maxz + 1)), 1);
// Traverse tree
let base = this.m_nav.getPolyRefBase(tile);
let end = tile.data.header.bvNodeCount;
while (nodeIndex < end) {
let node = tile.data.bvTree[nodeIndex];
let overlap = DetourCommon.overlapQuantBounds(bmin, bmax, node.bmin, node.bmax);
let isLeafNode = node.i >= 0;
if (isLeafNode && overlap) {
let ref = this.or(base, node.i);
if (filter.passFilter(ref, tile, tile.data.polys[node.i])) {
polys.push(ref);
}
}
if (overlap || isLeafNode)
nodeIndex++;
else {
let escapeIndex = -node.i;
nodeIndex += escapeIndex;
}
}
return polys;
} else {
let bmin = new Array(3);
let bmax = new Array(3);
let base = this.m_nav.getPolyRefBase(tile);
for (let i = 0; i < tile.data.header.polyCount; ++i) {
let p = tile.data.polys[i];
// Do not return off-mesh connection polygons.
if (p.getType() == Poly.DT_POLYTYPE_OFFMESH_CONNECTION)
continue;
let ref = base | i;
if (!filter.passFilter(ref, tile, p))
continue;
// Calc polygon bounds.
let v = p.verts[0] * 3;
DetourCommon.vCopy(bmin, tile.data.verts, v);
DetourCommon.vCopy(bmax, tile.data.verts, v);
for (let j = 1; j < p.vertCount; ++j) {
v = p.verts[j] * 3;
DetourCommon.vMin(bmin, tile.data.verts, v);
DetourCommon.vMax(bmax, tile.data.verts, v);
}
if (overlapBounds(qmin, qmax, bmin, bmax)) {
polys.push(ref);
}
}
return polys;
}
}
/**
* Finds polygons that overlap the search box.
*
* If no polygons are found, the function will return with a polyCount of zero.
*
* @param center
* The center of the search box. [(x, y, z)]
* @param extents
* The search distance aPoly each axis. [(x, y, z)]
* @param (filter)
* The polygon filter to apply to the query.
* @return The reference ids of the polygons that overlap the query box.
*/
queryPolygons(center, extents, filter) {
let bmin = DetourCommon.vSub(center, extents);
let bmax = DetourCommon.vAdd(center, extents);
// Find tiles the query touches.
let minxy = this.m_nav.calcTileLoc(bmin);
let minx = minxy[0];
let miny = minxy[1];
let maxxy = this.m_nav.calcTileLoc(bmax);
let maxx = maxxy[0];
let maxy = maxxy[1];
let polys = [];
for (let y = miny; y <= maxy; ++y) {
for (let x = minx; x <= maxx; ++x) {
let neis = this.m_nav.getTilesAt(x, y);
for (let j = 0; j < neis.length; ++j) {
let polysInTile = this.queryPolygonsInTile(neis[j], bmin, bmax, filter);
polys.push(...polysInTile);
}
}
}
return polys;
}
/**
* Finds a path from the start polygon to the end polygon.
*
* If the end polygon cannot be reached through the navigation graph, the last polygon in the path will be the
* nearest the end polygon.
*
* The start and end positions are used to calculate traversal costs. (The y-values impact the result.)
*
* @param startRef
* The refrence id of the start polygon.
* @param endRef
* The reference id of the end polygon.
* @param startPos
* A position within the start polygon. [(x, y, z)]
* @param endPos
* A position within the end polygon. [(x, y, z)]
* @param filter
* The polygon filter to apply to the query.
* @return Found path
*/
findPath(startRef, endRef, startPos, endPos,
filter) {
if (startRef == 0 || endRef == 0)
throw new IllegalArgumentException("Start or end ref = 0");
// Validate input
if (!this.m_nav.isValidPolyRef(startRef) || !this.m_nav.isValidPolyRef(endRef))
throw new IllegalArgumentException("Invalid start or end ref");
if (startRef == endRef) {
let path = new Array(1);
path.push(startRef);
return new FindPathResult(Status.SUCCSESS, path);
}
this.m_nodePool = [];
this.m_openList = [];
let startNode = this.m_nodePool.getNode(startRef);
DetourCommon.vCopy(startNode.pos, startPos);
startNode.pidx = 0;
startNode.cost = 0;
startNode.total = DetourCommon.vDist2(startPos, endPos) * NavMeshQuery.H_SCALE;
startNode.id = startRef;
startNode.flags = Node.DT_NODE_OPEN;
this.m_openList.push(startNode);
let lastBestNode = startNode;
lastBestNodeCost = startNode.total;
let status = Status.SUCCSESS;
while (!this.m_openList.length == 0) {
// Remove node from open list and put it in closed list.
let bestNode = this.m_openList.pop();
bestNode.flags &= ~Node.DT_NODE_OPEN;
bestNode.flags |= Node.DT_NODE_CLOSED;
// Reached the goal, stop searching.
if (bestNode.id == endRef) {
lastBestNode = bestNode;
break;
}
// Get current let and tile.
// The API input has been cheked already, skip checking internal data.
let bestRef = bestNode.id;
let tileAndPoly = this.m_nav.getTileAndPolyByRefUnsafe(bestRef);
let bestTile = tileAndPoly[0];
let bestPoly = tileAndPoly[1];
// Get parent let and tile.
let parentRef = 0;
let parentTile = null;
let parentPoly = null;
if (bestNode.pidx != 0)
parentRef = this.m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef != 0) {
tileAndPoly = this.m_nav.getTileAndPolyByRefUnsafe(parentRef);
parentTile = tileAndPoly[0];
parentPoly = tileAndPoly[1];
}
for (let i = bestPoly.firstLink; i != NavMesh.DT_NULL_LINK; i = bestTile.links[i].next) {
let neighbourRef = bestTile.links[i].ref;
// Skip invalid ids and do not expand back to where we came from.
if (neighbourRef == 0 || neighbourRef == parentRef)
continue;
// Get neighbour let and tile.
// The API input has been cheked already, skip checking internal data.
tileAndPoly = this.m_nav.getTileAndPolyByRefUnsafe(neighbourRef);
let neighbourTile = tileAndPoly[0];
let neighbourPoly = tileAndPoly[1];
if (!filter.passFilter(neighbourRef, neighbourTile, neighbourPoly))
continue;
// deal explicitly with crossing tile boundaries
let crossSide = 0;
if (bestTile.links[i].side != 0xff)
crossSide = bestTile.links[i].side >> 1;
// get the node
let neighbourNode = this.m_nodePool.getNode(neighbourRef, crossSide);
// If the node is visited the first time, calculate node position.
if (neighbourNode.flags == 0) {
neighbourNode.pos = this.getEdgeMidPoint6(bestRef, bestPoly, bestTile, neighbourRef,
neighbourPoly, neighbourTile);
}
// Calculate cost and heuristic.
cost = 0;
heuristic = 0;
// Special case for last node.
if (neighbourRef == endRef) {
// Cost
curCost = filter.getCost(bestNode.pos, neighbourNode.pos, parentRef, parentTile, parentPoly,
bestRef, bestTile, bestPoly, neighbourRef, neighbourTile, neighbourPoly);
let endCost = filter.getCost(neighbourNode.pos, endPos, bestRef, bestTile, bestPoly, neighbourRef,
neighbourTile, neighbourPoly, 0, null, null);
cost = bestNode.cost + curCost + endCost;
heuristic = 0;
} else {
// Cost
curCost = filter.getCost(bestNode.pos, neighbourNode.pos, parentRef, parentTile, parentPoly,
bestRef, bestTile, bestPoly, neighbourRef, neighbourTile, neighbourPoly);
cost = bestNode.cost + curCost;
heuristic = DetourCommon.vDist2(neighbourNode.pos, endPos) * NavMeshQuery.H_SCALE;
}
total = cost + heuristic;
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0 && total >= neighbourNode.total)
continue;
// The node is already visited and process, and the new result is worse, skip.
if ((neighbourNode.flags & Node.DT_NODE_CLOSED) != 0 && total >= neighbourNode.total)
continue;
// Add or update the node.
neighbourNode.pidx = this.m_nodePool.getNodeIdx(bestNode);
neighbourNode.id = neighbourRef;
neighbourNode.flags = (neighbourNode.flags & ~Node.DT_NODE_CLOSED);
neighbourNode.cost = cost;
neighbourNode.total = total;
if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0) {
// Already in open, update node location.
this.m_openList.modify(neighbourNode);
} else {
// Put the node in open list.
neighbourNode.flags |= Node.DT_NODE_OPEN;
this.m_openList.push(neighbourNode);
}
// Update nearest node to target so far.
if (heuristic < lastBestNodeCost) {
lastBestNodeCost = heuristic;
lastBestNode = neighbourNode;
}
}
}
let path = getPathToNode(lastBestNode);
if (lastBestNode.id != endRef)
status = Status.PARTIAL_RESULT;
return new FindPathResult(status, path);
}
/**
* Intializes a sliced path query.
*
* Common use case: -# Call initSlicedFindPath() to initialize the sliced path query. -# Call updateSlicedFindPath()
* until it returns compPolye. -# Call finalizeSlicedFindPath() to get the path.
*
* @param startRef
* The reference id of the start polygon.
* @param endRef
* The reference id of the end polygon.
* @param startPos
* A position within the start polygon. [(x, y, z)]
* @param endPos
* A position within the end polygon. [(x, y, z)]
* @param filter
* The polygon filter to apply to the query.
* @param options
* query options (see: #FindPathOptions)
* @return
*/
initSlicedFindPath(startRef, endRef, startPos, endPos, filter,
options) {
// Init path state.
this.m_query = new QueryData();
this.m_query.status = Status.FAILURE;
this.m_query.startRef = startRef;
this.m_query.endRef = endRef;
DetourCommon.vCopy(this.m_query.startPos, startPos);
DetourCommon.vCopy(this.m_query.endPos, endPos);
this.m_query.filter = filter;
this.m_query.options = options;
this.m_query.raycastLimitSqr = Number.MAX_VALUE;
if (startRef == 0 || endRef == 0)
throw new IllegalArgumentException("Start or end ref = 0");
// Validate input
if (!this.m_nav.isValidPolyRef(startRef) || !this.m_nav.isValidPolyRef(endRef))
throw new IllegalArgumentException("Invalid start or end ref");
// trade quality with performance?
if ((options & NavMeshQuery.DT_FINDPATH_ANY_ANGLE) != 0) {
// limiting to several times the character radius yields nice results. It is not sensitive
// so it is enough to compute it from the first tile.
let tile = this.m_nav.getTileByRef(startRef);
agentRadius = tile.data.header.walkableRadius;
this.m_query.raycastLimitSqr = DetourCommon.sqr(agentRadius * NavMesh.DT_RAY_CAST_LIMIT_PROPORTIONS);
}
if (startRef == endRef) {
this.m_query.status = Status.SUCCSESS;
return Status.SUCCSESS;
}
this.m_nodePool.clear();
this.m_openList.clear();
let startNode = this.m_nodePool.getNode(startRef);
DetourCommon.vCopy(startNode.pos, startPos);
startNode.pidx = 0;
startNode.cost = 0;
startNode.total = DetourCommon.vDist2(startPos, endPos) * NavMeshQuery.H_SCALE;
startNode.id = startRef;
startNode.flags = Node.DT_NODE_OPEN;
this.m_openList.push(startNode);
this.m_query.status = Status.IN_PROGRESS;
this.m_query.lastBestNode = startNode;
this.m_query.lastBestNodeCost = startNode.total;
return this.m_query.status;
}
/**
* Updates an in-progress sliced path query.
*
* @param maxIter
* The maximum number of iterations to perform.
* @return The status flags for the query.
*/
updateSlicedFindPath(maxIter) {
if (this.m_query.status != Status.IN_PROGRESS)