DetourNavMesh.cpp 42 KB

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