DetourNavMesh.cpp 42 KB

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