DetourNavMesh.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. #include <math.h>
  19. #include <float.h>
  20. #include <string.h>
  21. #include <stdio.h>
  22. #include "DetourNavMesh.h"
  23. #include "DetourNode.h"
  24. #include "DetourCommon.h"
  25. #include "DetourAlloc.h"
  26. #include "DetourAssert.h"
  27. #include <new>
  28. inline bool overlapSlabs(const float* amin, const float* amax,
  29. const float* bmin, const float* bmax,
  30. const float px, const float py)
  31. {
  32. // Check for horizontal overlap.
  33. // The segment is shrunken a little so that slabs which touch
  34. // at end points are not connected.
  35. const float minx = dtMax(amin[0]+px,bmin[0]+px);
  36. const float maxx = dtMin(amax[0]-px,bmax[0]-px);
  37. if (minx > maxx)
  38. return false;
  39. // Check vertical overlap.
  40. const float ad = (amax[1]-amin[1]) / (amax[0]-amin[0]);
  41. const float ak = amin[1] - ad*amin[0];
  42. const float bd = (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]);
  43. const float bk = bmin[1] - bd*bmin[0];
  44. const float aminy = ad*minx + ak;
  45. const float amaxy = ad*maxx + ak;
  46. const float bminy = bd*minx + bk;
  47. const float bmaxy = bd*maxx + bk;
  48. const float dmin = bminy - aminy;
  49. const float dmax = bmaxy - amaxy;
  50. // Crossing segments always overlap.
  51. if (dmin*dmax < 0)
  52. return true;
  53. // Check for overlap at endpoints.
  54. const float thr = dtSqr(py*2);
  55. if (dmin*dmin <= thr || dmax*dmax <= thr)
  56. return true;
  57. return false;
  58. }
  59. static float getSlabCoord(const float* va, const int side)
  60. {
  61. if (side == 0 || side == 4)
  62. return va[0];
  63. else if (side == 2 || side == 6)
  64. return va[2];
  65. return 0;
  66. }
  67. static void calcSlabEndPoints(const float* va, const float* vb, float* bmin, float* bmax, const int side)
  68. {
  69. if (side == 0 || side == 4)
  70. {
  71. if (va[2] < vb[2])
  72. {
  73. bmin[0] = va[2];
  74. bmin[1] = va[1];
  75. bmax[0] = vb[2];
  76. bmax[1] = vb[1];
  77. }
  78. else
  79. {
  80. bmin[0] = vb[2];
  81. bmin[1] = vb[1];
  82. bmax[0] = va[2];
  83. bmax[1] = va[1];
  84. }
  85. }
  86. else if (side == 2 || side == 6)
  87. {
  88. if (va[0] < vb[0])
  89. {
  90. bmin[0] = va[0];
  91. bmin[1] = va[1];
  92. bmax[0] = vb[0];
  93. bmax[1] = vb[1];
  94. }
  95. else
  96. {
  97. bmin[0] = vb[0];
  98. bmin[1] = vb[1];
  99. bmax[0] = va[0];
  100. bmax[1] = va[1];
  101. }
  102. }
  103. }
  104. inline int computeTileHash(int x, int y, const int mask)
  105. {
  106. const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
  107. const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
  108. unsigned int n = h1 * x + h2 * y;
  109. return (int)(n & mask);
  110. }
  111. inline unsigned int allocLink(dtMeshTile* tile)
  112. {
  113. if (tile->linksFreeList == DT_NULL_LINK)
  114. return DT_NULL_LINK;
  115. unsigned int link = tile->linksFreeList;
  116. tile->linksFreeList = tile->links[link].next;
  117. return link;
  118. }
  119. inline void freeLink(dtMeshTile* tile, unsigned int link)
  120. {
  121. tile->links[link].next = tile->linksFreeList;
  122. tile->linksFreeList = link;
  123. }
  124. dtNavMesh* dtAllocNavMesh()
  125. {
  126. void* mem = dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM);
  127. if (!mem) return 0;
  128. return new(mem) dtNavMesh;
  129. }
  130. /// @par
  131. ///
  132. /// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA
  133. /// flag set.
  134. void dtFreeNavMesh(dtNavMesh* navmesh)
  135. {
  136. if (!navmesh) return;
  137. navmesh->~dtNavMesh();
  138. dtFree(navmesh);
  139. }
  140. //////////////////////////////////////////////////////////////////////////////////////////
  141. /**
  142. @class dtNavMesh
  143. The navigation mesh consists of one or more tiles defining three primary types of structural data:
  144. A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.)
  145. A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.)
  146. Off-mesh connections, which define custom point-to-point edges within the navigation graph.
  147. The general build process is as follows:
  148. -# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline.
  149. -# Optionally, create off-mesh connection data.
  150. -# Combine the source data into a dtNavMeshCreateParams structure.
  151. -# Create a tile data array using dtCreateNavMeshData().
  152. -# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes,
  153. the tile data is loaded during this step.)
  154. -# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile().
  155. Notes:
  156. - This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding.
  157. - Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized
  158. to have only a single tile.
  159. - This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will
  160. always contain either a success or failure flag.
  161. @see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh
  162. */
  163. dtNavMesh::dtNavMesh() :
  164. m_tileWidth(0),
  165. m_tileHeight(0),
  166. m_maxTiles(0),
  167. m_tileLutSize(0),
  168. m_tileLutMask(0),
  169. m_posLookup(0),
  170. m_nextFree(0),
  171. m_tiles(0),
  172. m_saltBits(0),
  173. m_tileBits(0),
  174. m_polyBits(0)
  175. {
  176. memset(&m_params, 0, sizeof(dtNavMeshParams));
  177. m_orig[0] = 0;
  178. m_orig[1] = 0;
  179. m_orig[2] = 0;
  180. }
  181. dtNavMesh::~dtNavMesh()
  182. {
  183. for (int i = 0; i < m_maxTiles; ++i)
  184. {
  185. if (m_tiles[i].flags & DT_TILE_FREE_DATA)
  186. {
  187. dtFree(m_tiles[i].data);
  188. m_tiles[i].data = 0;
  189. m_tiles[i].dataSize = 0;
  190. }
  191. }
  192. dtFree(m_posLookup);
  193. dtFree(m_tiles);
  194. }
  195. dtStatus dtNavMesh::init(const dtNavMeshParams* params)
  196. {
  197. memcpy(&m_params, params, sizeof(dtNavMeshParams));
  198. dtVcopy(m_orig, params->orig);
  199. m_tileWidth = params->tileWidth;
  200. m_tileHeight = params->tileHeight;
  201. // Init tiles
  202. m_maxTiles = params->maxTiles;
  203. m_tileLutSize = dtNextPow2(params->maxTiles/4);
  204. if (!m_tileLutSize) m_tileLutSize = 1;
  205. m_tileLutMask = m_tileLutSize-1;
  206. m_tiles = (dtMeshTile*)dtAlloc(sizeof(dtMeshTile)*m_maxTiles, DT_ALLOC_PERM);
  207. if (!m_tiles)
  208. return DT_FAILURE | DT_OUT_OF_MEMORY;
  209. m_posLookup = (dtMeshTile**)dtAlloc(sizeof(dtMeshTile*)*m_tileLutSize, DT_ALLOC_PERM);
  210. if (!m_posLookup)
  211. return DT_FAILURE | DT_OUT_OF_MEMORY;
  212. memset(m_tiles, 0, sizeof(dtMeshTile)*m_maxTiles);
  213. memset(m_posLookup, 0, sizeof(dtMeshTile*)*m_tileLutSize);
  214. m_nextFree = 0;
  215. for (int i = m_maxTiles-1; i >= 0; --i)
  216. {
  217. m_tiles[i].salt = 1;
  218. m_tiles[i].next = m_nextFree;
  219. m_nextFree = &m_tiles[i];
  220. }
  221. // Init ID generator values.
  222. m_tileBits = dtIlog2(dtNextPow2((unsigned int)params->maxTiles));
  223. m_polyBits = dtIlog2(dtNextPow2((unsigned int)params->maxPolys));
  224. // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow.
  225. m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits - m_polyBits);
  226. if (m_saltBits < 10)
  227. return DT_FAILURE | DT_INVALID_PARAM;
  228. return DT_SUCCESS;
  229. }
  230. dtStatus dtNavMesh::init(unsigned char* data, const int dataSize, const int flags)
  231. {
  232. // Make sure the data is in right format.
  233. dtMeshHeader* header = (dtMeshHeader*)data;
  234. if (header->magic != DT_NAVMESH_MAGIC)
  235. return DT_FAILURE | DT_WRONG_MAGIC;
  236. if (header->version != DT_NAVMESH_VERSION)
  237. return DT_FAILURE | DT_WRONG_VERSION;
  238. dtNavMeshParams params;
  239. dtVcopy(params.orig, header->bmin);
  240. params.tileWidth = header->bmax[0] - header->bmin[0];
  241. params.tileHeight = header->bmax[2] - header->bmin[2];
  242. params.maxTiles = 1;
  243. params.maxPolys = header->polyCount;
  244. dtStatus status = init(&params);
  245. if (dtStatusFailed(status))
  246. return status;
  247. return addTile(data, dataSize, flags, 0, 0);
  248. }
  249. /// @par
  250. ///
  251. /// @note The parameters are created automatically when the single tile
  252. /// initialization is performed.
  253. const dtNavMeshParams* dtNavMesh::getParams() const
  254. {
  255. return &m_params;
  256. }
  257. //////////////////////////////////////////////////////////////////////////////////////////
  258. int dtNavMesh::findConnectingPolys(const float* va, const float* vb,
  259. const dtMeshTile* tile, int side,
  260. dtPolyRef* con, float* conarea, int maxcon) const
  261. {
  262. if (!tile) return 0;
  263. float amin[2], amax[2];
  264. calcSlabEndPoints(va,vb, amin,amax, side);
  265. const float apos = getSlabCoord(va, side);
  266. // Remove links pointing to 'side' and compact the links array.
  267. float bmin[2], bmax[2];
  268. unsigned short m = DT_EXT_LINK | (unsigned short)side;
  269. int n = 0;
  270. dtPolyRef base = getPolyRefBase(tile);
  271. for (int i = 0; i < tile->header->polyCount; ++i)
  272. {
  273. dtPoly* poly = &tile->polys[i];
  274. const int nv = poly->vertCount;
  275. for (int j = 0; j < nv; ++j)
  276. {
  277. // Skip edges which do not point to the right side.
  278. if (poly->neis[j] != m) continue;
  279. const float* vc = &tile->verts[poly->verts[j]*3];
  280. const float* vd = &tile->verts[poly->verts[(j+1) % nv]*3];
  281. const float bpos = getSlabCoord(vc, side);
  282. // Segments are not close enough.
  283. if (dtAbs(apos-bpos) > 0.01f)
  284. continue;
  285. // Check if the segments touch.
  286. calcSlabEndPoints(vc,vd, bmin,bmax, side);
  287. if (!overlapSlabs(amin,amax, bmin,bmax, 0.01f, tile->header->walkableClimb)) continue;
  288. // Add return value.
  289. if (n < maxcon)
  290. {
  291. conarea[n*2+0] = dtMax(amin[0], bmin[0]);
  292. conarea[n*2+1] = dtMin(amax[0], bmax[0]);
  293. con[n] = base | (dtPolyRef)i;
  294. n++;
  295. }
  296. break;
  297. }
  298. }
  299. return n;
  300. }
  301. void dtNavMesh::unconnectExtLinks(dtMeshTile* tile, dtMeshTile* target)
  302. {
  303. if (!tile || !target) return;
  304. const unsigned int targetNum = decodePolyIdTile(getTileRef(target));
  305. for (int i = 0; i < tile->header->polyCount; ++i)
  306. {
  307. dtPoly* poly = &tile->polys[i];
  308. unsigned int j = poly->firstLink;
  309. unsigned int pj = DT_NULL_LINK;
  310. while (j != DT_NULL_LINK)
  311. {
  312. if (tile->links[j].side != 0xff &&
  313. decodePolyIdTile(tile->links[j].ref) == targetNum)
  314. {
  315. // Revove link.
  316. unsigned int nj = tile->links[j].next;
  317. if (pj == DT_NULL_LINK)
  318. poly->firstLink = nj;
  319. else
  320. tile->links[pj].next = nj;
  321. freeLink(tile, j);
  322. j = nj;
  323. }
  324. else
  325. {
  326. // Advance
  327. pj = j;
  328. j = tile->links[j].next;
  329. }
  330. }
  331. }
  332. }
  333. void dtNavMesh::connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side)
  334. {
  335. if (!tile) return;
  336. // Connect border links.
  337. for (int i = 0; i < tile->header->polyCount; ++i)
  338. {
  339. dtPoly* poly = &tile->polys[i];
  340. // Create new links.
  341. // unsigned short m = DT_EXT_LINK | (unsigned short)side;
  342. const int nv = poly->vertCount;
  343. for (int j = 0; j < nv; ++j)
  344. {
  345. // Skip non-portal edges.
  346. if ((poly->neis[j] & DT_EXT_LINK) == 0)
  347. continue;
  348. const int dir = (int)(poly->neis[j] & 0xff);
  349. if (side != -1 && dir != side)
  350. continue;
  351. // Create new links
  352. const float* va = &tile->verts[poly->verts[j]*3];
  353. const float* vb = &tile->verts[poly->verts[(j+1) % nv]*3];
  354. dtPolyRef nei[4];
  355. float neia[4*2];
  356. int nnei = findConnectingPolys(va,vb, target, dtOppositeTile(dir), nei,neia,4);
  357. for (int k = 0; k < nnei; ++k)
  358. {
  359. unsigned int idx = allocLink(tile);
  360. if (idx != DT_NULL_LINK)
  361. {
  362. dtLink* link = &tile->links[idx];
  363. link->ref = nei[k];
  364. link->edge = (unsigned char)j;
  365. link->side = (unsigned char)dir;
  366. link->next = poly->firstLink;
  367. poly->firstLink = idx;
  368. // Compress portal limits to a byte value.
  369. if (dir == 0 || dir == 4)
  370. {
  371. float tmin = (neia[k*2+0]-va[2]) / (vb[2]-va[2]);
  372. float tmax = (neia[k*2+1]-va[2]) / (vb[2]-va[2]);
  373. if (tmin > tmax)
  374. dtSwap(tmin,tmax);
  375. link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
  376. link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
  377. }
  378. else if (dir == 2 || dir == 6)
  379. {
  380. float tmin = (neia[k*2+0]-va[0]) / (vb[0]-va[0]);
  381. float tmax = (neia[k*2+1]-va[0]) / (vb[0]-va[0]);
  382. if (tmin > tmax)
  383. dtSwap(tmin,tmax);
  384. link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
  385. link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. void dtNavMesh::connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side)
  393. {
  394. if (!tile) return;
  395. // Connect off-mesh links.
  396. // We are interested on links which land from target tile to this tile.
  397. const unsigned char oppositeSide = (side == -1) ? 0xff : (unsigned char)dtOppositeTile(side);
  398. for (int i = 0; i < target->header->offMeshConCount; ++i)
  399. {
  400. dtOffMeshConnection* targetCon = &target->offMeshCons[i];
  401. if (targetCon->side != oppositeSide)
  402. continue;
  403. dtPoly* targetPoly = &target->polys[targetCon->poly];
  404. // Skip off-mesh connections which start location could not be connected at all.
  405. if (targetPoly->firstLink == DT_NULL_LINK)
  406. continue;
  407. const float ext[3] = { targetCon->rad, target->header->walkableClimb, targetCon->rad };
  408. // Find polygon to connect to.
  409. const float* p = &targetCon->pos[3];
  410. float nearestPt[3];
  411. dtPolyRef ref = findNearestPolyInTile(tile, p, ext, nearestPt);
  412. if (!ref)
  413. continue;
  414. // findNearestPoly may return too optimistic results, further check to make sure.
  415. if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(targetCon->rad))
  416. continue;
  417. // Make sure the location is on current mesh.
  418. float* v = &target->verts[targetPoly->verts[1]*3];
  419. dtVcopy(v, nearestPt);
  420. // Link off-mesh connection to target poly.
  421. unsigned int idx = allocLink(target);
  422. if (idx != DT_NULL_LINK)
  423. {
  424. dtLink* link = &target->links[idx];
  425. link->ref = ref;
  426. link->edge = (unsigned char)1;
  427. link->side = oppositeSide;
  428. link->bmin = link->bmax = 0;
  429. // Add to linked list.
  430. link->next = targetPoly->firstLink;
  431. targetPoly->firstLink = idx;
  432. }
  433. // Link target poly to off-mesh connection.
  434. if (targetCon->flags & DT_OFFMESH_CON_BIDIR)
  435. {
  436. unsigned int tidx = allocLink(tile);
  437. if (tidx != DT_NULL_LINK)
  438. {
  439. const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
  440. dtPoly* landPoly = &tile->polys[landPolyIdx];
  441. dtLink* link = &tile->links[tidx];
  442. link->ref = getPolyRefBase(target) | (dtPolyRef)(targetCon->poly);
  443. link->edge = 0xff;
  444. link->side = (unsigned char)(side == -1 ? 0xff : side);
  445. link->bmin = link->bmax = 0;
  446. // Add to linked list.
  447. link->next = landPoly->firstLink;
  448. landPoly->firstLink = tidx;
  449. }
  450. }
  451. }
  452. }
  453. void dtNavMesh::connectIntLinks(dtMeshTile* tile)
  454. {
  455. if (!tile) return;
  456. dtPolyRef base = getPolyRefBase(tile);
  457. for (int i = 0; i < tile->header->polyCount; ++i)
  458. {
  459. dtPoly* poly = &tile->polys[i];
  460. poly->firstLink = DT_NULL_LINK;
  461. if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
  462. continue;
  463. // Build edge links backwards so that the links will be
  464. // in the linked list from lowest index to highest.
  465. for (int j = poly->vertCount-1; j >= 0; --j)
  466. {
  467. // Skip hard and non-internal edges.
  468. if (poly->neis[j] == 0 || (poly->neis[j] & DT_EXT_LINK)) continue;
  469. unsigned int idx = allocLink(tile);
  470. if (idx != DT_NULL_LINK)
  471. {
  472. dtLink* link = &tile->links[idx];
  473. link->ref = base | (dtPolyRef)(poly->neis[j]-1);
  474. link->edge = (unsigned char)j;
  475. link->side = 0xff;
  476. link->bmin = link->bmax = 0;
  477. // Add to linked list.
  478. link->next = poly->firstLink;
  479. poly->firstLink = idx;
  480. }
  481. }
  482. }
  483. }
  484. void dtNavMesh::baseOffMeshLinks(dtMeshTile* tile)
  485. {
  486. if (!tile) return;
  487. dtPolyRef base = getPolyRefBase(tile);
  488. // Base off-mesh connection start points.
  489. for (int i = 0; i < tile->header->offMeshConCount; ++i)
  490. {
  491. dtOffMeshConnection* con = &tile->offMeshCons[i];
  492. dtPoly* poly = &tile->polys[con->poly];
  493. const float ext[3] = { con->rad, tile->header->walkableClimb, con->rad };
  494. // Find polygon to connect to.
  495. const float* p = &con->pos[0]; // First vertex
  496. float nearestPt[3];
  497. dtPolyRef ref = findNearestPolyInTile(tile, p, ext, nearestPt);
  498. if (!ref) continue;
  499. // findNearestPoly may return too optimistic results, further check to make sure.
  500. if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(con->rad))
  501. continue;
  502. // Make sure the location is on current mesh.
  503. float* v = &tile->verts[poly->verts[0]*3];
  504. dtVcopy(v, nearestPt);
  505. // Link off-mesh connection to target poly.
  506. unsigned int idx = allocLink(tile);
  507. if (idx != DT_NULL_LINK)
  508. {
  509. dtLink* link = &tile->links[idx];
  510. link->ref = ref;
  511. link->edge = (unsigned char)0;
  512. link->side = 0xff;
  513. link->bmin = link->bmax = 0;
  514. // Add to linked list.
  515. link->next = poly->firstLink;
  516. poly->firstLink = idx;
  517. }
  518. // Start end-point is always connect back to off-mesh connection.
  519. unsigned int tidx = allocLink(tile);
  520. if (tidx != DT_NULL_LINK)
  521. {
  522. const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
  523. dtPoly* landPoly = &tile->polys[landPolyIdx];
  524. dtLink* link = &tile->links[tidx];
  525. link->ref = base | (dtPolyRef)(con->poly);
  526. link->edge = 0xff;
  527. link->side = 0xff;
  528. link->bmin = link->bmax = 0;
  529. // Add to linked list.
  530. link->next = landPoly->firstLink;
  531. landPoly->firstLink = tidx;
  532. }
  533. }
  534. }
  535. void dtNavMesh::closestPointOnPolyInTile(const dtMeshTile* tile, unsigned int ip,
  536. const float* pos, float* closest) const
  537. {
  538. const dtPoly* poly = &tile->polys[ip];
  539. float closestDistSqr = FLT_MAX;
  540. const dtPolyDetail* pd = &tile->detailMeshes[ip];
  541. for (int j = 0; j < pd->triCount; ++j)
  542. {
  543. const unsigned char* t = &tile->detailTris[(pd->triBase+j)*4];
  544. const float* v[3];
  545. for (int k = 0; k < 3; ++k)
  546. {
  547. if (t[k] < poly->vertCount)
  548. v[k] = &tile->verts[poly->verts[t[k]]*3];
  549. else
  550. v[k] = &tile->detailVerts[(pd->vertBase+(t[k]-poly->vertCount))*3];
  551. }
  552. float pt[3];
  553. dtClosestPtPointTriangle(pt, pos, v[0], v[1], v[2]);
  554. float d = dtVdistSqr(pos, pt);
  555. if (d < closestDistSqr)
  556. {
  557. dtVcopy(closest, pt);
  558. closestDistSqr = d;
  559. }
  560. }
  561. }
  562. dtPolyRef dtNavMesh::findNearestPolyInTile(const dtMeshTile* tile,
  563. const float* center, const float* extents,
  564. float* nearestPt) const
  565. {
  566. float bmin[3], bmax[3];
  567. dtVsub(bmin, center, extents);
  568. dtVadd(bmax, center, extents);
  569. // Get nearby polygons from proximity grid.
  570. dtPolyRef polys[128];
  571. int polyCount = queryPolygonsInTile(tile, bmin, bmax, polys, 128);
  572. // Find nearest polygon amongst the nearby polygons.
  573. dtPolyRef nearest = 0;
  574. float nearestDistanceSqr = FLT_MAX;
  575. for (int i = 0; i < polyCount; ++i)
  576. {
  577. dtPolyRef ref = polys[i];
  578. float closestPtPoly[3];
  579. closestPointOnPolyInTile(tile, decodePolyIdPoly(ref), center, closestPtPoly);
  580. float d = dtVdistSqr(center, closestPtPoly);
  581. if (d < nearestDistanceSqr)
  582. {
  583. if (nearestPt)
  584. dtVcopy(nearestPt, closestPtPoly);
  585. nearestDistanceSqr = d;
  586. nearest = ref;
  587. }
  588. }
  589. return nearest;
  590. }
  591. int dtNavMesh::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
  592. dtPolyRef* polys, const int maxPolys) const
  593. {
  594. if (tile->bvTree)
  595. {
  596. const dtBVNode* node = &tile->bvTree[0];
  597. const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount];
  598. const float* tbmin = tile->header->bmin;
  599. const float* tbmax = tile->header->bmax;
  600. const float qfac = tile->header->bvQuantFactor;
  601. // Calculate quantized box
  602. unsigned short bmin[3], bmax[3];
  603. // dtClamp query box to world box.
  604. float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
  605. float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
  606. float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
  607. float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
  608. float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
  609. float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
  610. // Quantize
  611. bmin[0] = (unsigned short)(qfac * minx) & 0xfffe;
  612. bmin[1] = (unsigned short)(qfac * miny) & 0xfffe;
  613. bmin[2] = (unsigned short)(qfac * minz) & 0xfffe;
  614. bmax[0] = (unsigned short)(qfac * maxx + 1) | 1;
  615. bmax[1] = (unsigned short)(qfac * maxy + 1) | 1;
  616. bmax[2] = (unsigned short)(qfac * maxz + 1) | 1;
  617. // Traverse tree
  618. dtPolyRef base = getPolyRefBase(tile);
  619. int n = 0;
  620. while (node < end)
  621. {
  622. const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax);
  623. const bool isLeafNode = node->i >= 0;
  624. if (isLeafNode && overlap)
  625. {
  626. if (n < maxPolys)
  627. polys[n++] = base | (dtPolyRef)node->i;
  628. }
  629. if (overlap || isLeafNode)
  630. node++;
  631. else
  632. {
  633. const int escapeIndex = -node->i;
  634. node += escapeIndex;
  635. }
  636. }
  637. return n;
  638. }
  639. else
  640. {
  641. float bmin[3], bmax[3];
  642. int n = 0;
  643. dtPolyRef base = getPolyRefBase(tile);
  644. for (int i = 0; i < tile->header->polyCount; ++i)
  645. {
  646. dtPoly* p = &tile->polys[i];
  647. // Do not return off-mesh connection polygons.
  648. if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
  649. continue;
  650. // Calc polygon bounds.
  651. const float* v = &tile->verts[p->verts[0]*3];
  652. dtVcopy(bmin, v);
  653. dtVcopy(bmax, v);
  654. for (int j = 1; j < p->vertCount; ++j)
  655. {
  656. v = &tile->verts[p->verts[j]*3];
  657. dtVmin(bmin, v);
  658. dtVmax(bmax, v);
  659. }
  660. if (dtOverlapBounds(qmin,qmax, bmin,bmax))
  661. {
  662. if (n < maxPolys)
  663. polys[n++] = base | (dtPolyRef)i;
  664. }
  665. }
  666. return n;
  667. }
  668. }
  669. /// @par
  670. ///
  671. /// The add operation will fail if the data is in the wrong format, the allocated tile
  672. /// space is full, or there is a tile already at the specified reference.
  673. ///
  674. /// The lastRef parameter is used to restore a tile with the same tile
  675. /// reference it had previously used. In this case the #dtPolyRef's for the
  676. /// tile will be restored to the same values they were before the tile was
  677. /// removed.
  678. ///
  679. /// @see dtCreateNavMeshData, #removeTile
  680. dtStatus dtNavMesh::addTile(unsigned char* data, int dataSize, int flags,
  681. dtTileRef lastRef, dtTileRef* result)
  682. {
  683. // Make sure the data is in right format.
  684. dtMeshHeader* header = (dtMeshHeader*)data;
  685. if (header->magic != DT_NAVMESH_MAGIC)
  686. return DT_FAILURE | DT_WRONG_MAGIC;
  687. if (header->version != DT_NAVMESH_VERSION)
  688. return DT_FAILURE | DT_WRONG_VERSION;
  689. // Make sure the location is free.
  690. if (getTileAt(header->x, header->y, header->layer))
  691. return DT_FAILURE;
  692. // Allocate a tile.
  693. dtMeshTile* tile = 0;
  694. if (!lastRef)
  695. {
  696. if (m_nextFree)
  697. {
  698. tile = m_nextFree;
  699. m_nextFree = tile->next;
  700. tile->next = 0;
  701. }
  702. }
  703. else
  704. {
  705. // Try to relocate the tile to specific index with same salt.
  706. int tileIndex = (int)decodePolyIdTile((dtPolyRef)lastRef);
  707. if (tileIndex >= m_maxTiles)
  708. return DT_FAILURE | DT_OUT_OF_MEMORY;
  709. // Try to find the specific tile id from the free list.
  710. dtMeshTile* target = &m_tiles[tileIndex];
  711. dtMeshTile* prev = 0;
  712. tile = m_nextFree;
  713. while (tile && tile != target)
  714. {
  715. prev = tile;
  716. tile = tile->next;
  717. }
  718. // Could not find the correct location.
  719. if (tile != target)
  720. return DT_FAILURE | DT_OUT_OF_MEMORY;
  721. // Remove from freelist
  722. if (!prev)
  723. m_nextFree = tile->next;
  724. else
  725. prev->next = tile->next;
  726. // Restore salt.
  727. tile->salt = decodePolyIdSalt((dtPolyRef)lastRef);
  728. }
  729. // Make sure we could allocate a tile.
  730. if (!tile)
  731. return DT_FAILURE | DT_OUT_OF_MEMORY;
  732. // Insert tile into the position lut.
  733. int h = computeTileHash(header->x, header->y, m_tileLutMask);
  734. tile->next = m_posLookup[h];
  735. m_posLookup[h] = tile;
  736. // Patch header pointers.
  737. const int headerSize = dtAlign4(sizeof(dtMeshHeader));
  738. const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount);
  739. const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount);
  740. const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount));
  741. const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount);
  742. const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount);
  743. const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount);
  744. const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount);
  745. const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount);
  746. unsigned char* d = data + headerSize;
  747. tile->verts = (float*)d; d += vertsSize;
  748. tile->polys = (dtPoly*)d; d += polysSize;
  749. tile->links = (dtLink*)d; d += linksSize;
  750. tile->detailMeshes = (dtPolyDetail*)d; d += detailMeshesSize;
  751. tile->detailVerts = (float*)d; d += detailVertsSize;
  752. tile->detailTris = (unsigned char*)d; d += detailTrisSize;
  753. tile->bvTree = (dtBVNode*)d; d += bvtreeSize;
  754. tile->offMeshCons = (dtOffMeshConnection*)d; d += offMeshLinksSize;
  755. // If there are no items in the bvtree, reset the tree pointer.
  756. if (!bvtreeSize)
  757. tile->bvTree = 0;
  758. // Build links freelist
  759. tile->linksFreeList = 0;
  760. tile->links[header->maxLinkCount-1].next = DT_NULL_LINK;
  761. for (int i = 0; i < header->maxLinkCount-1; ++i)
  762. tile->links[i].next = i+1;
  763. // Init tile.
  764. tile->header = header;
  765. tile->data = data;
  766. tile->dataSize = dataSize;
  767. tile->flags = flags;
  768. connectIntLinks(tile);
  769. baseOffMeshLinks(tile);
  770. // Create connections with neighbour tiles.
  771. static const int MAX_NEIS = 32;
  772. dtMeshTile* neis[MAX_NEIS];
  773. int nneis;
  774. // Connect with layers in current tile.
  775. nneis = getTilesAt(header->x, header->y, neis, MAX_NEIS);
  776. for (int j = 0; j < nneis; ++j)
  777. {
  778. if (neis[j] != tile)
  779. {
  780. connectExtLinks(tile, neis[j], -1);
  781. connectExtLinks(neis[j], tile, -1);
  782. }
  783. connectExtOffMeshLinks(tile, neis[j], -1);
  784. connectExtOffMeshLinks(neis[j], tile, -1);
  785. }
  786. // Connect with neighbour tiles.
  787. for (int i = 0; i < 8; ++i)
  788. {
  789. nneis = getNeighbourTilesAt(header->x, header->y, i, neis, MAX_NEIS);
  790. for (int j = 0; j < nneis; ++j)
  791. {
  792. connectExtLinks(tile, neis[j], i);
  793. connectExtLinks(neis[j], tile, dtOppositeTile(i));
  794. connectExtOffMeshLinks(tile, neis[j], i);
  795. connectExtOffMeshLinks(neis[j], tile, dtOppositeTile(i));
  796. }
  797. }
  798. if (result)
  799. *result = getTileRef(tile);
  800. return DT_SUCCESS;
  801. }
  802. const dtMeshTile* dtNavMesh::getTileAt(const int x, const int y, const int layer) const
  803. {
  804. // Find tile based on hash.
  805. int h = computeTileHash(x,y,m_tileLutMask);
  806. dtMeshTile* tile = m_posLookup[h];
  807. while (tile)
  808. {
  809. if (tile->header &&
  810. tile->header->x == x &&
  811. tile->header->y == y &&
  812. tile->header->layer == layer)
  813. {
  814. return tile;
  815. }
  816. tile = tile->next;
  817. }
  818. return 0;
  819. }
  820. int dtNavMesh::getNeighbourTilesAt(const int x, const int y, const int side, dtMeshTile** tiles, const int maxTiles) const
  821. {
  822. int nx = x, ny = y;
  823. switch (side)
  824. {
  825. case 0: nx++; break;
  826. case 1: nx++; ny++; break;
  827. case 2: ny++; break;
  828. case 3: nx--; ny++; break;
  829. case 4: nx--; break;
  830. case 5: nx--; ny--; break;
  831. case 6: ny--; break;
  832. case 7: nx++; ny--; break;
  833. };
  834. return getTilesAt(nx, ny, tiles, maxTiles);
  835. }
  836. int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile** tiles, const int maxTiles) const
  837. {
  838. int n = 0;
  839. // Find tile based on hash.
  840. int h = computeTileHash(x,y,m_tileLutMask);
  841. dtMeshTile* tile = m_posLookup[h];
  842. while (tile)
  843. {
  844. if (tile->header &&
  845. tile->header->x == x &&
  846. tile->header->y == y)
  847. {
  848. if (n < maxTiles)
  849. tiles[n++] = tile;
  850. }
  851. tile = tile->next;
  852. }
  853. return n;
  854. }
  855. /// @par
  856. ///
  857. /// This function will not fail if the tiles array is too small to hold the
  858. /// entire result set. It will simply fill the array to capacity.
  859. int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile const** tiles, const int maxTiles) const
  860. {
  861. int n = 0;
  862. // Find tile based on hash.
  863. int h = computeTileHash(x,y,m_tileLutMask);
  864. dtMeshTile* tile = m_posLookup[h];
  865. while (tile)
  866. {
  867. if (tile->header &&
  868. tile->header->x == x &&
  869. tile->header->y == y)
  870. {
  871. if (n < maxTiles)
  872. tiles[n++] = tile;
  873. }
  874. tile = tile->next;
  875. }
  876. return n;
  877. }
  878. dtTileRef dtNavMesh::getTileRefAt(const int x, const int y, const int layer) const
  879. {
  880. // Find tile based on hash.
  881. int h = computeTileHash(x,y,m_tileLutMask);
  882. dtMeshTile* tile = m_posLookup[h];
  883. while (tile)
  884. {
  885. if (tile->header &&
  886. tile->header->x == x &&
  887. tile->header->y == y &&
  888. tile->header->layer == layer)
  889. {
  890. return getTileRef(tile);
  891. }
  892. tile = tile->next;
  893. }
  894. return 0;
  895. }
  896. const dtMeshTile* dtNavMesh::getTileByRef(dtTileRef ref) const
  897. {
  898. if (!ref)
  899. return 0;
  900. unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
  901. unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
  902. if ((int)tileIndex >= m_maxTiles)
  903. return 0;
  904. const dtMeshTile* tile = &m_tiles[tileIndex];
  905. if (tile->salt != tileSalt)
  906. return 0;
  907. return tile;
  908. }
  909. int dtNavMesh::getMaxTiles() const
  910. {
  911. return m_maxTiles;
  912. }
  913. dtMeshTile* dtNavMesh::getTile(int i)
  914. {
  915. return &m_tiles[i];
  916. }
  917. const dtMeshTile* dtNavMesh::getTile(int i) const
  918. {
  919. return &m_tiles[i];
  920. }
  921. void dtNavMesh::calcTileLoc(const float* pos, int* tx, int* ty) const
  922. {
  923. *tx = (int)floorf((pos[0]-m_orig[0]) / m_tileWidth);
  924. *ty = (int)floorf((pos[2]-m_orig[2]) / m_tileHeight);
  925. }
  926. dtStatus dtNavMesh::getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
  927. {
  928. if (!ref) return DT_FAILURE;
  929. unsigned int salt, it, ip;
  930. decodePolyId(ref, salt, it, ip);
  931. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  932. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  933. if (ip >= (unsigned int)m_tiles[it].header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  934. *tile = &m_tiles[it];
  935. *poly = &m_tiles[it].polys[ip];
  936. return DT_SUCCESS;
  937. }
  938. /// @par
  939. ///
  940. /// @warning Only use this function if it is known that the provided polygon
  941. /// reference is valid. This function is faster than #getTileAndPolyByRef, but
  942. /// it does not validate the reference.
  943. void dtNavMesh::getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
  944. {
  945. unsigned int salt, it, ip;
  946. decodePolyId(ref, salt, it, ip);
  947. *tile = &m_tiles[it];
  948. *poly = &m_tiles[it].polys[ip];
  949. }
  950. bool dtNavMesh::isValidPolyRef(dtPolyRef ref) const
  951. {
  952. if (!ref) return false;
  953. unsigned int salt, it, ip;
  954. decodePolyId(ref, salt, it, ip);
  955. if (it >= (unsigned int)m_maxTiles) return false;
  956. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return false;
  957. if (ip >= (unsigned int)m_tiles[it].header->polyCount) return false;
  958. return true;
  959. }
  960. /// @par
  961. ///
  962. /// This function returns the data for the tile so that, if desired,
  963. /// it can be added back to the navigation mesh at a later point.
  964. ///
  965. /// @see #addTile
  966. dtStatus dtNavMesh::removeTile(dtTileRef ref, unsigned char** data, int* dataSize)
  967. {
  968. if (!ref)
  969. return DT_FAILURE | DT_INVALID_PARAM;
  970. unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
  971. unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
  972. if ((int)tileIndex >= m_maxTiles)
  973. return DT_FAILURE | DT_INVALID_PARAM;
  974. dtMeshTile* tile = &m_tiles[tileIndex];
  975. if (tile->salt != tileSalt)
  976. return DT_FAILURE | DT_INVALID_PARAM;
  977. // Remove tile from hash lookup.
  978. int h = computeTileHash(tile->header->x,tile->header->y,m_tileLutMask);
  979. dtMeshTile* prev = 0;
  980. dtMeshTile* cur = m_posLookup[h];
  981. while (cur)
  982. {
  983. if (cur == tile)
  984. {
  985. if (prev)
  986. prev->next = cur->next;
  987. else
  988. m_posLookup[h] = cur->next;
  989. break;
  990. }
  991. prev = cur;
  992. cur = cur->next;
  993. }
  994. // Remove connections to neighbour tiles.
  995. // Create connections with neighbour tiles.
  996. static const int MAX_NEIS = 32;
  997. dtMeshTile* neis[MAX_NEIS];
  998. int nneis;
  999. // Connect with layers in current tile.
  1000. nneis = getTilesAt(tile->header->x, tile->header->y, neis, MAX_NEIS);
  1001. for (int j = 0; j < nneis; ++j)
  1002. {
  1003. if (neis[j] == tile) continue;
  1004. unconnectExtLinks(neis[j], tile);
  1005. }
  1006. // Connect with neighbour tiles.
  1007. for (int i = 0; i < 8; ++i)
  1008. {
  1009. nneis = getNeighbourTilesAt(tile->header->x, tile->header->y, i, neis, MAX_NEIS);
  1010. for (int j = 0; j < nneis; ++j)
  1011. unconnectExtLinks(neis[j], tile);
  1012. }
  1013. // Reset tile.
  1014. if (tile->flags & DT_TILE_FREE_DATA)
  1015. {
  1016. // Owns data
  1017. dtFree(tile->data);
  1018. tile->data = 0;
  1019. tile->dataSize = 0;
  1020. if (data) *data = 0;
  1021. if (dataSize) *dataSize = 0;
  1022. }
  1023. else
  1024. {
  1025. if (data) *data = tile->data;
  1026. if (dataSize) *dataSize = tile->dataSize;
  1027. }
  1028. tile->header = 0;
  1029. tile->flags = 0;
  1030. tile->linksFreeList = 0;
  1031. tile->polys = 0;
  1032. tile->verts = 0;
  1033. tile->links = 0;
  1034. tile->detailMeshes = 0;
  1035. tile->detailVerts = 0;
  1036. tile->detailTris = 0;
  1037. tile->bvTree = 0;
  1038. tile->offMeshCons = 0;
  1039. // Update salt, salt should never be zero.
  1040. tile->salt = (tile->salt+1) & ((1<<m_saltBits)-1);
  1041. if (tile->salt == 0)
  1042. tile->salt++;
  1043. // Add to free list.
  1044. tile->next = m_nextFree;
  1045. m_nextFree = tile;
  1046. return DT_SUCCESS;
  1047. }
  1048. dtTileRef dtNavMesh::getTileRef(const dtMeshTile* tile) const
  1049. {
  1050. if (!tile) return 0;
  1051. const unsigned int it = (unsigned int)(tile - m_tiles);
  1052. return (dtTileRef)encodePolyId(tile->salt, it, 0);
  1053. }
  1054. /// @par
  1055. ///
  1056. /// Example use case:
  1057. /// @code
  1058. ///
  1059. /// const dtPolyRef base = navmesh->getPolyRefBase(tile);
  1060. /// for (int i = 0; i < tile->header->polyCount; ++i)
  1061. /// {
  1062. /// const dtPoly* p = &tile->polys[i];
  1063. /// const dtPolyRef ref = base | (dtPolyRef)i;
  1064. ///
  1065. /// // Use the reference to access the polygon data.
  1066. /// }
  1067. /// @endcode
  1068. dtPolyRef dtNavMesh::getPolyRefBase(const dtMeshTile* tile) const
  1069. {
  1070. if (!tile) return 0;
  1071. const unsigned int it = (unsigned int)(tile - m_tiles);
  1072. return encodePolyId(tile->salt, it, 0);
  1073. }
  1074. struct dtTileState
  1075. {
  1076. int magic; // Magic number, used to identify the data.
  1077. int version; // Data version number.
  1078. dtTileRef ref; // Tile ref at the time of storing the data.
  1079. };
  1080. struct dtPolyState
  1081. {
  1082. unsigned short flags; // Flags (see dtPolyFlags).
  1083. unsigned char area; // Area ID of the polygon.
  1084. };
  1085. /// @see #storeTileState
  1086. int dtNavMesh::getTileStateSize(const dtMeshTile* tile) const
  1087. {
  1088. if (!tile) return 0;
  1089. const int headerSize = dtAlign4(sizeof(dtTileState));
  1090. const int polyStateSize = dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1091. return headerSize + polyStateSize;
  1092. }
  1093. /// @par
  1094. ///
  1095. /// Tile state includes non-structural data such as polygon flags, area ids, etc.
  1096. /// @note The state data is only valid until the tile reference changes.
  1097. /// @see #getTileStateSize, #restoreTileState
  1098. dtStatus dtNavMesh::storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const
  1099. {
  1100. // Make sure there is enough space to store the state.
  1101. const int sizeReq = getTileStateSize(tile);
  1102. if (maxDataSize < sizeReq)
  1103. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1104. dtTileState* tileState = (dtTileState*)data; data += dtAlign4(sizeof(dtTileState));
  1105. dtPolyState* polyStates = (dtPolyState*)data; data += dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1106. // Store tile state.
  1107. tileState->magic = DT_NAVMESH_STATE_MAGIC;
  1108. tileState->version = DT_NAVMESH_STATE_VERSION;
  1109. tileState->ref = getTileRef(tile);
  1110. // Store per poly state.
  1111. for (int i = 0; i < tile->header->polyCount; ++i)
  1112. {
  1113. const dtPoly* p = &tile->polys[i];
  1114. dtPolyState* s = &polyStates[i];
  1115. s->flags = p->flags;
  1116. s->area = p->getArea();
  1117. }
  1118. return DT_SUCCESS;
  1119. }
  1120. /// @par
  1121. ///
  1122. /// Tile state includes non-structural data such as polygon flags, area ids, etc.
  1123. /// @note This function does not impact the tile's #dtTileRef and #dtPolyRef's.
  1124. /// @see #storeTileState
  1125. dtStatus dtNavMesh::restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize)
  1126. {
  1127. // Make sure there is enough space to store the state.
  1128. const int sizeReq = getTileStateSize(tile);
  1129. if (maxDataSize < sizeReq)
  1130. return DT_FAILURE | DT_INVALID_PARAM;
  1131. const dtTileState* tileState = (const dtTileState*)data; data += dtAlign4(sizeof(dtTileState));
  1132. const dtPolyState* polyStates = (const dtPolyState*)data; data += dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1133. // Check that the restore is possible.
  1134. if (tileState->magic != DT_NAVMESH_STATE_MAGIC)
  1135. return DT_FAILURE | DT_WRONG_MAGIC;
  1136. if (tileState->version != DT_NAVMESH_STATE_VERSION)
  1137. return DT_FAILURE | DT_WRONG_VERSION;
  1138. if (tileState->ref != getTileRef(tile))
  1139. return DT_FAILURE | DT_INVALID_PARAM;
  1140. // Restore per poly state.
  1141. for (int i = 0; i < tile->header->polyCount; ++i)
  1142. {
  1143. dtPoly* p = &tile->polys[i];
  1144. const dtPolyState* s = &polyStates[i];
  1145. p->flags = s->flags;
  1146. p->setArea(s->area);
  1147. }
  1148. return DT_SUCCESS;
  1149. }
  1150. /// @par
  1151. ///
  1152. /// Off-mesh connections are stored in the navigation mesh as special 2-vertex
  1153. /// polygons with a single edge. At least one of the vertices is expected to be
  1154. /// inside a normal polygon. So an off-mesh connection is "entered" from a
  1155. /// normal polygon at one of its endpoints. This is the polygon identified by
  1156. /// the prevRef parameter.
  1157. dtStatus dtNavMesh::getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const
  1158. {
  1159. unsigned int salt, it, ip;
  1160. if (!polyRef)
  1161. return DT_FAILURE;
  1162. // Get current polygon
  1163. decodePolyId(polyRef, salt, it, ip);
  1164. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1165. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1166. const dtMeshTile* tile = &m_tiles[it];
  1167. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1168. const dtPoly* poly = &tile->polys[ip];
  1169. // Make sure that the current poly is indeed off-mesh link.
  1170. if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
  1171. return DT_FAILURE;
  1172. // Figure out which way to hand out the vertices.
  1173. int idx0 = 0, idx1 = 1;
  1174. // Find link that points to first vertex.
  1175. for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next)
  1176. {
  1177. if (tile->links[i].edge == 0)
  1178. {
  1179. if (tile->links[i].ref != prevRef)
  1180. {
  1181. idx0 = 1;
  1182. idx1 = 0;
  1183. }
  1184. break;
  1185. }
  1186. }
  1187. dtVcopy(startPos, &tile->verts[poly->verts[idx0]*3]);
  1188. dtVcopy(endPos, &tile->verts[poly->verts[idx1]*3]);
  1189. return DT_SUCCESS;
  1190. }
  1191. const dtOffMeshConnection* dtNavMesh::getOffMeshConnectionByRef(dtPolyRef ref) const
  1192. {
  1193. unsigned int salt, it, ip;
  1194. if (!ref)
  1195. return 0;
  1196. // Get current polygon
  1197. decodePolyId(ref, salt, it, ip);
  1198. if (it >= (unsigned int)m_maxTiles) return 0;
  1199. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return 0;
  1200. const dtMeshTile* tile = &m_tiles[it];
  1201. if (ip >= (unsigned int)tile->header->polyCount) return 0;
  1202. const dtPoly* poly = &tile->polys[ip];
  1203. // Make sure that the current poly is indeed off-mesh link.
  1204. if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
  1205. return 0;
  1206. const unsigned int idx = ip - tile->header->offMeshBase;
  1207. dtAssert(idx < (unsigned int)tile->header->offMeshConCount);
  1208. return &tile->offMeshCons[idx];
  1209. }
  1210. dtStatus dtNavMesh::setPolyFlags(dtPolyRef ref, unsigned short flags)
  1211. {
  1212. if (!ref) return DT_FAILURE;
  1213. unsigned int salt, it, ip;
  1214. decodePolyId(ref, salt, it, ip);
  1215. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1216. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1217. dtMeshTile* tile = &m_tiles[it];
  1218. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1219. dtPoly* poly = &tile->polys[ip];
  1220. // Change flags.
  1221. poly->flags = flags;
  1222. return DT_SUCCESS;
  1223. }
  1224. dtStatus dtNavMesh::getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const
  1225. {
  1226. if (!ref) return DT_FAILURE;
  1227. unsigned int salt, it, ip;
  1228. decodePolyId(ref, salt, it, ip);
  1229. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1230. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1231. const dtMeshTile* tile = &m_tiles[it];
  1232. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1233. const dtPoly* poly = &tile->polys[ip];
  1234. *resultFlags = poly->flags;
  1235. return DT_SUCCESS;
  1236. }
  1237. dtStatus dtNavMesh::setPolyArea(dtPolyRef ref, unsigned char area)
  1238. {
  1239. if (!ref) return DT_FAILURE;
  1240. unsigned int salt, it, ip;
  1241. decodePolyId(ref, salt, it, ip);
  1242. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1243. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1244. dtMeshTile* tile = &m_tiles[it];
  1245. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1246. dtPoly* poly = &tile->polys[ip];
  1247. poly->setArea(area);
  1248. return DT_SUCCESS;
  1249. }
  1250. dtStatus dtNavMesh::getPolyArea(dtPolyRef ref, unsigned char* resultArea) const
  1251. {
  1252. if (!ref) return DT_FAILURE;
  1253. unsigned int salt, it, ip;
  1254. decodePolyId(ref, salt, it, ip);
  1255. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1256. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1257. const dtMeshTile* tile = &m_tiles[it];
  1258. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1259. const dtPoly* poly = &tile->polys[ip];
  1260. *resultArea = poly->getArea();
  1261. return DT_SUCCESS;
  1262. }