Debian Codegraph @

Detour/Source/DetourNavMeshQuery.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //
2 // Copyright (c) 2009-2010 Mikko Mononen [email protected]
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty. In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 // claim that you wrote the original software. If you use this software
12 // in a product, an acknowledgment in the product documentation would be
13 // appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 // misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18
19 #include <float.h>
20 #include <string.h>
21 #include "DetourNavMeshQuery.h"
22 #include "DetourNavMesh.h"
23 #include "DetourNode.h"
24 #include "DetourCommon.h"
25 #include "DetourMath.h"
26 #include "DetourAlloc.h"
27 #include "DetourAssert.h"
28 #include <new>
29
30 /// @class dtQueryFilter
31 ///
32 /// <b>The Default Implementation</b>
33 ///
34 /// At construction: All area costs default to 1.0. All flags are included
35 /// and none are excluded.
36 ///
37 /// If a polygon has both an include and an exclude flag, it will be excluded.
38 ///
39 /// The way filtering works, a navigation mesh polygon must have at least one flag
40 /// set to ever be considered by a query. So a polygon with no flags will never
41 /// be considered.
42 ///
43 /// Setting the include flags to 0 will result in all polygons being excluded.
44 ///
45 /// <b>Custom Implementations</b>
46 ///
47 /// DT_VIRTUAL_QUERYFILTER must be defined in order to extend this class.
48 ///
49 /// Implement a custom query filter by overriding the virtual passFilter()
50 /// and getCost() functions. If this is done, both functions should be as
51 /// fast as possible. Use cached local copies of data rather than accessing
52 /// your own objects where possible.
53 ///
54 /// Custom implementations do not need to adhere to the flags or cost logic
55 /// used by the default implementation.
56 ///
57 /// In order for A* searches to work properly, the cost should be proportional to
58 /// the travel distance. Implementing a cost modifier less than 1.0 is likely
59 /// to lead to problems during pathfinding.
60 ///
61 /// @see dtNavMeshQuery
62
63 dtQueryFilter::dtQueryFilter() :
64 m_includeFlags(0xffff),
65 m_excludeFlags(0)
66 {
67 for (int i = 0; i < DT_MAX_AREAS; ++i)
68 m_areaCost[i] = 1.0f;
69 }
70
71 #ifdef DT_VIRTUAL_QUERYFILTER
72 bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/,
73 const dtMeshTile* /*tile*/,
74 const dtPoly* poly) const
75 {
76 return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0;
77 }
78
79 float dtQueryFilter::getCost(const float* pa, const float* pb,
80 const dtPolyRef /*prevRef*/, const dtMeshTile* /*prevTile*/, const dtPoly* /*prevPoly*/,
81 const dtPolyRef /*curRef*/, const dtMeshTile* /*curTile*/, const dtPoly* curPoly,
82 const dtPolyRef /*nextRef*/, const dtMeshTile* /*nextTile*/, const dtPoly* /*nextPoly*/) const
83 {
84 return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()];
85 }
86 #else
87 inline bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/,
88 const dtMeshTile* /*tile*/,
89 const dtPoly* poly) const
90 {
91 return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0;
92 }
93
94 inline float dtQueryFilter::getCost(const float* pa, const float* pb,
95 const dtPolyRef /*prevRef*/, const dtMeshTile* /*prevTile*/, const dtPoly* /*prevPoly*/,
96 const dtPolyRef /*curRef*/, const dtMeshTile* /*curTile*/, const dtPoly* curPoly,
97 const dtPolyRef /*nextRef*/, const dtMeshTile* /*nextTile*/, const dtPoly* /*nextPoly*/) const
98 {
99 return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()];
100 }
101 #endif
102
103 static const float H_SCALE = 0.999f; // Search heuristic scale.
104
105
106 dtNavMeshQuery* dtAllocNavMeshQuery()
107 {
108 void* mem = dtAlloc(sizeof(dtNavMeshQuery), DT_ALLOC_PERM);
109 if (!mem) return 0;
110 return new(mem) dtNavMeshQuery;
111 }
112
113 void dtFreeNavMeshQuery(dtNavMeshQuery* navmesh)
114 {
115 if (!navmesh) return;
116 navmesh->~dtNavMeshQuery();
117 dtFree(navmesh);
118 }
119
120 dtPolyQuery::~dtPolyQuery()
121 {
122 // Defined out of line to fix the weak v-tables warning
123 }
124
125 //////////////////////////////////////////////////////////////////////////////////////////
126
127 /// @class dtNavMeshQuery
128 ///
129 /// For methods that support undersized buffers, if the buffer is too small
130 /// to hold the entire result set the return status of the method will include
131 /// the #DT_BUFFER_TOO_SMALL flag.
132 ///
133 /// Constant member functions can be used by multiple clients without side
134 /// effects. (E.g. No change to the closed list. No impact on an in-progress
135 /// sliced path query. Etc.)
136 ///
137 /// Walls and portals: A @e wall is a polygon segment that is
138 /// considered impassable. A @e portal is a passable segment between polygons.
139 /// A portal may be treated as a wall based on the dtQueryFilter used for a query.
140 ///
141 /// @see dtNavMesh, dtQueryFilter, #dtAllocNavMeshQuery(), #dtAllocNavMeshQuery()
142
143 dtNavMeshQuery::dtNavMeshQuery() :
144 m_nav(0),
145 m_tinyNodePool(0),
146 m_nodePool(0),
147 m_openList(0)
148 {
149 memset(&m_query, 0, sizeof(dtQueryData));
150 }
151
152 dtNavMeshQuery::~dtNavMeshQuery()
153 {
154 if (m_tinyNodePool)
155 m_tinyNodePool->~dtNodePool();
156 if (m_nodePool)
157 m_nodePool->~dtNodePool();
158 if (m_openList)
159 m_openList->~dtNodeQueue();
160 dtFree(m_tinyNodePool);
161 dtFree(m_nodePool);
162 dtFree(m_openList);
163 }
164
165 /// @par
166 ///
167 /// Must be the first function called after construction, before other
168 /// functions are used.
169 ///
170 /// This function can be used multiple times.
171 dtStatus dtNavMeshQuery::init(const dtNavMesh* nav, const int maxNodes)
172 {
173 if (maxNodes > DT_NULL_IDX || maxNodes > (1 << DT_NODE_PARENT_BITS) - 1)
174 return DT_FAILURE | DT_INVALID_PARAM;
175
176 m_nav = nav;
177
178 if (!m_nodePool || m_nodePool->getMaxNodes() < maxNodes)
179 {
180 if (m_nodePool)
181 {
182 m_nodePool->~dtNodePool();
183 dtFree(m_nodePool);
184 m_nodePool = 0;
185 }
186 m_nodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(maxNodes, dtNextPow2(maxNodes/4));
187 if (!m_nodePool)
188 return DT_FAILURE | DT_OUT_OF_MEMORY;
189 }
190 else
191 {
192 m_nodePool->clear();
193 }
194
195 if (!m_tinyNodePool)
196 {
197 m_tinyNodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(64, 32);
198 if (!m_tinyNodePool)
199 return DT_FAILURE | DT_OUT_OF_MEMORY;
200 }
201 else
202 {
203 m_tinyNodePool->clear();
204 }
205
206 if (!m_openList || m_openList->getCapacity() < maxNodes)
207 {
208 if (m_openList)
209 {
210 m_openList->~dtNodeQueue();
211 dtFree(m_openList);
212 m_openList = 0;
213 }
214 m_openList = new (dtAlloc(sizeof(dtNodeQueue), DT_ALLOC_PERM)) dtNodeQueue(maxNodes);
215 if (!m_openList)
216 return DT_FAILURE | DT_OUT_OF_MEMORY;
217 }
218 else
219 {
220 m_openList->clear();
221 }
222
223 return DT_SUCCESS;
224 }
225
226 dtStatus dtNavMeshQuery::findRandomPoint(const dtQueryFilter* filter, float (*frand)(),
227 dtPolyRef* randomRef, float* randomPt) const
228 {
229 dtAssert(m_nav);
230
231 if (!filter || !frand || !randomRef || !randomPt)
232 return DT_FAILURE | DT_INVALID_PARAM;
233
234 // Randomly pick one tile. Assume that all tiles cover roughly the same area.
235 const dtMeshTile* tile = 0;
236 float tsum = 0.0f;
237 for (int i = 0; i < m_nav->getMaxTiles(); i++)
238 {
239 const dtMeshTile* t = m_nav->getTile(i);
240 if (!t || !t->header) continue;
241
242 // Choose random tile using reservoi sampling.
243 const float area = 1.0f; // Could be tile area too.
244 tsum += area;
245 const float u = frand();
246 if (u*tsum <= area)
247 tile = t;
248 }
249 if (!tile)
250 return DT_FAILURE;
251
252 // Randomly pick one polygon weighted by polygon area.
253 const dtPoly* poly = 0;
254 dtPolyRef polyRef = 0;
255 const dtPolyRef base = m_nav->getPolyRefBase(tile);
256
257 float areaSum = 0.0f;
258 for (int i = 0; i < tile->header->polyCount; ++i)
259 {
260 const dtPoly* p = &tile->polys[i];
261 // Do not return off-mesh connection polygons.
262 if (p->getType() != DT_POLYTYPE_GROUND)
263 continue;
264 // Must pass filter
265 const dtPolyRef ref = base | (dtPolyRef)i;
266 if (!filter->passFilter(ref, tile, p))
267 continue;
268
269 // Calc area of the polygon.
270 float polyArea = 0.0f;
271 for (int j = 2; j < p->vertCount; ++j)
272 {
273 const float* va = &tile->verts[p->verts[0]*3];
274 const float* vb = &tile->verts[p->verts[j-1]*3];
275 const float* vc = &tile->verts[p->verts[j]*3];
276 polyArea += dtTriArea2D(va,vb,vc);
277 }
278
279 // Choose random polygon weighted by area, using reservoi sampling.
280 areaSum += polyArea;
281 const float u = frand();
282 if (u*areaSum <= polyArea)
283 {
284 poly = p;
285 polyRef = ref;
286 }
287 }
288
289 if (!poly)
290 return DT_FAILURE;
291
292 // Randomly pick point on polygon.
293 const float* v = &tile->verts[poly->verts[0]*3];
294 float verts[3*DT_VERTS_PER_POLYGON];
295 float areas[DT_VERTS_PER_POLYGON];
296 dtVcopy(&verts[0*3],v);
297 for (int j = 1; j < poly->vertCount; ++j)
298 {
299 v = &tile->verts[poly->verts[j]*3];
300 dtVcopy(&verts[j*3],v);
301 }
302
303 const float s = frand();
304 const float t = frand();
305
306 float pt[3];
307 dtRandomPointInConvexPoly(verts, poly->vertCount, areas, s, t, pt);
308
309 closestPointOnPoly(polyRef, pt, pt, NULL);
310
311 dtVcopy(randomPt, pt);
312 *randomRef = polyRef;
313
314 return DT_SUCCESS;
315 }
316
317 dtStatus dtNavMeshQuery::findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius,
318 const dtQueryFilter* filter, float (*frand)(),
319 dtPolyRef* randomRef, float* randomPt) const
320 {
321 dtAssert(m_nav);
322 dtAssert(m_nodePool);
323 dtAssert(m_openList);
324
325 // Validate input
326 if (!m_nav->isValidPolyRef(startRef) ||
327 !centerPos || !dtVisfinite(centerPos) ||
328 maxRadius < 0 || !dtMathIsfinite(maxRadius) ||
329 !filter || !frand || !randomRef || !randomPt)
330 {
331 return DT_FAILURE | DT_INVALID_PARAM;
332 }
333
334 const dtMeshTile* startTile = 0;
335 const dtPoly* startPoly = 0;
336 m_nav->getTileAndPolyByRefUnsafe(startRef, &startTile, &startPoly);
337 if (!filter->passFilter(startRef, startTile, startPoly))
338 return DT_FAILURE | DT_INVALID_PARAM;
339
340 m_nodePool->clear();
341 m_openList->clear();
342
343 dtNode* startNode = m_nodePool->getNode(startRef);
344 dtVcopy(startNode->pos, centerPos);
345 startNode->pidx = 0;
346 startNode->cost = 0;
347 startNode->total = 0;
348 startNode->id = startRef;
349 startNode->flags = DT_NODE_OPEN;
350 m_openList->push(startNode);
351
352 dtStatus status = DT_SUCCESS;
353
354 const float radiusSqr = dtSqr(maxRadius);
355 float areaSum = 0.0f;
356
357 const dtMeshTile* randomTile = 0;
358 const dtPoly* randomPoly = 0;
359 dtPolyRef randomPolyRef = 0;
360
361 while (!m_openList->empty())
362 {
363 dtNode* bestNode = m_openList->pop();
364 bestNode->flags &= ~DT_NODE_OPEN;
365 bestNode->flags |= DT_NODE_CLOSED;
366
367 // Get poly and tile.
368 // The API input has been cheked already, skip checking internal data.
369 const dtPolyRef bestRef = bestNode->id;
370 const dtMeshTile* bestTile = 0;
371 const dtPoly* bestPoly = 0;
372 m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
373
374 // Place random locations on on ground.
375 if (bestPoly->getType() == DT_POLYTYPE_GROUND)
376 {
377 // Calc area of the polygon.
378 float polyArea = 0.0f;
379 for (int j = 2; j < bestPoly->vertCount; ++j)
380 {
381 const float* va = &bestTile->verts[bestPoly->verts[0]*3];
382 const float* vb = &bestTile->verts[bestPoly->verts[j-1]*3];
383 const float* vc = &bestTile->verts[bestPoly->verts[j]*3];
384 polyArea += dtTriArea2D(va,vb,vc);
385 }
386 // Choose random polygon weighted by area, using reservoi sampling.
387 areaSum += polyArea;
388 const float u = frand();
389 if (u*areaSum <= polyArea)
390 {
391 randomTile = bestTile;
392 randomPoly = bestPoly;
393 randomPolyRef = bestRef;
394 }
395 }
396
397
398 // Get parent poly and tile.
399 dtPolyRef parentRef = 0;
400 const dtMeshTile* parentTile = 0;
401 const dtPoly* parentPoly = 0;
402 if (bestNode->pidx)
403 parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
404 if (parentRef)
405 m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
406
407 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
408 {
409 const dtLink* link = &bestTile->links[i];
410 dtPolyRef neighbourRef = link->ref;
411 // Skip invalid neighbours and do not follow back to parent.
412 if (!neighbourRef || neighbourRef == parentRef)
413 continue;
414
415 // Expand to neighbour
416 const dtMeshTile* neighbourTile = 0;
417 const dtPoly* neighbourPoly = 0;
418 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
419
420 // Do not advance if the polygon is excluded by the filter.
421 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
422 continue;
423
424 // Find edge and calc distance to the edge.
425 float va[3], vb[3];
426 if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
427 continue;
428
429 // If the circle is not touching the next polygon, skip it.
430 float tseg;
431 float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
432 if (distSqr > radiusSqr)
433 continue;
434
435 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
436 if (!neighbourNode)
437 {
438 status |= DT_OUT_OF_NODES;
439 continue;
440 }
441
442 if (neighbourNode->flags & DT_NODE_CLOSED)
443 continue;
444
445 // Cost
446 if (neighbourNode->flags == 0)
447 dtVlerp(neighbourNode->pos, va, vb, 0.5f);
448
449 const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos);
450
451 // The node is already in open list and the new result is worse, skip.
452 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
453 continue;
454
455 neighbourNode->id = neighbourRef;
456 neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
457 neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
458 neighbourNode->total = total;
459
460 if (neighbourNode->flags & DT_NODE_OPEN)
461 {
462 m_openList->modify(neighbourNode);
463 }
464 else
465 {
466 neighbourNode->flags = DT_NODE_OPEN;
467 m_openList->push(neighbourNode);
468 }
469 }
470 }
471
472 if (!randomPoly)
473 return DT_FAILURE;
474
475 // Randomly pick point on polygon.
476 const float* v = &randomTile->verts[randomPoly->verts[0]*3];
477 float verts[3*DT_VERTS_PER_POLYGON];
478 float areas[DT_VERTS_PER_POLYGON];
479 dtVcopy(&verts[0*3],v);
480 for (int j = 1; j < randomPoly->vertCount; ++j)
481 {
482 v = &randomTile->verts[randomPoly->verts[j]*3];
483 dtVcopy(&verts[j*3],v);
484 }
485
486 const float s = frand();
487 const float t = frand();
488
489 float pt[3];
490 dtRandomPointInConvexPoly(verts, randomPoly->vertCount, areas, s, t, pt);
491
492 closestPointOnPoly(randomPolyRef, pt, pt, NULL);
493
494 dtVcopy(randomPt, pt);
495 *randomRef = randomPolyRef;
496
497 return status;
498 }
499
500
501 //////////////////////////////////////////////////////////////////////////////////////////
502
503 /// @par
504 ///
505 /// Uses the detail polygons to find the surface height. (Most accurate.)
506 ///
507 /// @p pos does not have to be within the bounds of the polygon or navigation mesh.
508 ///
509 /// See closestPointOnPolyBoundary() for a limited but faster option.
510 ///
511 dtStatus dtNavMeshQuery::closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const
512 {
513 dtAssert(m_nav);
514 if (!m_nav->isValidPolyRef(ref) ||
515 !pos || !dtVisfinite(pos) ||
516 !closest)
517 {
518 return DT_FAILURE | DT_INVALID_PARAM;
519 }
520
521 m_nav->closestPointOnPoly(ref, pos, closest, posOverPoly);
522 return DT_SUCCESS;
523 }
524
525 /// @par
526 ///
527 /// Much faster than closestPointOnPoly().
528 ///
529 /// If the provided position lies within the polygon's xz-bounds (above or below),
530 /// then @p pos and @p closest will be equal.
531 ///
532 /// The height of @p closest will be the polygon boundary. The height detail is not used.
533 ///
534 /// @p pos does not have to be within the bounds of the polybon or the navigation mesh.
535 ///
536 dtStatus dtNavMeshQuery::closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const
537 {
538 dtAssert(m_nav);
539
540 const dtMeshTile* tile = 0;
541 const dtPoly* poly = 0;
542 if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
543 return DT_FAILURE | DT_INVALID_PARAM;
544
545 if (!pos || !dtVisfinite(pos) || !closest)
546 return DT_FAILURE | DT_INVALID_PARAM;
547
548 // Collect vertices.
549 float verts[DT_VERTS_PER_POLYGON*3];
550 float edged[DT_VERTS_PER_POLYGON];
551 float edget[DT_VERTS_PER_POLYGON];
552 int nv = 0;
553 for (int i = 0; i < (int)poly->vertCount; ++i)
554 {
555 dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]);
556 nv++;
557 }
558
559 bool inside = dtDistancePtPolyEdgesSqr(pos, verts, nv, edged, edget);
560 if (inside)
561 {
562 // Point is inside the polygon, return the point.
563 dtVcopy(closest, pos);
564 }
565 else
566 {
567 // Point is outside the polygon, dtClamp to nearest edge.
568 float dmin = edged[0];
569 int imin = 0;
570 for (int i = 1; i < nv; ++i)
571 {
572 if (edged[i] < dmin)
573 {
574 dmin = edged[i];
575 imin = i;
576 }
577 }
578 const float* va = &verts[imin*3];
579 const float* vb = &verts[((imin+1)%nv)*3];
580 dtVlerp(closest, va, vb, edget[imin]);
581 }
582
583 return DT_SUCCESS;
584 }
585
586 /// @par
587 ///
588 /// Will return #DT_FAILURE | DT_INVALID_PARAM if the provided position is outside the xz-bounds
589 /// of the polygon.
590 ///
591 dtStatus dtNavMeshQuery::getPolyHeight(dtPolyRef ref, const float* pos, float* height) const
592 {
593 dtAssert(m_nav);
594
595 const dtMeshTile* tile = 0;
596 const dtPoly* poly = 0;
597 if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
598 return DT_FAILURE | DT_INVALID_PARAM;
599
600 if (!pos || !dtVisfinite2D(pos))
601 return DT_FAILURE | DT_INVALID_PARAM;
602
603 // We used to return success for offmesh connections, but the
604 // getPolyHeight in DetourNavMesh does not do this, so special
605 // case it here.
606 if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
607 {
608 const float* v0 = &tile->verts[poly->verts[0]*3];
609 const float* v1 = &tile->verts[poly->verts[1]*3];
610 float t;
611 dtDistancePtSegSqr2D(pos, v0, v1, t);
612 if (height)
613 *height = v0[1] + (v1[1] - v0[1])*t;
614
615 return DT_SUCCESS;
616 }
617
618 return m_nav->getPolyHeight(tile, poly, pos, height)
619 ? DT_SUCCESS
620 : DT_FAILURE | DT_INVALID_PARAM;
621 }
622
623 class dtFindNearestPolyQuery : public dtPolyQuery
624 {
625 const dtNavMeshQuery* m_query;
626 const float* m_center;
627 float m_nearestDistanceSqr;
628 dtPolyRef m_nearestRef;
629 float m_nearestPoint[3];
630 bool m_overPoly;
631
632 public:
633 dtFindNearestPolyQuery(const dtNavMeshQuery* query, const float* center)
634 : m_query(query), m_center(center), m_nearestDistanceSqr(FLT_MAX), m_nearestRef(0), m_nearestPoint(), m_overPoly(false)
635 {
636 }
637
638 virtual ~dtFindNearestPolyQuery();
639
640 dtPolyRef nearestRef() const { return m_nearestRef; }
641 const float* nearestPoint() const { return m_nearestPoint; }
642 bool isOverPoly() const { return m_overPoly; }
643
644 void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count)
645 {
646 dtIgnoreUnused(polys);
647
648 for (int i = 0; i < count; ++i)
649 {
650 dtPolyRef ref = refs[i];
651 float closestPtPoly[3];
652 float diff[3];
653 bool posOverPoly = false;
654 float d;
655 m_query->closestPointOnPoly(ref, m_center, closestPtPoly, &posOverPoly);
656
657 // If a point is directly over a polygon and closer than
658 // climb height, favor that instead of straight line nearest point.
659 dtVsub(diff, m_center, closestPtPoly);
660 if (posOverPoly)
661 {
662 d = dtAbs(diff[1]) - tile->header->walkableClimb;
663 d = d > 0 ? d*d : 0;
664 }
665 else
666 {
667 d = dtVlenSqr(diff);
668 }
669
670 if (d < m_nearestDistanceSqr)
671 {
672 dtVcopy(m_nearestPoint, closestPtPoly);
673
674 m_nearestDistanceSqr = d;
675 m_nearestRef = ref;
676 m_overPoly = posOverPoly;
677 }
678 }
679 }
680 };
681
682 dtFindNearestPolyQuery::~dtFindNearestPolyQuery()
683 {
684 // Defined out of line to fix the weak v-tables warning
685 }
686
687 /// @par
688 ///
689 /// @note If the search box does not intersect any polygons the search will
690 /// return #DT_SUCCESS, but @p nearestRef will be zero. So if in doubt, check
691 /// @p nearestRef before using @p nearestPt.
692 ///
693 dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents,
694 const dtQueryFilter* filter,
695 dtPolyRef* nearestRef, float* nearestPt) const
696 {
697 return findNearestPoly(center, halfExtents, filter, nearestRef, nearestPt, NULL);
698 }
699
700 // If center and nearestPt point to an equal position, isOverPoly will be true;
701 // however there's also a special case of climb height inside the polygon (see dtFindNearestPolyQuery)
702 dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents,
703 const dtQueryFilter* filter,
704 dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const
705 {
706 dtAssert(m_nav);
707
708 if (!nearestRef)
709 return DT_FAILURE | DT_INVALID_PARAM;
710
711 // queryPolygons below will check rest of params
712
713 dtFindNearestPolyQuery query(this, center);
714
715 dtStatus status = queryPolygons(center, halfExtents, filter, &query);
716 if (dtStatusFailed(status))
717 return status;
718
719 *nearestRef = query.nearestRef();
720 // Only override nearestPt if we actually found a poly so the nearest point
721 // is valid.
722 if (nearestPt && *nearestRef)
723 {
724 dtVcopy(nearestPt, query.nearestPoint());
725 if (isOverPoly)
726 *isOverPoly = query.isOverPoly();
727 }
728
729 return DT_SUCCESS;
730 }
731
732 void dtNavMeshQuery::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
733 const dtQueryFilter* filter, dtPolyQuery* query) const
734 {
735 dtAssert(m_nav);
736 static const int batchSize = 32;
737 dtPolyRef polyRefs[batchSize];
738 dtPoly* polys[batchSize];
739 int n = 0;
740
741 if (tile->bvTree)
742 {
743 const dtBVNode* node = &tile->bvTree[0];
744 const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount];
745 const float* tbmin = tile->header->bmin;
746 const float* tbmax = tile->header->bmax;
747 const float qfac = tile->header->bvQuantFactor;
748
749 // Calculate quantized box
750 unsigned short bmin[3], bmax[3];
751 // dtClamp query box to world box.
752 float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
753 float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
754 float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
755 float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
756 float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
757 float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
758 // Quantize
759 bmin[0] = (unsigned short)(qfac * minx) & 0xfffe;
760 bmin[1] = (unsigned short)(qfac * miny) & 0xfffe;
761 bmin[2] = (unsigned short)(qfac * minz) & 0xfffe;
762 bmax[0] = (unsigned short)(qfac * maxx + 1) | 1;
763 bmax[1] = (unsigned short)(qfac * maxy + 1) | 1;
764 bmax[2] = (unsigned short)(qfac * maxz + 1) | 1;
765
766 // Traverse tree
767 const dtPolyRef base = m_nav->getPolyRefBase(tile);
768 while (node < end)
769 {
770 const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax);
771 const bool isLeafNode = node->i >= 0;
772
773 if (isLeafNode && overlap)
774 {
775 dtPolyRef ref = base | (dtPolyRef)node->i;
776 if (filter->passFilter(ref, tile, &tile->polys[node->i]))
777 {
778 polyRefs[n] = ref;
779 polys[n] = &tile->polys[node->i];
780
781 if (n == batchSize - 1)
782 {
783 query->process(tile, polys, polyRefs, batchSize);
784 n = 0;
785 }
786 else
787 {
788 n++;
789 }
790 }
791 }
792
793 if (overlap || isLeafNode)
794 node++;
795 else
796 {
797 const int escapeIndex = -node->i;
798 node += escapeIndex;
799 }
800 }
801 }
802 else
803 {
804 float bmin[3], bmax[3];
805 const dtPolyRef base = m_nav->getPolyRefBase(tile);
806 for (int i = 0; i < tile->header->polyCount; ++i)
807 {
808 dtPoly* p = &tile->polys[i];
809 // Do not return off-mesh connection polygons.
810 if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
811 continue;
812 // Must pass filter
813 const dtPolyRef ref = base | (dtPolyRef)i;
814 if (!filter->passFilter(ref, tile, p))
815 continue;
816 // Calc polygon bounds.
817 const float* v = &tile->verts[p->verts[0]*3];
818 dtVcopy(bmin, v);
819 dtVcopy(bmax, v);
820 for (int j = 1; j < p->vertCount; ++j)
821 {
822 v = &tile->verts[p->verts[j]*3];
823 dtVmin(bmin, v);
824 dtVmax(bmax, v);
825 }
826 if (dtOverlapBounds(qmin, qmax, bmin, bmax))
827 {
828 polyRefs[n] = ref;
829 polys[n] = p;
830
831 if (n == batchSize - 1)
832 {
833 query->process(tile, polys, polyRefs, batchSize);
834 n = 0;
835 }
836 else
837 {
838 n++;
839 }
840 }
841 }
842 }
843
844 // Process the last polygons that didn't make a full batch.
845 if (n > 0)
846 query->process(tile, polys, polyRefs, n);
847 }
848
849 class dtCollectPolysQuery : public dtPolyQuery
850 {
851 dtPolyRef* m_polys;
852 const int m_maxPolys;
853 int m_numCollected;
854 bool m_overflow;
855
856 public:
857 dtCollectPolysQuery(dtPolyRef* polys, const int maxPolys)
858 : m_polys(polys), m_maxPolys(maxPolys), m_numCollected(0), m_overflow(false)
859 {
860 }
861
862 virtual ~dtCollectPolysQuery();
863
864 int numCollected() const { return m_numCollected; }
865 bool overflowed() const { return m_overflow; }
866
867 void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count)
868 {
869 dtIgnoreUnused(tile);
870 dtIgnoreUnused(polys);
871
872 int numLeft = m_maxPolys - m_numCollected;
873 int toCopy = count;
874 if (toCopy > numLeft)
875 {
876 m_overflow = true;
877 toCopy = numLeft;
878 }
879
880 memcpy(m_polys + m_numCollected, refs, (size_t)toCopy * sizeof(dtPolyRef));
881 m_numCollected += toCopy;
882 }
883 };
884
885 dtCollectPolysQuery::~dtCollectPolysQuery()
886 {
887 // Defined out of line to fix the weak v-tables warning
888 }
889
890 /// @par
891 ///
892 /// If no polygons are found, the function will return #DT_SUCCESS with a
893 /// @p polyCount of zero.
894 ///
895 /// If @p polys is too small to hold the entire result set, then the array will
896 /// be filled to capacity. The method of choosing which polygons from the
897 /// full set are included in the partial result set is undefined.
898 ///
899 dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents,
900 const dtQueryFilter* filter,
901 dtPolyRef* polys, int* polyCount, const int maxPolys) const
902 {
903 if (!polys || !polyCount || maxPolys < 0)
904 return DT_FAILURE | DT_INVALID_PARAM;
905
906 dtCollectPolysQuery collector(polys, maxPolys);
907
908 dtStatus status = queryPolygons(center, halfExtents, filter, &collector);
909 if (dtStatusFailed(status))
910 return status;
911
912 *polyCount = collector.numCollected();
913 return collector.overflowed() ? DT_SUCCESS | DT_BUFFER_TOO_SMALL : DT_SUCCESS;
914 }
915
916 /// @par
917 ///
918 /// The query will be invoked with batches of polygons. Polygons passed
919 /// to the query have bounding boxes that overlap with the center and halfExtents
920 /// passed to this function. The dtPolyQuery::process function is invoked multiple
921 /// times until all overlapping polygons have been processed.
922 ///
923 dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents,
924 const dtQueryFilter* filter, dtPolyQuery* query) const
925 {
926 dtAssert(m_nav);
927
928 if (!center || !dtVisfinite(center) ||
929 !halfExtents || !dtVisfinite(halfExtents) ||
930 !filter || !query)
931 {
932 return DT_FAILURE | DT_INVALID_PARAM;
933 }
934
935 float bmin[3], bmax[3];
936 dtVsub(bmin, center, halfExtents);
937 dtVadd(bmax, center, halfExtents);
938
939 // Find tiles the query touches.
940 int minx, miny, maxx, maxy;
941 m_nav->calcTileLoc(bmin, &minx, &miny);
942 m_nav->calcTileLoc(bmax, &maxx, &maxy);
943
944 static const int MAX_NEIS = 32;
945 const dtMeshTile* neis[MAX_NEIS];
946
947 for (int y = miny; y <= maxy; ++y)
948 {
949 for (int x = minx; x <= maxx; ++x)
950 {
951 const int nneis = m_nav->getTilesAt(x,y,neis,MAX_NEIS);
952 for (int j = 0; j < nneis; ++j)
953 {
954 queryPolygonsInTile(neis[j], bmin, bmax, filter, query);
955 }
956 }
957 }
958
959 return DT_SUCCESS;
960 }
961
962 /// @par
963 ///
964 /// If the end polygon cannot be reached through the navigation graph,
965 /// the last polygon in the path will be the nearest the end polygon.
966 ///
967 /// If the path array is to small to hold the full result, it will be filled as
968 /// far as possible from the start polygon toward the end polygon.
969 ///
970 /// The start and end positions are used to calculate traversal costs.
971 /// (The y-values impact the result.)
972 ///
973 dtStatus dtNavMeshQuery::findPath(dtPolyRef startRef, dtPolyRef endRef,
974 const float* startPos, const float* endPos,
975 const dtQueryFilter* filter,
976 dtPolyRef* path, int* pathCount, const int maxPath) const
977 {
978 dtAssert(m_nav);
979 dtAssert(m_nodePool);
980 dtAssert(m_openList);
981
982 if (!pathCount)
983 return DT_FAILURE | DT_INVALID_PARAM;
984
985 *pathCount = 0;
986
987 // Validate input
988 if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) ||
989 !startPos || !dtVisfinite(startPos) ||
990 !endPos || !dtVisfinite(endPos) ||
991 !filter || !path || maxPath <= 0)
992 {
993 return DT_FAILURE | DT_INVALID_PARAM;
994 }
995
996 if (startRef == endRef)
997 {
998 path[0] = startRef;
999 *pathCount = 1;
1000 return DT_SUCCESS;
1001 }
1002
1003 m_nodePool->clear();
1004 m_openList->clear();
1005
1006 dtNode* startNode = m_nodePool->getNode(startRef);
1007 dtVcopy(startNode->pos, startPos);
1008 startNode->pidx = 0;
1009 startNode->cost = 0;
1010 startNode->total = dtVdist(startPos, endPos) * H_SCALE;
1011 startNode->id = startRef;
1012 startNode->flags = DT_NODE_OPEN;
1013 m_openList->push(startNode);
1014
1015 dtNode* lastBestNode = startNode;
1016 float lastBestNodeCost = startNode->total;
1017
1018 bool outOfNodes = false;
1019
1020 while (!m_openList->empty())
1021 {
1022 // Remove node from open list and put it in closed list.
1023 dtNode* bestNode = m_openList->pop();
1024 bestNode->flags &= ~DT_NODE_OPEN;
1025 bestNode->flags |= DT_NODE_CLOSED;
1026
1027 // Reached the goal, stop searching.
1028 if (bestNode->id == endRef)
1029 {
1030 lastBestNode = bestNode;
1031 break;
1032 }
1033
1034 // Get current poly and tile.
1035 // The API input has been cheked already, skip checking internal data.
1036 const dtPolyRef bestRef = bestNode->id;
1037 const dtMeshTile* bestTile = 0;
1038 const dtPoly* bestPoly = 0;
1039 m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
1040
1041 // Get parent poly and tile.
1042 dtPolyRef parentRef = 0;
1043 const dtMeshTile* parentTile = 0;
1044 const dtPoly* parentPoly = 0;
1045 if (bestNode->pidx)
1046 parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
1047 if (parentRef)
1048 m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
1049
1050 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
1051 {
1052 dtPolyRef neighbourRef = bestTile->links[i].ref;
1053
1054 // Skip invalid ids and do not expand back to where we came from.
1055 if (!neighbourRef || neighbourRef == parentRef)
1056 continue;
1057
1058 // Get neighbour poly and tile.
1059 // The API input has been cheked already, skip checking internal data.
1060 const dtMeshTile* neighbourTile = 0;
1061 const dtPoly* neighbourPoly = 0;
1062 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
1063
1064 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
1065 continue;
1066
1067 // deal explicitly with crossing tile boundaries
1068 unsigned char crossSide = 0;
1069 if (bestTile->links[i].side != 0xff)
1070 crossSide = bestTile->links[i].side >> 1;
1071
1072 // get the node
1073 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, crossSide);
1074 if (!neighbourNode)
1075 {
1076 outOfNodes = true;
1077 continue;
1078 }
1079
1080 // If the node is visited the first time, calculate node position.
1081 if (neighbourNode->flags == 0)
1082 {
1083 getEdgeMidPoint(bestRef, bestPoly, bestTile,
1084 neighbourRef, neighbourPoly, neighbourTile,
1085 neighbourNode->pos);
1086 }
1087
1088 // Calculate cost and heuristic.
1089 float cost = 0;
1090 float heuristic = 0;
1091
1092 // Special case for last node.
1093 if (neighbourRef == endRef)
1094 {
1095 // Cost
1096 const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos,
1097 parentRef, parentTile, parentPoly,
1098 bestRef, bestTile, bestPoly,
1099 neighbourRef, neighbourTile, neighbourPoly);
1100 const float endCost = filter->getCost(neighbourNode->pos, endPos,
1101 bestRef, bestTile, bestPoly,
1102 neighbourRef, neighbourTile, neighbourPoly,
1103 0, 0, 0);
1104
1105 cost = bestNode->cost + curCost + endCost;
1106 heuristic = 0;
1107 }
1108 else
1109 {
1110 // Cost
1111 const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos,
1112 parentRef, parentTile, parentPoly,
1113 bestRef, bestTile, bestPoly,
1114 neighbourRef, neighbourTile, neighbourPoly);
1115 cost = bestNode->cost + curCost;
1116 heuristic = dtVdist(neighbourNode->pos, endPos)*H_SCALE;
1117 }
1118
1119 const float total = cost + heuristic;
1120
1121 // The node is already in open list and the new result is worse, skip.
1122 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
1123 continue;
1124 // The node is already visited and process, and the new result is worse, skip.
1125 if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total)
1126 continue;
1127
1128 // Add or update the node.
1129 neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
1130 neighbourNode->id = neighbourRef;
1131 neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
1132 neighbourNode->cost = cost;
1133 neighbourNode->total = total;
1134
1135 if (neighbourNode->flags & DT_NODE_OPEN)
1136 {
1137 // Already in open, update node location.
1138 m_openList->modify(neighbourNode);
1139 }
1140 else
1141 {
1142 // Put the node in open list.
1143 neighbourNode->flags |= DT_NODE_OPEN;
1144 m_openList->push(neighbourNode);
1145 }
1146
1147 // Update nearest node to target so far.
1148 if (heuristic < lastBestNodeCost)
1149 {
1150 lastBestNodeCost = heuristic;
1151 lastBestNode = neighbourNode;
1152 }
1153 }
1154 }
1155
1156 dtStatus status = getPathToNode(lastBestNode, path, pathCount, maxPath);
1157
1158 if (lastBestNode->id != endRef)
1159 status |= DT_PARTIAL_RESULT;
1160
1161 if (outOfNodes)
1162 status |= DT_OUT_OF_NODES;
1163
1164 return status;
1165 }
1166
1167 dtStatus dtNavMeshQuery::getPathToNode(dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const
1168 {
1169 // Find the length of the entire path.
1170 dtNode* curNode = endNode;
1171 int length = 0;
1172 do
1173 {
1174 length++;
1175 curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
1176 } while (curNode);
1177
1178 // If the path cannot be fully stored then advance to the last node we will be able to store.
1179 curNode = endNode;
1180 int writeCount;
1181 for (writeCount = length; writeCount > maxPath; writeCount--)
1182 {
1183 dtAssert(curNode);
1184
1185 curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
1186 }
1187
1188 // Write path
1189 for (int i = writeCount - 1; i >= 0; i--)
1190 {
1191 dtAssert(curNode);
1192
1193 path[i] = curNode->id;
1194 curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
1195 }
1196
1197 dtAssert(!curNode);
1198
1199 *pathCount = dtMin(length, maxPath);
1200
1201 if (length > maxPath)
1202 return DT_SUCCESS | DT_BUFFER_TOO_SMALL;
1203
1204 return DT_SUCCESS;
1205 }
1206
1207
1208 /// @par
1209 ///
1210 /// @warning Calling any non-slice methods before calling finalizeSlicedFindPath()
1211 /// or finalizeSlicedFindPathPartial() may result in corrupted data!
1212 ///
1213 /// The @p filter pointer is stored and used for the duration of the sliced
1214 /// path query.
1215 ///
1216 dtStatus dtNavMeshQuery::initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef,
1217 const float* startPos, const float* endPos,
1218 const dtQueryFilter* filter, const unsigned int options)
1219 {
1220 dtAssert(m_nav);
1221 dtAssert(m_nodePool);
1222 dtAssert(m_openList);
1223
1224 // Init path state.
1225 memset(&m_query, 0, sizeof(dtQueryData));
1226 m_query.status = DT_FAILURE;
1227 m_query.startRef = startRef;
1228 m_query.endRef = endRef;
1229 if (startPos)
1230 dtVcopy(m_query.startPos, startPos);
1231 if (endPos)
1232 dtVcopy(m_query.endPos, endPos);
1233 m_query.filter = filter;
1234 m_query.options = options;
1235 m_query.raycastLimitSqr = FLT_MAX;
1236
1237 // Validate input
1238 if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) ||
1239 !startPos || !dtVisfinite(startPos) ||
1240 !endPos || !dtVisfinite(endPos) || !filter)
1241 {
1242 return DT_FAILURE | DT_INVALID_PARAM;
1243 }
1244
1245 // trade quality with performance?
1246 if (options & DT_FINDPATH_ANY_ANGLE)
1247 {
1248 // limiting to several times the character radius yields nice results. It is not sensitive
1249 // so it is enough to compute it from the first tile.
1250 const dtMeshTile* tile = m_nav->getTileByRef(startRef);
1251 float agentRadius = tile->header->walkableRadius;
1252 m_query.raycastLimitSqr = dtSqr(agentRadius * DT_RAY_CAST_LIMIT_PROPORTIONS);
1253 }
1254
1255 if (startRef == endRef)
1256 {
1257 m_query.status = DT_SUCCESS;
1258 return DT_SUCCESS;
1259 }
1260
1261 m_nodePool->clear();
1262 m_openList->clear();
1263
1264 dtNode* startNode = m_nodePool->getNode(startRef);
1265 dtVcopy(startNode->pos, startPos);
1266 startNode->pidx = 0;
1267 startNode->cost = 0;
1268 startNode->total = dtVdist(startPos, endPos) * H_SCALE;
1269 startNode->id = startRef;
1270 startNode->flags = DT_NODE_OPEN;
1271 m_openList->push(startNode);
1272
1273 m_query.status = DT_IN_PROGRESS;
1274 m_query.lastBestNode = startNode;
1275 m_query.lastBestNodeCost = startNode->total;
1276
1277 return m_query.status;
1278 }
1279
1280 dtStatus dtNavMeshQuery::updateSlicedFindPath(const int maxIter, int* doneIters)
1281 {
1282 if (!dtStatusInProgress(m_query.status))
1283 return m_query.status;
1284
1285 // Make sure the request is still valid.
1286 if (!m_nav->isValidPolyRef(m_query.startRef) || !m_nav->isValidPolyRef(m_query.endRef))
1287 {
1288 m_query.status = DT_FAILURE;
1289 return DT_FAILURE;
1290 }
1291
1292 dtRaycastHit rayHit;
1293 rayHit.maxPath = 0;
1294
1295 int iter = 0;
1296 while (iter < maxIter && !m_openList->empty())
1297 {
1298 iter++;
1299
1300 // Remove node from open list and put it in closed list.
1301 dtNode* bestNode = m_openList->pop();
1302 bestNode->flags &= ~DT_NODE_OPEN;
1303 bestNode->flags |= DT_NODE_CLOSED;
1304
1305 // Reached the goal, stop searching.
1306 if (bestNode->id == m_query.endRef)
1307 {
1308 m_query.lastBestNode = bestNode;
1309 const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
1310 m_query.status = DT_SUCCESS | details;
1311 if (doneIters)
1312 *doneIters = iter;
1313 return m_query.status;
1314 }
1315
1316 // Get current poly and tile.
1317 // The API input has been cheked already, skip checking internal data.
1318 const dtPolyRef bestRef = bestNode->id;
1319 const dtMeshTile* bestTile = 0;
1320 const dtPoly* bestPoly = 0;
1321 if (dtStatusFailed(m_nav->getTileAndPolyByRef(bestRef, &bestTile, &bestPoly)))
1322 {
1323 // The polygon has disappeared during the sliced query, fail.
1324 m_query.status = DT_FAILURE;
1325 if (doneIters)
1326 *doneIters = iter;
1327 return m_query.status;
1328 }
1329
1330 // Get parent and grand parent poly and tile.
1331 dtPolyRef parentRef = 0, grandpaRef = 0;
1332 const dtMeshTile* parentTile = 0;
1333 const dtPoly* parentPoly = 0;
1334 dtNode* parentNode = 0;
1335 if (bestNode->pidx)
1336 {
1337 parentNode = m_nodePool->getNodeAtIdx(bestNode->pidx);
1338 parentRef = parentNode->id;
1339 if (parentNode->pidx)
1340 grandpaRef = m_nodePool->getNodeAtIdx(parentNode->pidx)->id;
1341 }
1342 if (parentRef)
1343 {
1344 bool invalidParent = dtStatusFailed(m_nav->getTileAndPolyByRef(parentRef, &parentTile, &parentPoly));
1345 if (invalidParent || (grandpaRef && !m_nav->isValidPolyRef(grandpaRef)) )
1346 {
1347 // The polygon has disappeared during the sliced query, fail.
1348 m_query.status = DT_FAILURE;
1349 if (doneIters)
1350 *doneIters = iter;
1351 return m_query.status;
1352 }
1353 }
1354
1355 // decide whether to test raycast to previous nodes
1356 bool tryLOS = false;
1357 if (m_query.options & DT_FINDPATH_ANY_ANGLE)
1358 {
1359 if ((parentRef != 0) && (dtVdistSqr(parentNode->pos, bestNode->pos) < m_query.raycastLimitSqr))
1360 tryLOS = true;
1361 }
1362
1363 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
1364 {
1365 dtPolyRef neighbourRef = bestTile->links[i].ref;
1366
1367 // Skip invalid ids and do not expand back to where we came from.
1368 if (!neighbourRef || neighbourRef == parentRef)
1369 continue;
1370
1371 // Get neighbour poly and tile.
1372 // The API input has been cheked already, skip checking internal data.
1373 const dtMeshTile* neighbourTile = 0;
1374 const dtPoly* neighbourPoly = 0;
1375 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
1376
1377 if (!m_query.filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
1378 continue;
1379
1380 // get the neighbor node
1381 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, 0);
1382 if (!neighbourNode)
1383 {
1384 m_query.status |= DT_OUT_OF_NODES;
1385 continue;
1386 }
1387
1388 // do not expand to nodes that were already visited from the same parent
1389 if (neighbourNode->pidx != 0 && neighbourNode->pidx == bestNode->pidx)
1390 continue;
1391
1392 // If the node is visited the first time, calculate node position.
1393 if (neighbourNode->flags == 0)
1394 {
1395 getEdgeMidPoint(bestRef, bestPoly, bestTile,
1396 neighbourRef, neighbourPoly, neighbourTile,
1397 neighbourNode->pos);
1398 }
1399
1400 // Calculate cost and heuristic.
1401 float cost = 0;
1402 float heuristic = 0;
1403
1404 // raycast parent
1405 bool foundShortCut = false;
1406 rayHit.pathCost = rayHit.t = 0;
1407 if (tryLOS)
1408 {
1409 raycast(parentRef, parentNode->pos, neighbourNode->pos, m_query.filter, DT_RAYCAST_USE_COSTS, &rayHit, grandpaRef);
1410 foundShortCut = rayHit.t >= 1.0f;
1411 }
1412
1413 // update move cost
1414 if (foundShortCut)
1415 {
1416 // shortcut found using raycast. Using shorter cost instead
1417 cost = parentNode->cost + rayHit.pathCost;
1418 }
1419 else
1420 {
1421 // No shortcut found.
1422 const float curCost = m_query.filter->getCost(bestNode->pos, neighbourNode->pos,
1423 parentRef, parentTile, parentPoly,
1424 bestRef, bestTile, bestPoly,
1425 neighbourRef, neighbourTile, neighbourPoly);
1426 cost = bestNode->cost + curCost;
1427 }
1428
1429 // Special case for last node.
1430 if (neighbourRef == m_query.endRef)
1431 {
1432 const float endCost = m_query.filter->getCost(neighbourNode->pos, m_query.endPos,
1433 bestRef, bestTile, bestPoly,
1434 neighbourRef, neighbourTile, neighbourPoly,
1435 0, 0, 0);
1436
1437 cost = cost + endCost;
1438 heuristic = 0;
1439 }
1440 else
1441 {
1442 heuristic = dtVdist(neighbourNode->pos, m_query.endPos)*H_SCALE;
1443 }
1444
1445 const float total = cost + heuristic;
1446
1447 // The node is already in open list and the new result is worse, skip.
1448 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
1449 continue;
1450 // The node is already visited and process, and the new result is worse, skip.
1451 if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total)
1452 continue;
1453
1454 // Add or update the node.
1455 neighbourNode->pidx = foundShortCut ? bestNode->pidx : m_nodePool->getNodeIdx(bestNode);
1456 neighbourNode->id = neighbourRef;
1457 neighbourNode->flags = (neighbourNode->flags & ~(DT_NODE_CLOSED | DT_NODE_PARENT_DETACHED));
1458 neighbourNode->cost = cost;
1459 neighbourNode->total = total;
1460 if (foundShortCut)
1461 neighbourNode->flags = (neighbourNode->flags | DT_NODE_PARENT_DETACHED);
1462
1463 if (neighbourNode->flags & DT_NODE_OPEN)
1464 {
1465 // Already in open, update node location.
1466 m_openList->modify(neighbourNode);
1467 }
1468 else
1469 {
1470 // Put the node in open list.
1471 neighbourNode->flags |= DT_NODE_OPEN;
1472 m_openList->push(neighbourNode);
1473 }
1474
1475 // Update nearest node to target so far.
1476 if (heuristic < m_query.lastBestNodeCost)
1477 {
1478 m_query.lastBestNodeCost = heuristic;
1479 m_query.lastBestNode = neighbourNode;
1480 }
1481 }
1482 }
1483
1484 // Exhausted all nodes, but could not find path.
1485 if (m_openList->empty())
1486 {
1487 const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
1488 m_query.status = DT_SUCCESS | details;
1489 }
1490
1491 if (doneIters)
1492 *doneIters = iter;
1493
1494 return m_query.status;
1495 }
1496
1497 dtStatus dtNavMeshQuery::finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath)
1498 {
1499 if (!pathCount)
1500 return DT_FAILURE | DT_INVALID_PARAM;
1501
1502 *pathCount = 0;
1503
1504 if (!path || maxPath <= 0)
1505 return DT_FAILURE | DT_INVALID_PARAM;
1506
1507 if (dtStatusFailed(m_query.status))
1508 {
1509 // Reset query.
1510 memset(&m_query, 0, sizeof(dtQueryData));
1511 return DT_FAILURE;
1512 }
1513
1514 int n = 0;
1515
1516 if (m_query.startRef == m_query.endRef)
1517 {
1518 // Special case: the search starts and ends at same poly.
1519 path[n++] = m_query.startRef;
1520 }
1521 else
1522 {
1523 // Reverse the path.
1524 dtAssert(m_query.lastBestNode);
1525
1526 if (m_query.lastBestNode->id != m_query.endRef)
1527 m_query.status |= DT_PARTIAL_RESULT;
1528
1529 dtNode* prev = 0;
1530 dtNode* node = m_query.lastBestNode;
1531 int prevRay = 0;
1532 do
1533 {
1534 dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
1535 node->pidx = m_nodePool->getNodeIdx(prev);
1536 prev = node;
1537 int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
1538 node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node
1539 prevRay = nextRay;
1540 node = next;
1541 }
1542 while (node);
1543
1544 // Store path
1545 node = prev;
1546 do
1547 {
1548 dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
1549 dtStatus status = 0;
1550 if (node->flags & DT_NODE_PARENT_DETACHED)
1551 {
1552 float t, normal[3];
1553 int m;
1554 status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n);
1555 n += m;
1556 // raycast ends on poly boundary and the path might include the next poly boundary.
1557 if (path[n-1] == next->id)
1558 n--; // remove to avoid duplicates
1559 }
1560 else
1561 {
1562 path[n++] = node->id;
1563 if (n >= maxPath)
1564 status = DT_BUFFER_TOO_SMALL;
1565 }
1566
1567 if (status & DT_STATUS_DETAIL_MASK)
1568 {
1569 m_query.status |= status & DT_STATUS_DETAIL_MASK;
1570 break;
1571 }
1572 node = next;
1573 }
1574 while (node);
1575 }
1576
1577 const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
1578
1579 // Reset query.
1580 memset(&m_query, 0, sizeof(dtQueryData));
1581
1582 *pathCount = n;
1583
1584 return DT_SUCCESS | details;
1585 }
1586
1587 dtStatus dtNavMeshQuery::finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize,
1588 dtPolyRef* path, int* pathCount, const int maxPath)
1589 {
1590 if (!pathCount)
1591 return DT_FAILURE | DT_INVALID_PARAM;
1592
1593 *pathCount = 0;
1594
1595 if (!existing || existingSize <= 0 || !path || !pathCount || maxPath <= 0)
1596 return DT_FAILURE | DT_INVALID_PARAM;
1597
1598 if (dtStatusFailed(m_query.status))
1599 {
1600 // Reset query.
1601 memset(&m_query, 0, sizeof(dtQueryData));
1602 return DT_FAILURE;
1603 }
1604
1605 int n = 0;
1606
1607 if (m_query.startRef == m_query.endRef)
1608 {
1609 // Special case: the search starts and ends at same poly.
1610 path[n++] = m_query.startRef;
1611 }
1612 else
1613 {
1614 // Find furthest existing node that was visited.
1615 dtNode* prev = 0;
1616 dtNode* node = 0;
1617 for (int i = existingSize-1; i >= 0; --i)
1618 {
1619 m_nodePool->findNodes(existing[i], &node, 1);
1620 if (node)
1621 break;
1622 }
1623
1624 if (!node)
1625 {
1626 m_query.status |= DT_PARTIAL_RESULT;
1627 dtAssert(m_query.lastBestNode);
1628 node = m_query.lastBestNode;
1629 }
1630
1631 // Reverse the path.
1632 int prevRay = 0;
1633 do
1634 {
1635 dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
1636 node->pidx = m_nodePool->getNodeIdx(prev);
1637 prev = node;
1638 int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
1639 node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node
1640 prevRay = nextRay;
1641 node = next;
1642 }
1643 while (node);
1644
1645 // Store path
1646 node = prev;
1647 do
1648 {
1649 dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
1650 dtStatus status = 0;
1651 if (node->flags & DT_NODE_PARENT_DETACHED)
1652 {
1653 float t, normal[3];
1654 int m;
1655 status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n);
1656 n += m;
1657 // raycast ends on poly boundary and the path might include the next poly boundary.
1658 if (path[n-1] == next->id)
1659 n--; // remove to avoid duplicates
1660 }
1661 else
1662 {
1663 path[n++] = node->id;
1664 if (n >= maxPath)
1665 status = DT_BUFFER_TOO_SMALL;
1666 }
1667
1668 if (status & DT_STATUS_DETAIL_MASK)
1669 {
1670 m_query.status |= status & DT_STATUS_DETAIL_MASK;
1671 break;
1672 }
1673 node = next;
1674 }
1675 while (node);
1676 }
1677
1678 const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
1679
1680 // Reset query.
1681 memset(&m_query, 0, sizeof(dtQueryData));
1682
1683 *pathCount = n;
1684
1685 return DT_SUCCESS | details;
1686 }
1687
1688
1689 dtStatus dtNavMeshQuery::appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref,
1690 float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
1691 int* straightPathCount, const int maxStraightPath) const
1692 {
1693 if ((*straightPathCount) > 0 && dtVequal(&straightPath[((*straightPathCount)-1)*3], pos))
1694 {
1695 // The vertices are equal, update flags and poly.
1696 if (straightPathFlags)
1697 straightPathFlags[(*straightPathCount)-1] = flags;
1698 if (straightPathRefs)
1699 straightPathRefs[(*straightPathCount)-1] = ref;
1700 }
1701 else
1702 {
1703 // Append new vertex.
1704 dtVcopy(&straightPath[(*straightPathCount)*3], pos);
1705 if (straightPathFlags)
1706 straightPathFlags[(*straightPathCount)] = flags;
1707 if (straightPathRefs)
1708 straightPathRefs[(*straightPathCount)] = ref;
1709 (*straightPathCount)++;
1710
1711 // If there is no space to append more vertices, return.
1712 if ((*straightPathCount) >= maxStraightPath)
1713 {
1714 return DT_SUCCESS | DT_BUFFER_TOO_SMALL;
1715 }
1716
1717 // If reached end of path, return.
1718 if (flags == DT_STRAIGHTPATH_END)
1719 {
1720 return DT_SUCCESS;
1721 }
1722 }
1723 return DT_IN_PROGRESS;
1724 }
1725
1726 dtStatus dtNavMeshQuery::appendPortals(const int startIdx, const int endIdx, const float* endPos, const dtPolyRef* path,
1727 float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
1728 int* straightPathCount, const int maxStraightPath, const int options) const
1729 {
1730 const float* startPos = &straightPath[(*straightPathCount-1)*3];
1731 // Append or update last vertex
1732 dtStatus stat = 0;
1733 for (int i = startIdx; i < endIdx; i++)
1734 {
1735 // Calculate portal
1736 const dtPolyRef from = path[i];
1737 const dtMeshTile* fromTile = 0;
1738 const dtPoly* fromPoly = 0;
1739 if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly)))
1740 return DT_FAILURE | DT_INVALID_PARAM;
1741
1742 const dtPolyRef to = path[i+1];
1743 const dtMeshTile* toTile = 0;
1744 const dtPoly* toPoly = 0;
1745 if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly)))
1746 return DT_FAILURE | DT_INVALID_PARAM;
1747
1748 float left[3], right[3];
1749 if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right)))
1750 break;
1751
1752 if (options & DT_STRAIGHTPATH_AREA_CROSSINGS)
1753 {
1754 // Skip intersection if only area crossings are requested.
1755 if (fromPoly->getArea() == toPoly->getArea())
1756 continue;
1757 }
1758
1759 // Append intersection
1760 float s,t;
1761 if (dtIntersectSegSeg2D(startPos, endPos, left, right, s, t))
1762 {
1763 float pt[3];
1764 dtVlerp(pt, left,right, t);
1765
1766 stat = appendVertex(pt, 0, path[i+1],
1767 straightPath, straightPathFlags, straightPathRefs,
1768 straightPathCount, maxStraightPath);
1769 if (stat != DT_IN_PROGRESS)
1770 return stat;
1771 }
1772 }
1773 return DT_IN_PROGRESS;
1774 }
1775
1776 /// @par
1777 ///
1778 /// This method peforms what is often called 'string pulling'.
1779 ///
1780 /// The start position is clamped to the first polygon in the path, and the
1781 /// end position is clamped to the last. So the start and end positions should
1782 /// normally be within or very near the first and last polygons respectively.
1783 ///
1784 /// The returned polygon references represent the reference id of the polygon
1785 /// that is entered at the associated path position. The reference id associated
1786 /// with the end point will always be zero. This allows, for example, matching
1787 /// off-mesh link points to their representative polygons.
1788 ///
1789 /// If the provided result buffers are too small for the entire result set,
1790 /// they will be filled as far as possible from the start toward the end
1791 /// position.
1792 ///
1793 dtStatus dtNavMeshQuery::findStraightPath(const float* startPos, const float* endPos,
1794 const dtPolyRef* path, const int pathSize,
1795 float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
1796 int* straightPathCount, const int maxStraightPath, const int options) const
1797 {
1798 dtAssert(m_nav);
1799
1800 if (!straightPathCount)
1801 return DT_FAILURE | DT_INVALID_PARAM;
1802
1803 *straightPathCount = 0;
1804
1805 if (!startPos || !dtVisfinite(startPos) ||
1806 !endPos || !dtVisfinite(endPos) ||
1807 !path || pathSize <= 0 || !path[0] ||
1808 maxStraightPath <= 0)
1809 {
1810 return DT_FAILURE | DT_INVALID_PARAM;
1811 }
1812
1813 dtStatus stat = 0;
1814
1815 // TODO: Should this be callers responsibility?
1816 float closestStartPos[3];
1817 if (dtStatusFailed(closestPointOnPolyBoundary(path[0], startPos, closestStartPos)))
1818 return DT_FAILURE | DT_INVALID_PARAM;
1819
1820 float closestEndPos[3];
1821 if (dtStatusFailed(closestPointOnPolyBoundary(path[pathSize-1], endPos, closestEndPos)))
1822 return DT_FAILURE | DT_INVALID_PARAM;
1823
1824 // Add start point.
1825 stat = appendVertex(closestStartPos, DT_STRAIGHTPATH_START, path[0],
1826 straightPath, straightPathFlags, straightPathRefs,
1827 straightPathCount, maxStraightPath);
1828 if (stat != DT_IN_PROGRESS)
1829 return stat;
1830
1831 if (pathSize > 1)
1832 {
1833 float portalApex[3], portalLeft[3], portalRight[3];
1834 dtVcopy(portalApex, closestStartPos);
1835 dtVcopy(portalLeft, portalApex);
1836 dtVcopy(portalRight, portalApex);
1837 int apexIndex = 0;
1838 int leftIndex = 0;
1839 int rightIndex = 0;
1840
1841 unsigned char leftPolyType = 0;
1842 unsigned char rightPolyType = 0;
1843
1844 dtPolyRef leftPolyRef = path[0];
1845 dtPolyRef rightPolyRef = path[0];
1846
1847 for (int i = 0; i < pathSize; ++i)
1848 {
1849 float left[3], right[3];
1850 unsigned char toType;
1851
1852 if (i+1 < pathSize)
1853 {
1854 unsigned char fromType; // fromType is ignored.
1855
1856 // Next portal.
1857 if (dtStatusFailed(getPortalPoints(path[i], path[i+1], left, right, fromType, toType)))
1858 {
1859 // Failed to get portal points, in practice this means that path[i+1] is invalid polygon.
1860 // Clamp the end point to path[i], and return the path so far.
1861
1862 if (dtStatusFailed(closestPointOnPolyBoundary(path[i], endPos, closestEndPos)))
1863 {
1864 // This should only happen when the first polygon is invalid.
1865 return DT_FAILURE | DT_INVALID_PARAM;
1866 }
1867
1868 // Apeend portals along the current straight path segment.
1869 if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
1870 {
1871 // Ignore status return value as we're just about to return anyway.
1872 appendPortals(apexIndex, i, closestEndPos, path,
1873 straightPath, straightPathFlags, straightPathRefs,
1874 straightPathCount, maxStraightPath, options);
1875 }
1876
1877 // Ignore status return value as we're just about to return anyway.
1878 appendVertex(closestEndPos, 0, path[i],
1879 straightPath, straightPathFlags, straightPathRefs,
1880 straightPathCount, maxStraightPath);
1881
1882 return DT_SUCCESS | DT_PARTIAL_RESULT | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0);
1883 }
1884
1885 // If starting really close the portal, advance.
1886 if (i == 0)
1887 {
1888 float t;
1889 if (dtDistancePtSegSqr2D(portalApex, left, right, t) < dtSqr(0.001f))
1890 continue;
1891 }
1892 }
1893 else
1894 {
1895 // End of the path.
1896 dtVcopy(left, closestEndPos);
1897 dtVcopy(right, closestEndPos);
1898
1899 toType = DT_POLYTYPE_GROUND;
1900 }
1901
1902 // Right vertex.
1903 if (dtTriArea2D(portalApex, portalRight, right) <= 0.0f)
1904 {
1905 if (dtVequal(portalApex, portalRight) || dtTriArea2D(portalApex, portalLeft, right) > 0.0f)
1906 {
1907 dtVcopy(portalRight, right);
1908 rightPolyRef = (i+1 < pathSize) ? path[i+1] : 0;
1909 rightPolyType = toType;
1910 rightIndex = i;
1911 }
1912 else
1913 {
1914 // Append portals along the current straight path segment.
1915 if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
1916 {
1917 stat = appendPortals(apexIndex, leftIndex, portalLeft, path,
1918 straightPath, straightPathFlags, straightPathRefs,
1919 straightPathCount, maxStraightPath, options);
1920 if (stat != DT_IN_PROGRESS)
1921 return stat;
1922 }
1923
1924 dtVcopy(portalApex, portalLeft);
1925 apexIndex = leftIndex;
1926
1927 unsigned char flags = 0;
1928 if (!leftPolyRef)
1929 flags = DT_STRAIGHTPATH_END;
1930 else if (leftPolyType == DT_POLYTYPE_OFFMESH_CONNECTION)
1931 flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION;
1932 dtPolyRef ref = leftPolyRef;
1933
1934 // Append or update vertex
1935 stat = appendVertex(portalApex, flags, ref,
1936 straightPath, straightPathFlags, straightPathRefs,
1937 straightPathCount, maxStraightPath);
1938 if (stat != DT_IN_PROGRESS)
1939 return stat;
1940
1941 dtVcopy(portalLeft, portalApex);
1942 dtVcopy(portalRight, portalApex);
1943 leftIndex = apexIndex;
1944 rightIndex = apexIndex;
1945
1946 // Restart
1947 i = apexIndex;
1948
1949 continue;
1950 }
1951 }
1952
1953 // Left vertex.
1954 if (dtTriArea2D(portalApex, portalLeft, left) >= 0.0f)
1955 {
1956 if (dtVequal(portalApex, portalLeft) || dtTriArea2D(portalApex, portalRight, left) < 0.0f)
1957 {
1958 dtVcopy(portalLeft, left);
1959 leftPolyRef = (i+1 < pathSize) ? path[i+1] : 0;
1960 leftPolyType = toType;
1961 leftIndex = i;
1962 }
1963 else
1964 {
1965 // Append portals along the current straight path segment.
1966 if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
1967 {
1968 stat = appendPortals(apexIndex, rightIndex, portalRight, path,
1969 straightPath, straightPathFlags, straightPathRefs,
1970 straightPathCount, maxStraightPath, options);
1971 if (stat != DT_IN_PROGRESS)
1972 return stat;
1973 }
1974
1975 dtVcopy(portalApex, portalRight);
1976 apexIndex = rightIndex;
1977
1978 unsigned char flags = 0;
1979 if (!rightPolyRef)
1980 flags = DT_STRAIGHTPATH_END;
1981 else if (rightPolyType == DT_POLYTYPE_OFFMESH_CONNECTION)
1982 flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION;
1983 dtPolyRef ref = rightPolyRef;
1984
1985 // Append or update vertex
1986 stat = appendVertex(portalApex, flags, ref,
1987 straightPath, straightPathFlags, straightPathRefs,
1988 straightPathCount, maxStraightPath);
1989 if (stat != DT_IN_PROGRESS)
1990 return stat;
1991
1992 dtVcopy(portalLeft, portalApex);
1993 dtVcopy(portalRight, portalApex);
1994 leftIndex = apexIndex;
1995 rightIndex = apexIndex;
1996
1997 // Restart
1998 i = apexIndex;
1999
2000 continue;
2001 }
2002 }
2003 }
2004
2005 // Append portals along the current straight path segment.
2006 if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
2007 {
2008 stat = appendPortals(apexIndex, pathSize-1, closestEndPos, path,
2009 straightPath, straightPathFlags, straightPathRefs,
2010 straightPathCount, maxStraightPath, options);
2011 if (stat != DT_IN_PROGRESS)
2012 return stat;
2013 }
2014 }
2015
2016 // Ignore status return value as we're just about to return anyway.
2017 appendVertex(closestEndPos, DT_STRAIGHTPATH_END, 0,
2018 straightPath, straightPathFlags, straightPathRefs,
2019 straightPathCount, maxStraightPath);
2020
2021 return DT_SUCCESS | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0);
2022 }
2023
2024 /// @par
2025 ///
2026 /// This method is optimized for small delta movement and a small number of
2027 /// polygons. If used for too great a distance, the result set will form an
2028 /// incomplete path.
2029 ///
2030 /// @p resultPos will equal the @p endPos if the end is reached.
2031 /// Otherwise the closest reachable position will be returned.
2032 ///
2033 /// @p resultPos is not projected onto the surface of the navigation
2034 /// mesh. Use #getPolyHeight if this is needed.
2035 ///
2036 /// This method treats the end position in the same manner as
2037 /// the #raycast method. (As a 2D point.) See that method's documentation
2038 /// for details.
2039 ///
2040 /// If the @p visited array is too small to hold the entire result set, it will
2041 /// be filled as far as possible from the start position toward the end
2042 /// position.
2043 ///
2044 dtStatus dtNavMeshQuery::moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos,
2045 const dtQueryFilter* filter,
2046 float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const
2047 {
2048 dtAssert(m_nav);
2049 dtAssert(m_tinyNodePool);
2050
2051 if (!visitedCount)
2052 return DT_FAILURE | DT_INVALID_PARAM;
2053
2054 *visitedCount = 0;
2055
2056 if (!m_nav->isValidPolyRef(startRef) ||
2057 !startPos || !dtVisfinite(startPos) ||
2058 !endPos || !dtVisfinite(endPos) ||
2059 !filter || !resultPos || !visited ||
2060 maxVisitedSize <= 0)
2061 {
2062 return DT_FAILURE | DT_INVALID_PARAM;
2063 }
2064
2065 dtStatus status = DT_SUCCESS;
2066
2067 static const int MAX_STACK = 48;
2068 dtNode* stack[MAX_STACK];
2069 int nstack = 0;
2070
2071 m_tinyNodePool->clear();
2072
2073 dtNode* startNode = m_tinyNodePool->getNode(startRef);
2074 startNode->pidx = 0;
2075 startNode->cost = 0;
2076 startNode->total = 0;
2077 startNode->id = startRef;
2078 startNode->flags = DT_NODE_CLOSED;
2079 stack[nstack++] = startNode;
2080
2081 float bestPos[3];
2082 float bestDist = FLT_MAX;
2083 dtNode* bestNode = 0;
2084 dtVcopy(bestPos, startPos);
2085
2086 // Search constraints
2087 float searchPos[3], searchRadSqr;
2088 dtVlerp(searchPos, startPos, endPos, 0.5f);
2089 searchRadSqr = dtSqr(dtVdist(startPos, endPos)/2.0f + 0.001f);
2090
2091 float verts[DT_VERTS_PER_POLYGON*3];
2092
2093 while (nstack)
2094 {
2095 // Pop front.
2096 dtNode* curNode = stack[0];
2097 for (int i = 0; i < nstack-1; ++i)
2098 stack[i] = stack[i+1];
2099 nstack--;
2100
2101 // Get poly and tile.
2102 // The API input has been cheked already, skip checking internal data.
2103 const dtPolyRef curRef = curNode->id;
2104 const dtMeshTile* curTile = 0;
2105 const dtPoly* curPoly = 0;
2106 m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly);
2107
2108 // Collect vertices.
2109 const int nverts = curPoly->vertCount;
2110 for (int i = 0; i < nverts; ++i)
2111 dtVcopy(&verts[i*3], &curTile->verts[curPoly->verts[i]*3]);
2112
2113 // If target is inside the poly, stop search.
2114 if (dtPointInPolygon(endPos, verts, nverts))
2115 {
2116 bestNode = curNode;
2117 dtVcopy(bestPos, endPos);
2118 break;
2119 }
2120
2121 // Find wall edges and find nearest point inside the walls.
2122 for (int i = 0, j = (int)curPoly->vertCount-1; i < (int)curPoly->vertCount; j = i++)
2123 {
2124 // Find links to neighbours.
2125 static const int MAX_NEIS = 8;
2126 int nneis = 0;
2127 dtPolyRef neis[MAX_NEIS];
2128
2129 if (curPoly->neis[j] & DT_EXT_LINK)
2130 {
2131 // Tile border.
2132 for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next)
2133 {
2134 const dtLink* link = &curTile->links[k];
2135 if (link->edge == j)
2136 {
2137 if (link->ref != 0)
2138 {
2139 const dtMeshTile* neiTile = 0;
2140 const dtPoly* neiPoly = 0;
2141 m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
2142 if (filter->passFilter(link->ref, neiTile, neiPoly))
2143 {
2144 if (nneis < MAX_NEIS)
2145 neis[nneis++] = link->ref;
2146 }
2147 }
2148 }
2149 }
2150 }
2151 else if (curPoly->neis[j])
2152 {
2153 const unsigned int idx = (unsigned int)(curPoly->neis[j]-1);
2154 const dtPolyRef ref = m_nav->getPolyRefBase(curTile) | idx;
2155 if (filter->passFilter(ref, curTile, &curTile->polys[idx]))
2156 {
2157 // Internal edge, encode id.
2158 neis[nneis++] = ref;
2159 }
2160 }
2161
2162 if (!nneis)
2163 {
2164 // Wall edge, calc distance.
2165 const float* vj = &verts[j*3];
2166 const float* vi = &verts[i*3];
2167 float tseg;
2168 const float distSqr = dtDistancePtSegSqr2D(endPos, vj, vi, tseg);
2169 if (distSqr < bestDist)
2170 {
2171 // Update nearest distance.
2172 dtVlerp(bestPos, vj,vi, tseg);
2173 bestDist = distSqr;
2174 bestNode = curNode;
2175 }
2176 }
2177 else
2178 {
2179 for (int k = 0; k < nneis; ++k)
2180 {
2181 // Skip if no node can be allocated.
2182 dtNode* neighbourNode = m_tinyNodePool->getNode(neis[k]);
2183 if (!neighbourNode)
2184 continue;
2185 // Skip if already visited.
2186 if (neighbourNode->flags & DT_NODE_CLOSED)
2187 continue;
2188
2189 // Skip the link if it is too far from search constraint.
2190 // TODO: Maybe should use getPortalPoints(), but this one is way faster.
2191 const float* vj = &verts[j*3];
2192 const float* vi = &verts[i*3];
2193 float tseg;
2194 float distSqr = dtDistancePtSegSqr2D(searchPos, vj, vi, tseg);
2195 if (distSqr > searchRadSqr)
2196 continue;
2197
2198 // Mark as the node as visited and push to queue.
2199 if (nstack < MAX_STACK)
2200 {
2201 neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode);
2202 neighbourNode->flags |= DT_NODE_CLOSED;
2203 stack[nstack++] = neighbourNode;
2204 }
2205 }
2206 }
2207 }
2208 }
2209
2210 int n = 0;
2211 if (bestNode)
2212 {
2213 // Reverse the path.
2214 dtNode* prev = 0;
2215 dtNode* node = bestNode;
2216 do
2217 {
2218 dtNode* next = m_tinyNodePool->getNodeAtIdx(node->pidx);
2219 node->pidx = m_tinyNodePool->getNodeIdx(prev);
2220 prev = node;
2221 node = next;
2222 }
2223 while (node);
2224
2225 // Store result
2226 node = prev;
2227 do
2228 {
2229 visited[n++] = node->id;
2230 if (n >= maxVisitedSize)
2231 {
2232 status |= DT_BUFFER_TOO_SMALL;
2233 break;
2234 }
2235 node = m_tinyNodePool->getNodeAtIdx(node->pidx);
2236 }
2237 while (node);
2238 }
2239
2240 dtVcopy(resultPos, bestPos);
2241
2242 *visitedCount = n;
2243
2244 return status;
2245 }
2246
2247
2248 dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right,
2249 unsigned char& fromType, unsigned char& toType) const
2250 {
2251 dtAssert(m_nav);
2252
2253 const dtMeshTile* fromTile = 0;
2254 const dtPoly* fromPoly = 0;
2255 if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly)))
2256 return DT_FAILURE | DT_INVALID_PARAM;
2257 fromType = fromPoly->getType();
2258
2259 const dtMeshTile* toTile = 0;
2260 const dtPoly* toPoly = 0;
2261 if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly)))
2262 return DT_FAILURE | DT_INVALID_PARAM;
2263 toType = toPoly->getType();
2264
2265 return getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right);
2266 }
2267
2268 // Returns portal points between two polygons.
2269 dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
2270 dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
2271 float* left, float* right) const
2272 {
2273 // Find the link that points to the 'to' polygon.
2274 const dtLink* link = 0;
2275 for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next)
2276 {
2277 if (fromTile->links[i].ref == to)
2278 {
2279 link = &fromTile->links[i];
2280 break;
2281 }
2282 }
2283 if (!link)
2284 return DT_FAILURE | DT_INVALID_PARAM;
2285
2286 // Handle off-mesh connections.
2287 if (fromPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
2288 {
2289 // Find link that points to first vertex.
2290 for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next)
2291 {
2292 if (fromTile->links[i].ref == to)
2293 {
2294 const int v = fromTile->links[i].edge;
2295 dtVcopy(left, &fromTile->verts[fromPoly->verts[v]*3]);
2296 dtVcopy(right, &fromTile->verts[fromPoly->verts[v]*3]);
2297 return DT_SUCCESS;
2298 }
2299 }
2300 return DT_FAILURE | DT_INVALID_PARAM;
2301 }
2302
2303 if (toPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
2304 {
2305 for (unsigned int i = toPoly->firstLink; i != DT_NULL_LINK; i = toTile->links[i].next)
2306 {
2307 if (toTile->links[i].ref == from)
2308 {
2309 const int v = toTile->links[i].edge;
2310 dtVcopy(left, &toTile->verts[toPoly->verts[v]*3]);
2311 dtVcopy(right, &toTile->verts[toPoly->verts[v]*3]);
2312 return DT_SUCCESS;
2313 }
2314 }
2315 return DT_FAILURE | DT_INVALID_PARAM;
2316 }
2317
2318 // Find portal vertices.
2319 const int v0 = fromPoly->verts[link->edge];
2320 const int v1 = fromPoly->verts[(link->edge+1) % (int)fromPoly->vertCount];
2321 dtVcopy(left, &fromTile->verts[v0*3]);
2322 dtVcopy(right, &fromTile->verts[v1*3]);
2323
2324 // If the link is at tile boundary, dtClamp the vertices to
2325 // the link width.
2326 if (link->side != 0xff)
2327 {
2328 // Unpack portal limits.
2329 if (link->bmin != 0 || link->bmax != 255)
2330 {
2331 const float s = 1.0f/255.0f;
2332 const float tmin = link->bmin*s;
2333 const float tmax = link->bmax*s;
2334 dtVlerp(left, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmin);
2335 dtVlerp(right, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmax);
2336 }
2337 }
2338
2339 return DT_SUCCESS;
2340 }
2341
2342 // Returns edge mid point between two polygons.
2343 dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const
2344 {
2345 float left[3], right[3];
2346 unsigned char fromType, toType;
2347 if (dtStatusFailed(getPortalPoints(from, to, left,right, fromType, toType)))
2348 return DT_FAILURE | DT_INVALID_PARAM;
2349 mid[0] = (left[0]+right[0])*0.5f;
2350 mid[1] = (left[1]+right[1])*0.5f;
2351 mid[2] = (left[2]+right[2])*0.5f;
2352 return DT_SUCCESS;
2353 }
2354
2355 dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
2356 dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
2357 float* mid) const
2358 {
2359 float left[3], right[3];
2360 if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right)))
2361 return DT_FAILURE | DT_INVALID_PARAM;
2362 mid[0] = (left[0]+right[0])*0.5f;
2363 mid[1] = (left[1]+right[1])*0.5f;
2364 mid[2] = (left[2]+right[2])*0.5f;
2365 return DT_SUCCESS;
2366 }
2367
2368
2369
2370 /// @par
2371 ///
2372 /// This method is meant to be used for quick, short distance checks.
2373 ///
2374 /// If the path array is too small to hold the result, it will be filled as
2375 /// far as possible from the start postion toward the end position.
2376 ///
2377 /// <b>Using the Hit Parameter (t)</b>
2378 ///
2379 /// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
2380 /// the end position. In this case the path represents a valid corridor to the
2381 /// end position and the value of @p hitNormal is undefined.
2382 ///
2383 /// If the hit parameter is zero, then the start position is on the wall that
2384 /// was hit and the value of @p hitNormal is undefined.
2385 ///
2386 /// If 0 < t < 1.0 then the following applies:
2387 ///
2388 /// @code
2389 /// distanceToHitBorder = distanceToEndPosition * t
2390 /// hitPoint = startPos + (endPos - startPos) * t
2391 /// @endcode
2392 ///
2393 /// <b>Use Case Restriction</b>
2394 ///
2395 /// The raycast ignores the y-value of the end position. (2D check.) This
2396 /// places significant limits on how it can be used. For example:
2397 ///
2398 /// Consider a scene where there is a main floor with a second floor balcony
2399 /// that hangs over the main floor. So the first floor mesh extends below the
2400 /// balcony mesh. The start position is somewhere on the first floor. The end
2401 /// position is on the balcony.
2402 ///
2403 /// The raycast will search toward the end position along the first floor mesh.
2404 /// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
2405 /// (no wall hit), meaning it reached the end position. This is one example of why
2406 /// this method is meant for short distance checks.
2407 ///
2408 dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
2409 const dtQueryFilter* filter,
2410 float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const
2411 {
2412 dtRaycastHit hit;
2413 hit.path = path;
2414 hit.maxPath = maxPath;
2415
2416 dtStatus status = raycast(startRef, startPos, endPos, filter, 0, &hit);
2417
2418 *t = hit.t;
2419 if (hitNormal)
2420 dtVcopy(hitNormal, hit.hitNormal);
2421 if (pathCount)
2422 *pathCount = hit.pathCount;
2423
2424 return status;
2425 }
2426
2427
2428 /// @par
2429 ///
2430 /// This method is meant to be used for quick, short distance checks.
2431 ///
2432 /// If the path array is too small to hold the result, it will be filled as
2433 /// far as possible from the start postion toward the end position.
2434 ///
2435 /// <b>Using the Hit Parameter t of RaycastHit</b>
2436 ///
2437 /// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
2438 /// the end position. In this case the path represents a valid corridor to the
2439 /// end position and the value of @p hitNormal is undefined.
2440 ///
2441 /// If the hit parameter is zero, then the start position is on the wall that
2442 /// was hit and the value of @p hitNormal is undefined.
2443 ///
2444 /// If 0 < t < 1.0 then the following applies:
2445 ///
2446 /// @code
2447 /// distanceToHitBorder = distanceToEndPosition * t
2448 /// hitPoint = startPos + (endPos - startPos) * t
2449 /// @endcode
2450 ///
2451 /// <b>Use Case Restriction</b>
2452 ///
2453 /// The raycast ignores the y-value of the end position. (2D check.) This
2454 /// places significant limits on how it can be used. For example:
2455 ///
2456 /// Consider a scene where there is a main floor with a second floor balcony
2457 /// that hangs over the main floor. So the first floor mesh extends below the
2458 /// balcony mesh. The start position is somewhere on the first floor. The end
2459 /// position is on the balcony.
2460 ///
2461 /// The raycast will search toward the end position along the first floor mesh.
2462 /// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
2463 /// (no wall hit), meaning it reached the end position. This is one example of why
2464 /// this method is meant for short distance checks.
2465 ///
2466 dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
2467 const dtQueryFilter* filter, const unsigned int options,
2468 dtRaycastHit* hit, dtPolyRef prevRef) const
2469 {
2470 dtAssert(m_nav);
2471
2472 if (!hit)
2473 return DT_FAILURE | DT_INVALID_PARAM;
2474
2475 hit->t = 0;
2476 hit->pathCount = 0;
2477 hit->pathCost = 0;
2478
2479 // Validate input
2480 if (!m_nav->isValidPolyRef(startRef) ||
2481 !startPos || !dtVisfinite(startPos) ||
2482 !endPos || !dtVisfinite(endPos) ||
2483 !filter ||
2484 (prevRef && !m_nav->isValidPolyRef(prevRef)))
2485 {
2486 return DT_FAILURE | DT_INVALID_PARAM;
2487 }
2488
2489 float dir[3], curPos[3], lastPos[3];
2490 float verts[DT_VERTS_PER_POLYGON*3+3];
2491 int n = 0;
2492
2493 dtVcopy(curPos, startPos);
2494 dtVsub(dir, endPos, startPos);
2495 dtVset(hit->hitNormal, 0, 0, 0);
2496
2497 dtStatus status = DT_SUCCESS;
2498
2499 const dtMeshTile* prevTile, *tile, *nextTile;
2500 const dtPoly* prevPoly, *poly, *nextPoly;
2501 dtPolyRef curRef;
2502
2503 // The API input has been checked already, skip checking internal data.
2504 curRef = startRef;
2505 tile = 0;
2506 poly = 0;
2507 m_nav->getTileAndPolyByRefUnsafe(curRef, &tile, &poly);
2508 nextTile = prevTile = tile;
2509 nextPoly = prevPoly = poly;
2510 if (prevRef)
2511 m_nav->getTileAndPolyByRefUnsafe(prevRef, &prevTile, &prevPoly);
2512
2513 while (curRef)
2514 {
2515 // Cast ray against current polygon.
2516
2517 // Collect vertices.
2518 int nv = 0;
2519 for (int i = 0; i < (int)poly->vertCount; ++i)
2520 {
2521 dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]);
2522 nv++;
2523 }
2524
2525 float tmin, tmax;
2526 int segMin, segMax;
2527 if (!dtIntersectSegmentPoly2D(startPos, endPos, verts, nv, tmin, tmax, segMin, segMax))
2528 {
2529 // Could not hit the polygon, keep the old t and report hit.
2530 hit->pathCount = n;
2531 return status;
2532 }
2533
2534 hit->hitEdgeIndex = segMax;
2535
2536 // Keep track of furthest t so far.
2537 if (tmax > hit->t)
2538 hit->t = tmax;
2539
2540 // Store visited polygons.
2541 if (n < hit->maxPath)
2542 hit->path[n++] = curRef;
2543 else
2544 status |= DT_BUFFER_TOO_SMALL;
2545
2546 // Ray end is completely inside the polygon.
2547 if (segMax == -1)
2548 {
2549 hit->t = FLT_MAX;
2550 hit->pathCount = n;
2551
2552 // add the cost
2553 if (options & DT_RAYCAST_USE_COSTS)
2554 hit->pathCost += filter->getCost(curPos, endPos, prevRef, prevTile, prevPoly, curRef, tile, poly, curRef, tile, poly);
2555 return status;
2556 }
2557
2558 // Follow neighbours.
2559 dtPolyRef nextRef = 0;
2560
2561 for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next)
2562 {
2563 const dtLink* link = &tile->links[i];
2564
2565 // Find link which contains this edge.
2566 if ((int)link->edge != segMax)
2567 continue;
2568
2569 // Get pointer to the next polygon.
2570 nextTile = 0;
2571 nextPoly = 0;
2572 m_nav->getTileAndPolyByRefUnsafe(link->ref, &nextTile, &nextPoly);
2573
2574 // Skip off-mesh connections.
2575 if (nextPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
2576 continue;
2577
2578 // Skip links based on filter.
2579 if (!filter->passFilter(link->ref, nextTile, nextPoly))
2580 continue;
2581
2582 // If the link is internal, just return the ref.
2583 if (link->side == 0xff)
2584 {
2585 nextRef = link->ref;
2586 break;
2587 }
2588
2589 // If the link is at tile boundary,
2590
2591 // Check if the link spans the whole edge, and accept.
2592 if (link->bmin == 0 && link->bmax == 255)
2593 {
2594 nextRef = link->ref;
2595 break;
2596 }
2597
2598 // Check for partial edge links.
2599 const int v0 = poly->verts[link->edge];
2600 const int v1 = poly->verts[(link->edge+1) % poly->vertCount];
2601 const float* left = &tile->verts[v0*3];
2602 const float* right = &tile->verts[v1*3];
2603
2604 // Check that the intersection lies inside the link portal.
2605 if (link->side == 0 || link->side == 4)
2606 {
2607 // Calculate link size.
2608 const float s = 1.0f/255.0f;
2609 float lmin = left[2] + (right[2] - left[2])*(link->bmin*s);
2610 float lmax = left[2] + (right[2] - left[2])*(link->bmax*s);
2611 if (lmin > lmax) dtSwap(lmin, lmax);
2612
2613 // Find Z intersection.
2614 float z = startPos[2] + (endPos[2]-startPos[2])*tmax;
2615 if (z >= lmin && z <= lmax)
2616 {
2617 nextRef = link->ref;
2618 break;
2619 }
2620 }
2621 else if (link->side == 2 || link->side == 6)
2622 {
2623 // Calculate link size.
2624 const float s = 1.0f/255.0f;
2625 float lmin = left[0] + (right[0] - left[0])*(link->bmin*s);
2626 float lmax = left[0] + (right[0] - left[0])*(link->bmax*s);
2627 if (lmin > lmax) dtSwap(lmin, lmax);
2628
2629 // Find X intersection.
2630 float x = startPos[0] + (endPos[0]-startPos[0])*tmax;
2631 if (x >= lmin && x <= lmax)
2632 {
2633 nextRef = link->ref;
2634 break;
2635 }
2636 }
2637 }
2638
2639 // add the cost
2640 if (options & DT_RAYCAST_USE_COSTS)
2641 {
2642 // compute the intersection point at the furthest end of the polygon
2643 // and correct the height (since the raycast moves in 2d)
2644 dtVcopy(lastPos, curPos);
2645 dtVmad(curPos, startPos, dir, hit->t);
2646 float* e1 = &verts[segMax*3];
2647 float* e2 = &verts[((segMax+1)%nv)*3];
2648 float eDir[3], diff[3];
2649 dtVsub(eDir, e2, e1);
2650 dtVsub(diff, curPos, e1);
2651 float s = dtSqr(eDir[0]) > dtSqr(eDir[2]) ? diff[0] / eDir[0] : diff[2] / eDir[2];
2652 curPos[1] = e1[1] + eDir[1] * s;
2653
2654 hit->pathCost += filter->getCost(lastPos, curPos, prevRef, prevTile, prevPoly, curRef, tile, poly, nextRef, nextTile, nextPoly);
2655 }
2656
2657 if (!nextRef)
2658 {
2659 // No neighbour, we hit a wall.
2660
2661 // Calculate hit normal.
2662 const int a = segMax;
2663 const int b = segMax+1 < nv ? segMax+1 : 0;
2664 const float* va = &verts[a*3];
2665 const float* vb = &verts[b*3];
2666 const float dx = vb[0] - va[0];
2667 const float dz = vb[2] - va[2];
2668 hit->hitNormal[0] = dz;
2669 hit->hitNormal[1] = 0;
2670 hit->hitNormal[2] = -dx;
2671 dtVnormalize(hit->hitNormal);
2672
2673 hit->pathCount = n;
2674 return status;
2675 }
2676
2677 // No hit, advance to neighbour polygon.
2678 prevRef = curRef;
2679 curRef = nextRef;
2680 prevTile = tile;
2681 tile = nextTile;
2682 prevPoly = poly;
2683 poly = nextPoly;
2684 }
2685
2686 hit->pathCount = n;
2687
2688 return status;
2689 }
2690
2691 /// @par
2692 ///
2693 /// At least one result array must be provided.
2694 ///
2695 /// The order of the result set is from least to highest cost to reach the polygon.
2696 ///
2697 /// A common use case for this method is to perform Dijkstra searches.
2698 /// Candidate polygons are found by searching the graph beginning at the start polygon.
2699 ///
2700 /// If a polygon is not found via the graph search, even if it intersects the
2701 /// search circle, it will not be included in the result set. For example:
2702 ///
2703 /// polyA is the start polygon.
2704 /// polyB shares an edge with polyA. (Is adjacent.)
2705 /// polyC shares an edge with polyB, but not with polyA
2706 /// Even if the search circle overlaps polyC, it will not be included in the
2707 /// result set unless polyB is also in the set.
2708 ///
2709 /// The value of the center point is used as the start position for cost
2710 /// calculations. It is not projected onto the surface of the mesh, so its
2711 /// y-value will effect the costs.
2712 ///
2713 /// Intersection tests occur in 2D. All polygons and the search circle are
2714 /// projected onto the xz-plane. So the y-value of the center point does not
2715 /// effect intersection tests.
2716 ///
2717 /// If the result arrays are to small to hold the entire result set, they will be
2718 /// filled to capacity.
2719 ///
2720 dtStatus dtNavMeshQuery::findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius,
2721 const dtQueryFilter* filter,
2722 dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
2723 int* resultCount, const int maxResult) const
2724 {
2725 dtAssert(m_nav);
2726 dtAssert(m_nodePool);
2727 dtAssert(m_openList);
2728
2729 if (!resultCount)
2730 return DT_FAILURE | DT_INVALID_PARAM;
2731
2732 *resultCount = 0;
2733
2734 if (!m_nav->isValidPolyRef(startRef) ||
2735 !centerPos || !dtVisfinite(centerPos) ||
2736 radius < 0 || !dtMathIsfinite(radius) ||
2737 !filter || maxResult < 0)
2738 {
2739 return DT_FAILURE | DT_INVALID_PARAM;
2740 }
2741
2742 m_nodePool->clear();
2743 m_openList->clear();
2744
2745 dtNode* startNode = m_nodePool->getNode(startRef);
2746 dtVcopy(startNode->pos, centerPos);
2747 startNode->pidx = 0;
2748 startNode->cost = 0;
2749 startNode->total = 0;
2750 startNode->id = startRef;
2751 startNode->flags = DT_NODE_OPEN;
2752 m_openList->push(startNode);
2753
2754 dtStatus status = DT_SUCCESS;
2755
2756 int n = 0;
2757
2758 const float radiusSqr = dtSqr(radius);
2759
2760 while (!m_openList->empty())
2761 {
2762 dtNode* bestNode = m_openList->pop();
2763 bestNode->flags &= ~DT_NODE_OPEN;
2764 bestNode->flags |= DT_NODE_CLOSED;
2765
2766 // Get poly and tile.
2767 // The API input has been cheked already, skip checking internal data.
2768 const dtPolyRef bestRef = bestNode->id;
2769 const dtMeshTile* bestTile = 0;
2770 const dtPoly* bestPoly = 0;
2771 m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
2772
2773 // Get parent poly and tile.
2774 dtPolyRef parentRef = 0;
2775 const dtMeshTile* parentTile = 0;
2776 const dtPoly* parentPoly = 0;
2777 if (bestNode->pidx)
2778 parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
2779 if (parentRef)
2780 m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
2781
2782 if (n < maxResult)
2783 {
2784 if (resultRef)
2785 resultRef[n] = bestRef;
2786 if (resultParent)
2787 resultParent[n] = parentRef;
2788 if (resultCost)
2789 resultCost[n] = bestNode->total;
2790 ++n;
2791 }
2792 else
2793 {
2794 status |= DT_BUFFER_TOO_SMALL;
2795 }
2796
2797 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
2798 {
2799 const dtLink* link = &bestTile->links[i];
2800 dtPolyRef neighbourRef = link->ref;
2801 // Skip invalid neighbours and do not follow back to parent.
2802 if (!neighbourRef || neighbourRef == parentRef)
2803 continue;
2804
2805 // Expand to neighbour
2806 const dtMeshTile* neighbourTile = 0;
2807 const dtPoly* neighbourPoly = 0;
2808 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
2809
2810 // Do not advance if the polygon is excluded by the filter.
2811 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
2812 continue;
2813
2814 // Find edge and calc distance to the edge.
2815 float va[3], vb[3];
2816 if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
2817 continue;
2818
2819 // If the circle is not touching the next polygon, skip it.
2820 float tseg;
2821 float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
2822 if (distSqr > radiusSqr)
2823 continue;
2824
2825 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
2826 if (!neighbourNode)
2827 {
2828 status |= DT_OUT_OF_NODES;
2829 continue;
2830 }
2831
2832 if (neighbourNode->flags & DT_NODE_CLOSED)
2833 continue;
2834
2835 // Cost
2836 if (neighbourNode->flags == 0)
2837 dtVlerp(neighbourNode->pos, va, vb, 0.5f);
2838
2839 float cost = filter->getCost(
2840 bestNode->pos, neighbourNode->pos,
2841 parentRef, parentTile, parentPoly,
2842 bestRef, bestTile, bestPoly,
2843 neighbourRef, neighbourTile, neighbourPoly);
2844
2845 const float total = bestNode->total + cost;
2846
2847 // The node is already in open list and the new result is worse, skip.
2848 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
2849 continue;
2850
2851 neighbourNode->id = neighbourRef;
2852 neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
2853 neighbourNode->total = total;
2854
2855 if (neighbourNode->flags & DT_NODE_OPEN)
2856 {
2857 m_openList->modify(neighbourNode);
2858 }
2859 else
2860 {
2861 neighbourNode->flags = DT_NODE_OPEN;
2862 m_openList->push(neighbourNode);
2863 }
2864 }
2865 }
2866
2867 *resultCount = n;
2868
2869 return status;
2870 }
2871
2872 /// @par
2873 ///
2874 /// The order of the result set is from least to highest cost.
2875 ///
2876 /// At least one result array must be provided.
2877 ///
2878 /// A common use case for this method is to perform Dijkstra searches.
2879 /// Candidate polygons are found by searching the graph beginning at the start
2880 /// polygon.
2881 ///
2882 /// The same intersection test restrictions that apply to findPolysAroundCircle()
2883 /// method apply to this method.
2884 ///
2885 /// The 3D centroid of the search polygon is used as the start position for cost
2886 /// calculations.
2887 ///
2888 /// Intersection tests occur in 2D. All polygons are projected onto the
2889 /// xz-plane. So the y-values of the vertices do not effect intersection tests.
2890 ///
2891 /// If the result arrays are is too small to hold the entire result set, they will
2892 /// be filled to capacity.
2893 ///
2894 dtStatus dtNavMeshQuery::findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts,
2895 const dtQueryFilter* filter,
2896 dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
2897 int* resultCount, const int maxResult) const
2898 {
2899 dtAssert(m_nav);
2900 dtAssert(m_nodePool);
2901 dtAssert(m_openList);
2902
2903 if (!resultCount)
2904 return DT_FAILURE | DT_INVALID_PARAM;
2905
2906 *resultCount = 0;
2907
2908 if (!m_nav->isValidPolyRef(startRef) ||
2909 !verts || nverts < 3 ||
2910 !filter || maxResult < 0)
2911 {
2912 return DT_FAILURE | DT_INVALID_PARAM;
2913 }
2914
2915 // Validate input
2916 if (!startRef || !m_nav->isValidPolyRef(startRef))
2917 return DT_FAILURE | DT_INVALID_PARAM;
2918
2919 m_nodePool->clear();
2920 m_openList->clear();
2921
2922 float centerPos[3] = {0,0,0};
2923 for (int i = 0; i < nverts; ++i)
2924 dtVadd(centerPos,centerPos,&verts[i*3]);
2925 dtVscale(centerPos,centerPos,1.0f/nverts);
2926
2927 dtNode* startNode = m_nodePool->getNode(startRef);
2928 dtVcopy(startNode->pos, centerPos);
2929 startNode->pidx = 0;
2930 startNode->cost = 0;
2931 startNode->total = 0;
2932 startNode->id = startRef;
2933 startNode->flags = DT_NODE_OPEN;
2934 m_openList->push(startNode);
2935
2936 dtStatus status = DT_SUCCESS;
2937
2938 int n = 0;
2939
2940 while (!m_openList->empty())
2941 {
2942 dtNode* bestNode = m_openList->pop();
2943 bestNode->flags &= ~DT_NODE_OPEN;
2944 bestNode->flags |= DT_NODE_CLOSED;
2945
2946 // Get poly and tile.
2947 // The API input has been cheked already, skip checking internal data.
2948 const dtPolyRef bestRef = bestNode->id;
2949 const dtMeshTile* bestTile = 0;
2950 const dtPoly* bestPoly = 0;
2951 m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
2952
2953 // Get parent poly and tile.
2954 dtPolyRef parentRef = 0;
2955 const dtMeshTile* parentTile = 0;
2956 const dtPoly* parentPoly = 0;
2957 if (bestNode->pidx)
2958 parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
2959 if (parentRef)
2960 m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
2961
2962 if (n < maxResult)
2963 {
2964 if (resultRef)
2965 resultRef[n] = bestRef;
2966 if (resultParent)
2967 resultParent[n] = parentRef;
2968 if (resultCost)
2969 resultCost[n] = bestNode->total;
2970
2971 ++n;
2972 }
2973 else
2974 {
2975 status |= DT_BUFFER_TOO_SMALL;
2976 }
2977
2978 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
2979 {
2980 const dtLink* link = &bestTile->links[i];
2981 dtPolyRef neighbourRef = link->ref;
2982 // Skip invalid neighbours and do not follow back to parent.
2983 if (!neighbourRef || neighbourRef == parentRef)
2984 continue;
2985
2986 // Expand to neighbour
2987 const dtMeshTile* neighbourTile = 0;
2988 const dtPoly* neighbourPoly = 0;
2989 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
2990
2991 // Do not advance if the polygon is excluded by the filter.
2992 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
2993 continue;
2994
2995 // Find edge and calc distance to the edge.
2996 float va[3], vb[3];
2997 if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
2998 continue;
2999
3000 // If the poly is not touching the edge to the next polygon, skip the connection it.
3001 float tmin, tmax;
3002 int segMin, segMax;
3003 if (!dtIntersectSegmentPoly2D(va, vb, verts, nverts, tmin, tmax, segMin, segMax))
3004 continue;
3005 if (tmin > 1.0f || tmax < 0.0f)
3006 continue;
3007
3008 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
3009 if (!neighbourNode)
3010 {
3011 status |= DT_OUT_OF_NODES;
3012 continue;
3013 }
3014
3015 if (neighbourNode->flags & DT_NODE_CLOSED)
3016 continue;
3017
3018 // Cost
3019 if (neighbourNode->flags == 0)
3020 dtVlerp(neighbourNode->pos, va, vb, 0.5f);
3021
3022 float cost = filter->getCost(
3023 bestNode->pos, neighbourNode->pos,
3024 parentRef, parentTile, parentPoly,
3025 bestRef, bestTile, bestPoly,
3026 neighbourRef, neighbourTile, neighbourPoly);
3027
3028 const float total = bestNode->total + cost;
3029
3030 // The node is already in open list and the new result is worse, skip.
3031 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
3032 continue;
3033
3034 neighbourNode->id = neighbourRef;
3035 neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
3036 neighbourNode->total = total;
3037
3038 if (neighbourNode->flags & DT_NODE_OPEN)
3039 {
3040 m_openList->modify(neighbourNode);
3041 }
3042 else
3043 {
3044 neighbourNode->flags = DT_NODE_OPEN;
3045 m_openList->push(neighbourNode);
3046 }
3047 }
3048 }
3049
3050 *resultCount = n;
3051
3052 return status;
3053 }
3054
3055 dtStatus dtNavMeshQuery::getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const
3056 {
3057 if (!m_nav->isValidPolyRef(endRef) || !path || !pathCount || maxPath < 0)
3058 return DT_FAILURE | DT_INVALID_PARAM;
3059
3060 *pathCount = 0;
3061
3062 dtNode* endNode;
3063 if (m_nodePool->findNodes(endRef, &endNode, 1) != 1 ||
3064 (endNode->flags & DT_NODE_CLOSED) == 0)
3065 return DT_FAILURE | DT_INVALID_PARAM;
3066
3067 return getPathToNode(endNode, path, pathCount, maxPath);
3068 }
3069
3070 /// @par
3071 ///
3072 /// This method is optimized for a small search radius and small number of result
3073 /// polygons.
3074 ///
3075 /// Candidate polygons are found by searching the navigation graph beginning at
3076 /// the start polygon.
3077 ///
3078 /// The same intersection test restrictions that apply to the findPolysAroundCircle
3079 /// mehtod applies to this method.
3080 ///
3081 /// The value of the center point is used as the start point for cost calculations.
3082 /// It is not projected onto the surface of the mesh, so its y-value will effect
3083 /// the costs.
3084 ///
3085 /// Intersection tests occur in 2D. All polygons and the search circle are
3086 /// projected onto the xz-plane. So the y-value of the center point does not
3087 /// effect intersection tests.
3088 ///
3089 /// If the result arrays are is too small to hold the entire result set, they will
3090 /// be filled to capacity.
3091 ///
3092 dtStatus dtNavMeshQuery::findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius,
3093 const dtQueryFilter* filter,
3094 dtPolyRef* resultRef, dtPolyRef* resultParent,
3095 int* resultCount, const int maxResult) const
3096 {
3097 dtAssert(m_nav);
3098 dtAssert(m_tinyNodePool);
3099
3100 if (!resultCount)
3101 return DT_FAILURE | DT_INVALID_PARAM;
3102
3103 *resultCount = 0;
3104
3105 if (!m_nav->isValidPolyRef(startRef) ||
3106 !centerPos || !dtVisfinite(centerPos) ||
3107 radius < 0 || !dtMathIsfinite(radius) ||
3108 !filter || maxResult < 0)
3109 {
3110 return DT_FAILURE | DT_INVALID_PARAM;
3111 }
3112
3113 static const int MAX_STACK = 48;
3114 dtNode* stack[MAX_STACK];
3115 int nstack = 0;
3116
3117 m_tinyNodePool->clear();
3118
3119 dtNode* startNode = m_tinyNodePool->getNode(startRef);
3120 startNode->pidx = 0;
3121 startNode->id = startRef;
3122 startNode->flags = DT_NODE_CLOSED;
3123 stack[nstack++] = startNode;
3124
3125 const float radiusSqr = dtSqr(radius);
3126
3127 float pa[DT_VERTS_PER_POLYGON*3];
3128 float pb[DT_VERTS_PER_POLYGON*3];
3129
3130 dtStatus status = DT_SUCCESS;
3131
3132 int n = 0;
3133 if (n < maxResult)
3134 {
3135 resultRef[n] = startNode->id;
3136 if (resultParent)
3137 resultParent[n] = 0;
3138 ++n;
3139 }
3140 else
3141 {
3142 status |= DT_BUFFER_TOO_SMALL;
3143 }
3144
3145 while (nstack)
3146 {
3147 // Pop front.
3148 dtNode* curNode = stack[0];
3149 for (int i = 0; i < nstack-1; ++i)
3150 stack[i] = stack[i+1];
3151 nstack--;
3152
3153 // Get poly and tile.
3154 // The API input has been cheked already, skip checking internal data.
3155 const dtPolyRef curRef = curNode->id;
3156 const dtMeshTile* curTile = 0;
3157 const dtPoly* curPoly = 0;
3158 m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly);
3159
3160 for (unsigned int i = curPoly->firstLink; i != DT_NULL_LINK; i = curTile->links[i].next)
3161 {
3162 const dtLink* link = &curTile->links[i];
3163 dtPolyRef neighbourRef = link->ref;
3164 // Skip invalid neighbours.
3165 if (!neighbourRef)
3166 continue;
3167
3168 // Skip if cannot alloca more nodes.
3169 dtNode* neighbourNode = m_tinyNodePool->getNode(neighbourRef);
3170 if (!neighbourNode)
3171 continue;
3172 // Skip visited.
3173 if (neighbourNode->flags & DT_NODE_CLOSED)
3174 continue;
3175
3176 // Expand to neighbour
3177 const dtMeshTile* neighbourTile = 0;
3178 const dtPoly* neighbourPoly = 0;
3179 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
3180
3181 // Skip off-mesh connections.
3182 if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
3183 continue;
3184
3185 // Do not advance if the polygon is excluded by the filter.
3186 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
3187 continue;
3188
3189 // Find edge and calc distance to the edge.
3190 float va[3], vb[3];
3191 if (!getPortalPoints(curRef, curPoly, curTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
3192 continue;
3193
3194 // If the circle is not touching the next polygon, skip it.
3195 float tseg;
3196 float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
3197 if (distSqr > radiusSqr)
3198 continue;
3199
3200 // Mark node visited, this is done before the overlap test so that
3201 // we will not visit the poly again if the test fails.
3202 neighbourNode->flags |= DT_NODE_CLOSED;
3203 neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode);
3204
3205 // Check that the polygon does not collide with existing polygons.
3206
3207 // Collect vertices of the neighbour poly.
3208 const int npa = neighbourPoly->vertCount;
3209 for (int k = 0; k < npa; ++k)
3210 dtVcopy(&pa[k*3], &neighbourTile->verts[neighbourPoly->verts[k]*3]);
3211
3212 bool overlap = false;
3213 for (int j = 0; j < n; ++j)
3214 {
3215 dtPolyRef pastRef = resultRef[j];
3216
3217 // Connected polys do not overlap.
3218 bool connected = false;
3219 for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next)
3220 {
3221 if (curTile->links[k].ref == pastRef)
3222 {
3223 connected = true;
3224 break;
3225 }
3226 }
3227 if (connected)
3228 continue;
3229
3230 // Potentially overlapping.
3231 const dtMeshTile* pastTile = 0;
3232 const dtPoly* pastPoly = 0;
3233 m_nav->getTileAndPolyByRefUnsafe(pastRef, &pastTile, &pastPoly);
3234
3235 // Get vertices and test overlap
3236 const int npb = pastPoly->vertCount;
3237 for (int k = 0; k < npb; ++k)
3238 dtVcopy(&pb[k*3], &pastTile->verts[pastPoly->verts[k]*3]);
3239
3240 if (dtOverlapPolyPoly2D(pa,npa, pb,npb))
3241 {
3242 overlap = true;
3243 break;
3244 }
3245 }
3246 if (overlap)
3247 continue;
3248
3249 // This poly is fine, store and advance to the poly.
3250 if (n < maxResult)
3251 {
3252 resultRef[n] = neighbourRef;
3253 if (resultParent)
3254 resultParent[n] = curRef;
3255 ++n;
3256 }
3257 else
3258 {
3259 status |= DT_BUFFER_TOO_SMALL;
3260 }
3261
3262 if (nstack < MAX_STACK)
3263 {
3264 stack[nstack++] = neighbourNode;
3265 }
3266 }
3267 }
3268
3269 *resultCount = n;
3270
3271 return status;
3272 }
3273
3274
3275 struct dtSegInterval
3276 {
3277 dtPolyRef ref;
3278 short tmin, tmax;
3279 };
3280
3281 static void insertInterval(dtSegInterval* ints, int& nints, const int maxInts,
3282 const short tmin, const short tmax, const dtPolyRef ref)
3283 {
3284 if (nints+1 > maxInts) return;
3285 // Find insertion point.
3286 int idx = 0;
3287 while (idx < nints)
3288 {
3289 if (tmax <= ints[idx].tmin)
3290 break;
3291 idx++;
3292 }
3293 // Move current results.
3294 if (nints-idx)
3295 memmove(ints+idx+1, ints+idx, sizeof(dtSegInterval)*(nints-idx));
3296 // Store
3297 ints[idx].ref = ref;
3298 ints[idx].tmin = tmin;
3299 ints[idx].tmax = tmax;
3300 nints++;
3301 }
3302
3303 /// @par
3304 ///
3305 /// If the @p segmentRefs parameter is provided, then all polygon segments will be returned.
3306 /// Otherwise only the wall segments are returned.
3307 ///
3308 /// A segment that is normally a portal will be included in the result set as a
3309 /// wall if the @p filter results in the neighbor polygon becoomming impassable.
3310 ///
3311 /// The @p segmentVerts and @p segmentRefs buffers should normally be sized for the
3312 /// maximum segments per polygon of the source navigation mesh.
3313 ///
3314 dtStatus dtNavMeshQuery::getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter,
3315 float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount,
3316 const int maxSegments) const
3317 {
3318 dtAssert(m_nav);
3319
3320 if (!segmentCount)
3321 return DT_FAILURE | DT_INVALID_PARAM;
3322
3323 *segmentCount = 0;
3324
3325 const dtMeshTile* tile = 0;
3326 const dtPoly* poly = 0;
3327 if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
3328 return DT_FAILURE | DT_INVALID_PARAM;
3329
3330 if (!filter || !segmentVerts || maxSegments < 0)
3331 return DT_FAILURE | DT_INVALID_PARAM;
3332
3333 int n = 0;
3334 static const int MAX_INTERVAL = 16;
3335 dtSegInterval ints[MAX_INTERVAL];
3336 int nints;
3337
3338 const bool storePortals = segmentRefs != 0;
3339
3340 dtStatus status = DT_SUCCESS;
3341
3342 for (int i = 0, j = (int)poly->vertCount-1; i < (int)poly->vertCount; j = i++)
3343 {
3344 // Skip non-solid edges.
3345 nints = 0;
3346 if (poly->neis[j] & DT_EXT_LINK)
3347 {
3348 // Tile border.
3349 for (unsigned int k = poly->firstLink; k != DT_NULL_LINK; k = tile->links[k].next)
3350 {
3351 const dtLink* link = &tile->links[k];
3352 if (link->edge == j)
3353 {
3354 if (link->ref != 0)
3355 {
3356 const dtMeshTile* neiTile = 0;
3357 const dtPoly* neiPoly = 0;
3358 m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
3359 if (filter->passFilter(link->ref, neiTile, neiPoly))
3360 {
3361 insertInterval(ints, nints, MAX_INTERVAL, link->bmin, link->bmax, link->ref);
3362 }
3363 }
3364 }
3365 }
3366 }
3367 else
3368 {
3369 // Internal edge
3370 dtPolyRef neiRef = 0;
3371 if (poly->neis[j])
3372 {
3373 const unsigned int idx = (unsigned int)(poly->neis[j]-1);
3374 neiRef = m_nav->getPolyRefBase(tile) | idx;
3375 if (!filter->passFilter(neiRef, tile, &tile->polys[idx]))
3376 neiRef = 0;
3377 }
3378
3379 // If the edge leads to another polygon and portals are not stored, skip.
3380 if (neiRef != 0 && !storePortals)
3381 continue;
3382
3383 if (n < maxSegments)
3384 {
3385 const float* vj = &tile->verts[poly->verts[j]*3];
3386 const float* vi = &tile->verts[poly->verts[i]*3];
3387 float* seg = &segmentVerts[n*6];
3388 dtVcopy(seg+0, vj);
3389 dtVcopy(seg+3, vi);
3390 if (segmentRefs)
3391 segmentRefs[n] = neiRef;
3392 n++;
3393 }
3394 else
3395 {
3396 status |= DT_BUFFER_TOO_SMALL;
3397 }
3398
3399 continue;
3400 }
3401
3402 // Add sentinels
3403 insertInterval(ints, nints, MAX_INTERVAL, -1, 0, 0);
3404 insertInterval(ints, nints, MAX_INTERVAL, 255, 256, 0);
3405
3406 // Store segments.
3407 const float* vj = &tile->verts[poly->verts[j]*3];
3408 const float* vi = &tile->verts[poly->verts[i]*3];
3409 for (int k = 1; k < nints; ++k)
3410 {
3411 // Portal segment.
3412 if (storePortals && ints[k].ref)
3413 {
3414 const float tmin = ints[k].tmin/255.0f;
3415 const float tmax = ints[k].tmax/255.0f;
3416 if (n < maxSegments)
3417 {
3418 float* seg = &segmentVerts[n*6];
3419 dtVlerp(seg+0, vj,vi, tmin);
3420 dtVlerp(seg+3, vj,vi, tmax);
3421 if (segmentRefs)
3422 segmentRefs[n] = ints[k].ref;
3423 n++;
3424 }
3425 else
3426 {
3427 status |= DT_BUFFER_TOO_SMALL;
3428 }
3429 }
3430
3431 // Wall segment.
3432 const int imin = ints[k-1].tmax;
3433 const int imax = ints[k].tmin;
3434 if (imin != imax)
3435 {
3436 const float tmin = imin/255.0f;
3437 const float tmax = imax/255.0f;
3438 if (n < maxSegments)
3439 {
3440 float* seg = &segmentVerts[n*6];
3441 dtVlerp(seg+0, vj,vi, tmin);
3442 dtVlerp(seg+3, vj,vi, tmax);
3443 if (segmentRefs)
3444 segmentRefs[n] = 0;
3445 n++;
3446 }
3447 else
3448 {
3449 status |= DT_BUFFER_TOO_SMALL;
3450 }
3451 }
3452 }
3453 }
3454
3455 *segmentCount = n;
3456
3457 return status;
3458 }
3459
3460 /// @par
3461 ///
3462 /// @p hitPos is not adjusted using the height detail data.
3463 ///
3464 /// @p hitDist will equal the search radius if there is no wall within the
3465 /// radius. In this case the values of @p hitPos and @p hitNormal are
3466 /// undefined.
3467 ///
3468 /// The normal will become unpredicable if @p hitDist is a very small number.
3469 ///
3470 dtStatus dtNavMeshQuery::findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius,
3471 const dtQueryFilter* filter,
3472 float* hitDist, float* hitPos, float* hitNormal) const
3473 {
3474 dtAssert(m_nav);
3475 dtAssert(m_nodePool);
3476 dtAssert(m_openList);
3477
3478 // Validate input
3479 if (!m_nav->isValidPolyRef(startRef) ||
3480 !centerPos || !dtVisfinite(centerPos) ||
3481 maxRadius < 0 || !dtMathIsfinite(maxRadius) ||
3482 !filter || !hitDist || !hitPos || !hitNormal)
3483 {
3484 return DT_FAILURE | DT_INVALID_PARAM;
3485 }
3486
3487 m_nodePool->clear();
3488 m_openList->clear();
3489
3490 dtNode* startNode = m_nodePool->getNode(startRef);
3491 dtVcopy(startNode->pos, centerPos);
3492 startNode->pidx = 0;
3493 startNode->cost = 0;
3494 startNode->total = 0;
3495 startNode->id = startRef;
3496 startNode->flags = DT_NODE_OPEN;
3497 m_openList->push(startNode);
3498
3499 float radiusSqr = dtSqr(maxRadius);
3500
3501 dtStatus status = DT_SUCCESS;
3502
3503 while (!m_openList->empty())
3504 {
3505 dtNode* bestNode = m_openList->pop();
3506 bestNode->flags &= ~DT_NODE_OPEN;
3507 bestNode->flags |= DT_NODE_CLOSED;
3508
3509 // Get poly and tile.
3510 // The API input has been cheked already, skip checking internal data.
3511 const dtPolyRef bestRef = bestNode->id;
3512 const dtMeshTile* bestTile = 0;
3513 const dtPoly* bestPoly = 0;
3514 m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
3515
3516 // Get parent poly and tile.
3517 dtPolyRef parentRef = 0;
3518 const dtMeshTile* parentTile = 0;
3519 const dtPoly* parentPoly = 0;
3520 if (bestNode->pidx)
3521 parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
3522 if (parentRef)
3523 m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
3524
3525 // Hit test walls.
3526 for (int i = 0, j = (int)bestPoly->vertCount-1; i < (int)bestPoly->vertCount; j = i++)
3527 {
3528 // Skip non-solid edges.
3529 if (bestPoly->neis[j] & DT_EXT_LINK)
3530 {
3531 // Tile border.
3532 bool solid = true;
3533 for (unsigned int k = bestPoly->firstLink; k != DT_NULL_LINK; k = bestTile->links[k].next)
3534 {
3535 const dtLink* link = &bestTile->links[k];
3536 if (link->edge == j)
3537 {
3538 if (link->ref != 0)
3539 {
3540 const dtMeshTile* neiTile = 0;
3541 const dtPoly* neiPoly = 0;
3542 m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
3543 if (filter->passFilter(link->ref, neiTile, neiPoly))
3544 solid = false;
3545 }
3546 break;
3547 }
3548 }
3549 if (!solid) continue;
3550 }
3551 else if (bestPoly->neis[j])
3552 {
3553 // Internal edge
3554 const unsigned int idx = (unsigned int)(bestPoly->neis[j]-1);
3555 const dtPolyRef ref = m_nav->getPolyRefBase(bestTile) | idx;
3556 if (filter->passFilter(ref, bestTile, &bestTile->polys[idx]))
3557 continue;
3558 }
3559
3560 // Calc distance to the edge.
3561 const float* vj = &bestTile->verts[bestPoly->verts[j]*3];
3562 const float* vi = &bestTile->verts[bestPoly->verts[i]*3];
3563 float tseg;
3564 float distSqr = dtDistancePtSegSqr2D(centerPos, vj, vi, tseg);
3565
3566 // Edge is too far, skip.
3567 if (distSqr > radiusSqr)
3568 continue;
3569
3570 // Hit wall, update radius.
3571 radiusSqr = distSqr;
3572 // Calculate hit pos.
3573 hitPos[0] = vj[0] + (vi[0] - vj[0])*tseg;
3574 hitPos[1] = vj[1] + (vi[1] - vj[1])*tseg;
3575 hitPos[2] = vj[2] + (vi[2] - vj[2])*tseg;
3576 }
3577
3578 for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
3579 {
3580 const dtLink* link = &bestTile->links[i];
3581 dtPolyRef neighbourRef = link->ref;
3582 // Skip invalid neighbours and do not follow back to parent.
3583 if (!neighbourRef || neighbourRef == parentRef)
3584 continue;
3585
3586 // Expand to neighbour.
3587 const dtMeshTile* neighbourTile = 0;
3588 const dtPoly* neighbourPoly = 0;
3589 m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
3590
3591 // Skip off-mesh connections.
3592 if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
3593 continue;
3594
3595 // Calc distance to the edge.
3596 const float* va = &bestTile->verts[bestPoly->verts[link->edge]*3];
3597 const float* vb = &bestTile->verts[bestPoly->verts[(link->edge+1) % bestPoly->vertCount]*3];
3598 float tseg;
3599 float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
3600
3601 // If the circle is not touching the next polygon, skip it.
3602 if (distSqr > radiusSqr)
3603 continue;
3604
3605 if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
3606 continue;
3607
3608 dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
3609 if (!neighbourNode)
3610 {
3611 status |= DT_OUT_OF_NODES;
3612 continue;
3613 }
3614
3615 if (neighbourNode->flags & DT_NODE_CLOSED)
3616 continue;
3617
3618 // Cost
3619 if (neighbourNode->flags == 0)
3620 {
3621 getEdgeMidPoint(bestRef, bestPoly, bestTile,
3622 neighbourRef, neighbourPoly, neighbourTile, neighbourNode->pos);
3623 }
3624
3625 const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos);
3626
3627 // The node is already in open list and the new result is worse, skip.
3628 if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
3629 continue;
3630
3631 neighbourNode->id = neighbourRef;
3632 neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
3633 neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
3634 neighbourNode->total = total;
3635
3636 if (neighbourNode->flags & DT_NODE_OPEN)
3637 {
3638 m_openList->modify(neighbourNode);
3639 }
3640 else
3641 {
3642 neighbourNode->flags |= DT_NODE_OPEN;
3643 m_openList->push(neighbourNode);
3644 }
3645 }
3646 }
3647
3648 // Calc hit normal.
3649 dtVsub(hitNormal, centerPos, hitPos);
3650 dtVnormalize(hitNormal);
3651
3652 *hitDist = dtMathSqrtf(radiusSqr);
3653
3654 return status;
3655 }
3656
3657 bool dtNavMeshQuery::isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const
3658 {
3659 const dtMeshTile* tile = 0;
3660 const dtPoly* poly = 0;
3661 dtStatus status = m_nav->getTileAndPolyByRef(ref, &tile, &poly);
3662 // If cannot get polygon, assume it does not exists and boundary is invalid.
3663 if (dtStatusFailed(status))
3664 return false;
3665 // If cannot pass filter, assume flags has changed and boundary is invalid.
3666 if (!filter->passFilter(ref, tile, poly))
3667 return false;
3668 return true;
3669 }
3670
3671 /// @par
3672 ///
3673 /// The closed list is the list of polygons that were fully evaluated during
3674 /// the last navigation graph search. (A* or Dijkstra)
3675 ///
3676 bool dtNavMeshQuery::isInClosedList(dtPolyRef ref) const
3677 {
3678 if (!m_nodePool) return false;
3679
3680 dtNode* nodes[DT_MAX_STATES_PER_NODE];
3681 int n= m_nodePool->findNodes(ref, nodes, DT_MAX_STATES_PER_NODE);
3682
3683 for (int i=0; i<n; i++)
3684 {
3685 if (nodes[i]->flags & DT_NODE_CLOSED)
3686 return true;
3687 }
3688
3689 return false;
3690 }