Recast.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. #define _USE_MATH_DEFINES
  20. #include <math.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <stdarg.h>
  25. #include <new>
  26. #include "Recast.h"
  27. #include "RecastAlloc.h"
  28. #include "RecastAssert.h"
  29. float rcSqrt(float x)
  30. {
  31. return sqrtf(x);
  32. }
  33. /// @class rcContext
  34. /// @par
  35. ///
  36. /// This class does not provide logging or timer functionality on its
  37. /// own. Both must be provided by a concrete implementation
  38. /// by overriding the protected member functions. Also, this class does not
  39. /// provide an interface for extracting log messages. (Only adding them.)
  40. /// So concrete implementations must provide one.
  41. ///
  42. /// If no logging or timers are required, just pass an instance of this
  43. /// class through the Recast build process.
  44. ///
  45. /// @par
  46. ///
  47. /// Example:
  48. /// @code
  49. /// // Where ctx is an instance of rcContext and filepath is a char array.
  50. /// ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath);
  51. /// @endcode
  52. void rcContext::log(const rcLogCategory category, const char* format, ...)
  53. {
  54. if (!m_logEnabled)
  55. return;
  56. static const int MSG_SIZE = 512;
  57. char msg[MSG_SIZE];
  58. va_list ap;
  59. va_start(ap, format);
  60. int len = vsnprintf(msg, MSG_SIZE, format, ap);
  61. if (len >= MSG_SIZE)
  62. {
  63. len = MSG_SIZE-1;
  64. msg[MSG_SIZE-1] = '\0';
  65. }
  66. va_end(ap);
  67. doLog(category, msg, len);
  68. }
  69. rcHeightfield* rcAllocHeightfield()
  70. {
  71. return new (rcAlloc(sizeof(rcHeightfield), RC_ALLOC_PERM)) rcHeightfield;
  72. }
  73. rcHeightfield::rcHeightfield()
  74. : width()
  75. , height()
  76. , bmin()
  77. , bmax()
  78. , cs()
  79. , ch()
  80. , spans()
  81. , pools()
  82. , freelist()
  83. {
  84. }
  85. rcHeightfield::~rcHeightfield()
  86. {
  87. // Delete span array.
  88. rcFree(spans);
  89. // Delete span pools.
  90. while (pools)
  91. {
  92. rcSpanPool* next = pools->next;
  93. rcFree(pools);
  94. pools = next;
  95. }
  96. }
  97. void rcFreeHeightField(rcHeightfield* hf)
  98. {
  99. if (!hf) return;
  100. hf->~rcHeightfield();
  101. rcFree(hf);
  102. }
  103. rcCompactHeightfield* rcAllocCompactHeightfield()
  104. {
  105. rcCompactHeightfield* chf = (rcCompactHeightfield*)rcAlloc(sizeof(rcCompactHeightfield), RC_ALLOC_PERM);
  106. memset(chf, 0, sizeof(rcCompactHeightfield));
  107. return chf;
  108. }
  109. void rcFreeCompactHeightfield(rcCompactHeightfield* chf)
  110. {
  111. if (!chf) return;
  112. rcFree(chf->cells);
  113. rcFree(chf->spans);
  114. rcFree(chf->dist);
  115. rcFree(chf->areas);
  116. rcFree(chf);
  117. }
  118. rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet()
  119. {
  120. rcHeightfieldLayerSet* lset = (rcHeightfieldLayerSet*)rcAlloc(sizeof(rcHeightfieldLayerSet), RC_ALLOC_PERM);
  121. memset(lset, 0, sizeof(rcHeightfieldLayerSet));
  122. return lset;
  123. }
  124. void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* lset)
  125. {
  126. if (!lset) return;
  127. for (int i = 0; i < lset->nlayers; ++i)
  128. {
  129. rcFree(lset->layers[i].heights);
  130. rcFree(lset->layers[i].areas);
  131. rcFree(lset->layers[i].cons);
  132. }
  133. rcFree(lset->layers);
  134. rcFree(lset);
  135. }
  136. rcContourSet* rcAllocContourSet()
  137. {
  138. rcContourSet* cset = (rcContourSet*)rcAlloc(sizeof(rcContourSet), RC_ALLOC_PERM);
  139. memset(cset, 0, sizeof(rcContourSet));
  140. return cset;
  141. }
  142. void rcFreeContourSet(rcContourSet* cset)
  143. {
  144. if (!cset) return;
  145. for (int i = 0; i < cset->nconts; ++i)
  146. {
  147. rcFree(cset->conts[i].verts);
  148. rcFree(cset->conts[i].rverts);
  149. }
  150. rcFree(cset->conts);
  151. rcFree(cset);
  152. }
  153. rcPolyMesh* rcAllocPolyMesh()
  154. {
  155. rcPolyMesh* pmesh = (rcPolyMesh*)rcAlloc(sizeof(rcPolyMesh), RC_ALLOC_PERM);
  156. memset(pmesh, 0, sizeof(rcPolyMesh));
  157. return pmesh;
  158. }
  159. void rcFreePolyMesh(rcPolyMesh* pmesh)
  160. {
  161. if (!pmesh) return;
  162. rcFree(pmesh->verts);
  163. rcFree(pmesh->polys);
  164. rcFree(pmesh->regs);
  165. rcFree(pmesh->flags);
  166. rcFree(pmesh->areas);
  167. rcFree(pmesh);
  168. }
  169. rcPolyMeshDetail* rcAllocPolyMeshDetail()
  170. {
  171. rcPolyMeshDetail* dmesh = (rcPolyMeshDetail*)rcAlloc(sizeof(rcPolyMeshDetail), RC_ALLOC_PERM);
  172. memset(dmesh, 0, sizeof(rcPolyMeshDetail));
  173. return dmesh;
  174. }
  175. void rcFreePolyMeshDetail(rcPolyMeshDetail* dmesh)
  176. {
  177. if (!dmesh) return;
  178. rcFree(dmesh->meshes);
  179. rcFree(dmesh->verts);
  180. rcFree(dmesh->tris);
  181. rcFree(dmesh);
  182. }
  183. void rcCalcBounds(const float* verts, int nv, float* bmin, float* bmax)
  184. {
  185. // Calculate bounding box.
  186. rcVcopy(bmin, verts);
  187. rcVcopy(bmax, verts);
  188. for (int i = 1; i < nv; ++i)
  189. {
  190. const float* v = &verts[i*3];
  191. rcVmin(bmin, v);
  192. rcVmax(bmax, v);
  193. }
  194. }
  195. void rcCalcGridSize(const float* bmin, const float* bmax, float cs, int* w, int* h)
  196. {
  197. *w = (int)((bmax[0] - bmin[0])/cs+0.5f);
  198. *h = (int)((bmax[2] - bmin[2])/cs+0.5f);
  199. }
  200. /// @par
  201. ///
  202. /// See the #rcConfig documentation for more information on the configuration parameters.
  203. ///
  204. /// @see rcAllocHeightfield, rcHeightfield
  205. bool rcCreateHeightfield(rcContext* ctx, rcHeightfield& hf, int width, int height,
  206. const float* bmin, const float* bmax,
  207. float cs, float ch)
  208. {
  209. rcIgnoreUnused(ctx);
  210. hf.width = width;
  211. hf.height = height;
  212. rcVcopy(hf.bmin, bmin);
  213. rcVcopy(hf.bmax, bmax);
  214. hf.cs = cs;
  215. hf.ch = ch;
  216. hf.spans = (rcSpan**)rcAlloc(sizeof(rcSpan*)*hf.width*hf.height, RC_ALLOC_PERM);
  217. if (!hf.spans)
  218. return false;
  219. memset(hf.spans, 0, sizeof(rcSpan*)*hf.width*hf.height);
  220. return true;
  221. }
  222. static void calcTriNormal(const float* v0, const float* v1, const float* v2, float* norm)
  223. {
  224. float e0[3], e1[3];
  225. rcVsub(e0, v1, v0);
  226. rcVsub(e1, v2, v0);
  227. rcVcross(norm, e0, e1);
  228. rcVnormalize(norm);
  229. }
  230. /// @par
  231. ///
  232. /// Only sets the area id's for the walkable triangles. Does not alter the
  233. /// area id's for unwalkable triangles.
  234. ///
  235. /// See the #rcConfig documentation for more information on the configuration parameters.
  236. ///
  237. /// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
  238. void rcMarkWalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
  239. const float* verts, int nv,
  240. const int* tris, int nt,
  241. unsigned char* areas)
  242. {
  243. rcIgnoreUnused(ctx);
  244. rcIgnoreUnused(nv);
  245. const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
  246. float norm[3];
  247. for (int i = 0; i < nt; ++i)
  248. {
  249. const int* tri = &tris[i*3];
  250. calcTriNormal(&verts[tri[0]*3], &verts[tri[1]*3], &verts[tri[2]*3], norm);
  251. // Check if the face is walkable.
  252. if (norm[1] > walkableThr)
  253. areas[i] = RC_WALKABLE_AREA;
  254. }
  255. }
  256. /// @par
  257. ///
  258. /// Only sets the area id's for the unwalkable triangles. Does not alter the
  259. /// area id's for walkable triangles.
  260. ///
  261. /// See the #rcConfig documentation for more information on the configuration parameters.
  262. ///
  263. /// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
  264. void rcClearUnwalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
  265. const float* verts, int /*nv*/,
  266. const int* tris, int nt,
  267. unsigned char* areas)
  268. {
  269. rcIgnoreUnused(ctx);
  270. const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
  271. float norm[3];
  272. for (int i = 0; i < nt; ++i)
  273. {
  274. const int* tri = &tris[i*3];
  275. calcTriNormal(&verts[tri[0]*3], &verts[tri[1]*3], &verts[tri[2]*3], norm);
  276. // Check if the face is walkable.
  277. if (norm[1] <= walkableThr)
  278. areas[i] = RC_NULL_AREA;
  279. }
  280. }
  281. int rcGetHeightFieldSpanCount(rcContext* ctx, rcHeightfield& hf)
  282. {
  283. rcIgnoreUnused(ctx);
  284. const int w = hf.width;
  285. const int h = hf.height;
  286. int spanCount = 0;
  287. for (int y = 0; y < h; ++y)
  288. {
  289. for (int x = 0; x < w; ++x)
  290. {
  291. for (rcSpan* s = hf.spans[x + y*w]; s; s = s->next)
  292. {
  293. if (s->area != RC_NULL_AREA)
  294. spanCount++;
  295. }
  296. }
  297. }
  298. return spanCount;
  299. }
  300. /// @par
  301. ///
  302. /// This is just the beginning of the process of fully building a compact heightfield.
  303. /// Various filters may be applied, then the distance field and regions built.
  304. /// E.g: #rcBuildDistanceField and #rcBuildRegions
  305. ///
  306. /// See the #rcConfig documentation for more information on the configuration parameters.
  307. ///
  308. /// @see rcAllocCompactHeightfield, rcHeightfield, rcCompactHeightfield, rcConfig
  309. bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const int walkableClimb,
  310. rcHeightfield& hf, rcCompactHeightfield& chf)
  311. {
  312. rcAssert(ctx);
  313. rcScopedTimer timer(ctx, RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
  314. const int w = hf.width;
  315. const int h = hf.height;
  316. const int spanCount = rcGetHeightFieldSpanCount(ctx, hf);
  317. // Fill in header.
  318. chf.width = w;
  319. chf.height = h;
  320. chf.spanCount = spanCount;
  321. chf.walkableHeight = walkableHeight;
  322. chf.walkableClimb = walkableClimb;
  323. chf.maxRegions = 0;
  324. rcVcopy(chf.bmin, hf.bmin);
  325. rcVcopy(chf.bmax, hf.bmax);
  326. chf.bmax[1] += walkableHeight*hf.ch;
  327. chf.cs = hf.cs;
  328. chf.ch = hf.ch;
  329. chf.cells = (rcCompactCell*)rcAlloc(sizeof(rcCompactCell)*w*h, RC_ALLOC_PERM);
  330. if (!chf.cells)
  331. {
  332. ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.cells' (%d)", w*h);
  333. return false;
  334. }
  335. memset(chf.cells, 0, sizeof(rcCompactCell)*w*h);
  336. chf.spans = (rcCompactSpan*)rcAlloc(sizeof(rcCompactSpan)*spanCount, RC_ALLOC_PERM);
  337. if (!chf.spans)
  338. {
  339. ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.spans' (%d)", spanCount);
  340. return false;
  341. }
  342. memset(chf.spans, 0, sizeof(rcCompactSpan)*spanCount);
  343. chf.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*spanCount, RC_ALLOC_PERM);
  344. if (!chf.areas)
  345. {
  346. ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.areas' (%d)", spanCount);
  347. return false;
  348. }
  349. memset(chf.areas, RC_NULL_AREA, sizeof(unsigned char)*spanCount);
  350. const int MAX_HEIGHT = 0xffff;
  351. // Fill in cells and spans.
  352. int idx = 0;
  353. for (int y = 0; y < h; ++y)
  354. {
  355. for (int x = 0; x < w; ++x)
  356. {
  357. const rcSpan* s = hf.spans[x + y*w];
  358. // If there are no spans at this cell, just leave the data to index=0, count=0.
  359. if (!s) continue;
  360. rcCompactCell& c = chf.cells[x+y*w];
  361. c.index = idx;
  362. c.count = 0;
  363. while (s)
  364. {
  365. if (s->area != RC_NULL_AREA)
  366. {
  367. const int bot = (int)s->smax;
  368. const int top = s->next ? (int)s->next->smin : MAX_HEIGHT;
  369. chf.spans[idx].y = (unsigned short)rcClamp(bot, 0, 0xffff);
  370. chf.spans[idx].h = (unsigned char)rcClamp(top - bot, 0, 0xff);
  371. chf.areas[idx] = s->area;
  372. idx++;
  373. c.count++;
  374. }
  375. s = s->next;
  376. }
  377. }
  378. }
  379. // Find neighbour connections.
  380. const int MAX_LAYERS = RC_NOT_CONNECTED-1;
  381. int tooHighNeighbour = 0;
  382. for (int y = 0; y < h; ++y)
  383. {
  384. for (int x = 0; x < w; ++x)
  385. {
  386. const rcCompactCell& c = chf.cells[x+y*w];
  387. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  388. {
  389. rcCompactSpan& s = chf.spans[i];
  390. for (int dir = 0; dir < 4; ++dir)
  391. {
  392. rcSetCon(s, dir, RC_NOT_CONNECTED);
  393. const int nx = x + rcGetDirOffsetX(dir);
  394. const int ny = y + rcGetDirOffsetY(dir);
  395. // First check that the neighbour cell is in bounds.
  396. if (nx < 0 || ny < 0 || nx >= w || ny >= h)
  397. continue;
  398. // Iterate over all neighbour spans and check if any of the is
  399. // accessible from current cell.
  400. const rcCompactCell& nc = chf.cells[nx+ny*w];
  401. for (int k = (int)nc.index, nk = (int)(nc.index+nc.count); k < nk; ++k)
  402. {
  403. const rcCompactSpan& ns = chf.spans[k];
  404. const int bot = rcMax(s.y, ns.y);
  405. const int top = rcMin(s.y+s.h, ns.y+ns.h);
  406. // Check that the gap between the spans is walkable,
  407. // and that the climb height between the gaps is not too high.
  408. if ((top - bot) >= walkableHeight && rcAbs((int)ns.y - (int)s.y) <= walkableClimb)
  409. {
  410. // Mark direction as walkable.
  411. const int lidx = k - (int)nc.index;
  412. if (lidx < 0 || lidx > MAX_LAYERS)
  413. {
  414. tooHighNeighbour = rcMax(tooHighNeighbour, lidx);
  415. continue;
  416. }
  417. rcSetCon(s, dir, lidx);
  418. break;
  419. }
  420. }
  421. }
  422. }
  423. }
  424. }
  425. if (tooHighNeighbour > MAX_LAYERS)
  426. {
  427. ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)",
  428. tooHighNeighbour, MAX_LAYERS);
  429. }
  430. return true;
  431. }
  432. /*
  433. static int getHeightfieldMemoryUsage(const rcHeightfield& hf)
  434. {
  435. int size = 0;
  436. size += sizeof(hf);
  437. size += hf.width * hf.height * sizeof(rcSpan*);
  438. rcSpanPool* pool = hf.pools;
  439. while (pool)
  440. {
  441. size += (sizeof(rcSpanPool) - sizeof(rcSpan)) + sizeof(rcSpan)*RC_SPANS_PER_POOL;
  442. pool = pool->next;
  443. }
  444. return size;
  445. }
  446. static int getCompactHeightFieldMemoryusage(const rcCompactHeightfield& chf)
  447. {
  448. int size = 0;
  449. size += sizeof(rcCompactHeightfield);
  450. size += sizeof(rcCompactSpan) * chf.spanCount;
  451. size += sizeof(rcCompactCell) * chf.width * chf.height;
  452. return size;
  453. }
  454. */