RecastLayers.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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 "Recast.h"
  25. #include "RecastAlloc.h"
  26. #include "RecastAssert.h"
  27. static const int RC_MAX_LAYERS = RC_NOT_CONNECTED;
  28. static const int RC_MAX_NEIS = 16;
  29. struct rcLayerRegion
  30. {
  31. unsigned char layers[RC_MAX_LAYERS];
  32. unsigned char neis[RC_MAX_NEIS];
  33. unsigned short ymin, ymax;
  34. unsigned char layerId; // Layer ID
  35. unsigned char nlayers; // Layer count
  36. unsigned char nneis; // Neighbour count
  37. unsigned char base; // Flag indicating if the region is the base of merged regions.
  38. };
  39. static void addUnique(unsigned char* a, unsigned char& an, unsigned char v)
  40. {
  41. const int n = (int)an;
  42. for (int i = 0; i < n; ++i)
  43. if (a[i] == v)
  44. return;
  45. a[an] = v;
  46. an++;
  47. }
  48. static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v)
  49. {
  50. const int n = (int)an;
  51. for (int i = 0; i < n; ++i)
  52. if (a[i] == v)
  53. return true;
  54. return false;
  55. }
  56. inline bool overlapRange(const unsigned short amin, const unsigned short amax,
  57. const unsigned short bmin, const unsigned short bmax)
  58. {
  59. return (amin > bmax || amax < bmin) ? false : true;
  60. }
  61. struct rcLayerSweepSpan
  62. {
  63. unsigned short ns; // number samples
  64. unsigned char id; // region id
  65. unsigned char nei; // neighbour id
  66. };
  67. /// @par
  68. ///
  69. /// See the #rcConfig documentation for more information on the configuration parameters.
  70. ///
  71. /// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig
  72. bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
  73. const int borderSize, const int walkableHeight,
  74. rcHeightfieldLayerSet& lset)
  75. {
  76. rcAssert(ctx);
  77. ctx->startTimer(RC_TIMER_BUILD_LAYERS);
  78. const int w = chf.width;
  79. const int h = chf.height;
  80. rcScopedDelete<unsigned char> srcReg = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
  81. if (!srcReg)
  82. {
  83. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
  84. return false;
  85. }
  86. memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
  87. const int nsweeps = chf.width;
  88. rcScopedDelete<rcLayerSweepSpan> sweeps = (rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP);
  89. if (!sweeps)
  90. {
  91. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
  92. return false;
  93. }
  94. // Partition walkable area into monotone regions.
  95. int prevCount[256];
  96. unsigned char regId = 0;
  97. for (int y = borderSize; y < h-borderSize; ++y)
  98. {
  99. memset(prevCount,0,sizeof(int)*regId);
  100. unsigned char sweepId = 0;
  101. for (int x = borderSize; x < w-borderSize; ++x)
  102. {
  103. const rcCompactCell& c = chf.cells[x+y*w];
  104. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  105. {
  106. const rcCompactSpan& s = chf.spans[i];
  107. if (chf.areas[i] == RC_NULL_AREA) continue;
  108. unsigned char sid = 0xff;
  109. // -x
  110. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  111. {
  112. const int ax = x + rcGetDirOffsetX(0);
  113. const int ay = y + rcGetDirOffsetY(0);
  114. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  115. if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)
  116. sid = srcReg[ai];
  117. }
  118. if (sid == 0xff)
  119. {
  120. sid = sweepId++;
  121. sweeps[sid].nei = 0xff;
  122. sweeps[sid].ns = 0;
  123. }
  124. // -y
  125. if (rcGetCon(s,3) != RC_NOT_CONNECTED)
  126. {
  127. const int ax = x + rcGetDirOffsetX(3);
  128. const int ay = y + rcGetDirOffsetY(3);
  129. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  130. const unsigned char nr = srcReg[ai];
  131. if (nr != 0xff)
  132. {
  133. // Set neighbour when first valid neighbour is encoutered.
  134. if (sweeps[sid].ns == 0)
  135. sweeps[sid].nei = nr;
  136. if (sweeps[sid].nei == nr)
  137. {
  138. // Update existing neighbour
  139. sweeps[sid].ns++;
  140. prevCount[nr]++;
  141. }
  142. else
  143. {
  144. // This is hit if there is nore than one neighbour.
  145. // Invalidate the neighbour.
  146. sweeps[sid].nei = 0xff;
  147. }
  148. }
  149. }
  150. srcReg[i] = sid;
  151. }
  152. }
  153. // Create unique ID.
  154. for (int i = 0; i < sweepId; ++i)
  155. {
  156. // If the neighbour is set and there is only one continuous connection to it,
  157. // the sweep will be merged with the previous one, else new region is created.
  158. if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns)
  159. {
  160. sweeps[i].id = sweeps[i].nei;
  161. }
  162. else
  163. {
  164. if (regId == 255)
  165. {
  166. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow.");
  167. return false;
  168. }
  169. sweeps[i].id = regId++;
  170. }
  171. }
  172. // Remap local sweep ids to region ids.
  173. for (int x = borderSize; x < w-borderSize; ++x)
  174. {
  175. const rcCompactCell& c = chf.cells[x+y*w];
  176. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  177. {
  178. if (srcReg[i] != 0xff)
  179. srcReg[i] = sweeps[srcReg[i]].id;
  180. }
  181. }
  182. }
  183. // Allocate and init layer regions.
  184. const int nregs = (int)regId;
  185. rcScopedDelete<rcLayerRegion> regs = (rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP);
  186. if (!regs)
  187. {
  188. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
  189. return false;
  190. }
  191. memset(regs, 0, sizeof(rcLayerRegion)*nregs);
  192. for (int i = 0; i < nregs; ++i)
  193. {
  194. regs[i].layerId = 0xff;
  195. regs[i].ymin = 0xffff;
  196. regs[i].ymax = 0;
  197. }
  198. // Find region neighbours and overlapping regions.
  199. for (int y = 0; y < h; ++y)
  200. {
  201. for (int x = 0; x < w; ++x)
  202. {
  203. const rcCompactCell& c = chf.cells[x+y*w];
  204. unsigned char lregs[RC_MAX_LAYERS];
  205. int nlregs = 0;
  206. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  207. {
  208. const rcCompactSpan& s = chf.spans[i];
  209. const unsigned char ri = srcReg[i];
  210. if (ri == 0xff) continue;
  211. regs[ri].ymin = rcMin(regs[ri].ymin, s.y);
  212. regs[ri].ymax = rcMax(regs[ri].ymax, s.y);
  213. // Collect all region layers.
  214. if (nlregs < RC_MAX_LAYERS)
  215. lregs[nlregs++] = ri;
  216. // Update neighbours
  217. for (int dir = 0; dir < 4; ++dir)
  218. {
  219. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  220. {
  221. const int ax = x + rcGetDirOffsetX(dir);
  222. const int ay = y + rcGetDirOffsetY(dir);
  223. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  224. const unsigned char rai = srcReg[ai];
  225. if (rai != 0xff && rai != ri)
  226. addUnique(regs[ri].neis, regs[ri].nneis, rai);
  227. }
  228. }
  229. }
  230. // Update overlapping regions.
  231. for (int i = 0; i < nlregs-1; ++i)
  232. {
  233. for (int j = i+1; j < nlregs; ++j)
  234. {
  235. if (lregs[i] != lregs[j])
  236. {
  237. rcLayerRegion& ri = regs[lregs[i]];
  238. rcLayerRegion& rj = regs[lregs[j]];
  239. addUnique(ri.layers, ri.nlayers, lregs[j]);
  240. addUnique(rj.layers, rj.nlayers, lregs[i]);
  241. }
  242. }
  243. }
  244. }
  245. }
  246. // Create 2D layers from regions.
  247. unsigned char layerId = 0;
  248. static const int MAX_STACK = 64;
  249. unsigned char stack[MAX_STACK];
  250. int nstack = 0;
  251. for (int i = 0; i < nregs; ++i)
  252. {
  253. rcLayerRegion& root = regs[i];
  254. // Skip already visited.
  255. if (root.layerId != 0xff)
  256. continue;
  257. // Start search.
  258. root.layerId = layerId;
  259. root.base = 1;
  260. nstack = 0;
  261. stack[nstack++] = (unsigned char)i;
  262. while (nstack)
  263. {
  264. // Pop front
  265. rcLayerRegion& reg = regs[stack[0]];
  266. nstack--;
  267. for (int j = 0; j < nstack; ++j)
  268. stack[j] = stack[j+1];
  269. const int nneis = (int)reg.nneis;
  270. for (int j = 0; j < nneis; ++j)
  271. {
  272. const unsigned char nei = reg.neis[j];
  273. rcLayerRegion& regn = regs[nei];
  274. // Skip already visited.
  275. if (regn.layerId != 0xff)
  276. continue;
  277. // Skip if the neighbour is overlapping root region.
  278. if (contains(root.layers, root.nlayers, nei))
  279. continue;
  280. // Skip if the height range would become too large.
  281. const int ymin = rcMin(root.ymin, regn.ymin);
  282. const int ymax = rcMax(root.ymax, regn.ymax);
  283. if ((ymax - ymin) >= 255)
  284. continue;
  285. if (nstack < MAX_STACK)
  286. {
  287. // Deepen
  288. stack[nstack++] = (unsigned char)nei;
  289. // Mark layer id
  290. regn.layerId = layerId;
  291. // Merge current layers to root.
  292. for (int k = 0; k < regn.nlayers; ++k)
  293. addUnique(root.layers, root.nlayers, regn.layers[k]);
  294. root.ymin = rcMin(root.ymin, regn.ymin);
  295. root.ymax = rcMax(root.ymax, regn.ymax);
  296. }
  297. }
  298. }
  299. layerId++;
  300. }
  301. // Merge non-overlapping regions that are close in height.
  302. const unsigned short mergeHeight = (unsigned short)walkableHeight * 4;
  303. for (int i = 0; i < nregs; ++i)
  304. {
  305. rcLayerRegion& ri = regs[i];
  306. if (!ri.base) continue;
  307. unsigned char newId = ri.layerId;
  308. for (;;)
  309. {
  310. unsigned char oldId = 0xff;
  311. for (int j = 0; j < nregs; ++j)
  312. {
  313. if (i == j) continue;
  314. rcLayerRegion& rj = regs[j];
  315. if (!rj.base) continue;
  316. // Skip if the regions are not close to each other.
  317. if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight))
  318. continue;
  319. // Skip if the height range would become too large.
  320. const int ymin = rcMin(ri.ymin, rj.ymin);
  321. const int ymax = rcMax(ri.ymax, rj.ymax);
  322. if ((ymax - ymin) >= 255)
  323. continue;
  324. // Make sure that there is no overlap when merging 'ri' and 'rj'.
  325. bool overlap = false;
  326. // Iterate over all regions which have the same layerId as 'rj'
  327. for (int k = 0; k < nregs; ++k)
  328. {
  329. if (regs[k].layerId != rj.layerId)
  330. continue;
  331. // Check if region 'k' is overlapping region 'ri'
  332. // Index to 'regs' is the same as region id.
  333. if (contains(ri.layers,ri.nlayers, (unsigned char)k))
  334. {
  335. overlap = true;
  336. break;
  337. }
  338. }
  339. // Cannot merge of regions overlap.
  340. if (overlap)
  341. continue;
  342. // Can merge i and j.
  343. oldId = rj.layerId;
  344. break;
  345. }
  346. // Could not find anything to merge with, stop.
  347. if (oldId == 0xff)
  348. break;
  349. // Merge
  350. for (int j = 0; j < nregs; ++j)
  351. {
  352. rcLayerRegion& rj = regs[j];
  353. if (rj.layerId == oldId)
  354. {
  355. rj.base = 0;
  356. // Remap layerIds.
  357. rj.layerId = newId;
  358. // Add overlaid layers from 'rj' to 'ri'.
  359. for (int k = 0; k < rj.nlayers; ++k)
  360. addUnique(ri.layers, ri.nlayers, rj.layers[k]);
  361. // Update height bounds.
  362. ri.ymin = rcMin(ri.ymin, rj.ymin);
  363. ri.ymax = rcMax(ri.ymax, rj.ymax);
  364. }
  365. }
  366. }
  367. }
  368. // Compact layerIds
  369. unsigned char remap[256];
  370. memset(remap, 0, 256);
  371. // Find number of unique layers.
  372. layerId = 0;
  373. for (int i = 0; i < nregs; ++i)
  374. remap[regs[i].layerId] = 1;
  375. for (int i = 0; i < 256; ++i)
  376. {
  377. if (remap[i])
  378. remap[i] = layerId++;
  379. else
  380. remap[i] = 0xff;
  381. }
  382. // Remap ids.
  383. for (int i = 0; i < nregs; ++i)
  384. regs[i].layerId = remap[regs[i].layerId];
  385. // No layers, return empty.
  386. if (layerId == 0)
  387. {
  388. ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
  389. return true;
  390. }
  391. // Create layers.
  392. rcAssert(lset.layers == 0);
  393. const int lw = w - borderSize*2;
  394. const int lh = h - borderSize*2;
  395. // Build contracted bbox for layers.
  396. float bmin[3], bmax[3];
  397. rcVcopy(bmin, chf.bmin);
  398. rcVcopy(bmax, chf.bmax);
  399. bmin[0] += borderSize*chf.cs;
  400. bmin[2] += borderSize*chf.cs;
  401. bmax[0] -= borderSize*chf.cs;
  402. bmax[2] -= borderSize*chf.cs;
  403. lset.nlayers = (int)layerId;
  404. lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM);
  405. if (!lset.layers)
  406. {
  407. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers);
  408. return false;
  409. }
  410. memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers);
  411. // Store layers.
  412. for (int i = 0; i < lset.nlayers; ++i)
  413. {
  414. unsigned char curId = (unsigned char)i;
  415. rcHeightfieldLayer* layer = &lset.layers[i];
  416. const int gridSize = sizeof(unsigned char)*lw*lh;
  417. layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
  418. if (!layer->heights)
  419. {
  420. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize);
  421. return false;
  422. }
  423. memset(layer->heights, 0xff, gridSize);
  424. layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
  425. if (!layer->areas)
  426. {
  427. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize);
  428. return false;
  429. }
  430. memset(layer->areas, 0, gridSize);
  431. layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
  432. if (!layer->cons)
  433. {
  434. ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize);
  435. return false;
  436. }
  437. memset(layer->cons, 0, gridSize);
  438. // Find layer height bounds.
  439. int hmin = 0, hmax = 0;
  440. for (int j = 0; j < nregs; ++j)
  441. {
  442. if (regs[j].base && regs[j].layerId == curId)
  443. {
  444. hmin = (int)regs[j].ymin;
  445. hmax = (int)regs[j].ymax;
  446. }
  447. }
  448. layer->width = lw;
  449. layer->height = lh;
  450. layer->cs = chf.cs;
  451. layer->ch = chf.ch;
  452. // Adjust the bbox to fit the heightfield.
  453. rcVcopy(layer->bmin, bmin);
  454. rcVcopy(layer->bmax, bmax);
  455. layer->bmin[1] = bmin[1] + hmin*chf.ch;
  456. layer->bmax[1] = bmin[1] + hmax*chf.ch;
  457. layer->hmin = hmin;
  458. layer->hmax = hmax;
  459. // Update usable data region.
  460. layer->minx = layer->width;
  461. layer->maxx = 0;
  462. layer->miny = layer->height;
  463. layer->maxy = 0;
  464. // Copy height and area from compact heightfield.
  465. for (int y = 0; y < lh; ++y)
  466. {
  467. for (int x = 0; x < lw; ++x)
  468. {
  469. const int cx = borderSize+x;
  470. const int cy = borderSize+y;
  471. const rcCompactCell& c = chf.cells[cx+cy*w];
  472. for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
  473. {
  474. const rcCompactSpan& s = chf.spans[j];
  475. // Skip unassigned regions.
  476. if (srcReg[j] == 0xff)
  477. continue;
  478. // Skip of does nto belong to current layer.
  479. unsigned char lid = regs[srcReg[j]].layerId;
  480. if (lid != curId)
  481. continue;
  482. // Update data bounds.
  483. layer->minx = rcMin(layer->minx, x);
  484. layer->maxx = rcMax(layer->maxx, x);
  485. layer->miny = rcMin(layer->miny, y);
  486. layer->maxy = rcMax(layer->maxy, y);
  487. // Store height and area type.
  488. const int idx = x+y*lw;
  489. layer->heights[idx] = (unsigned char)(s.y - hmin);
  490. layer->areas[idx] = chf.areas[j];
  491. // Check connection.
  492. unsigned char portal = 0;
  493. unsigned char con = 0;
  494. for (int dir = 0; dir < 4; ++dir)
  495. {
  496. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  497. {
  498. const int ax = cx + rcGetDirOffsetX(dir);
  499. const int ay = cy + rcGetDirOffsetY(dir);
  500. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  501. unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;
  502. // Portal mask
  503. if (chf.areas[ai] != RC_NULL_AREA && lid != alid)
  504. {
  505. portal |= (unsigned char)(1<<dir);
  506. // Update height so that it matches on both sides of the portal.
  507. const rcCompactSpan& as = chf.spans[ai];
  508. if (as.y > hmin)
  509. layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin));
  510. }
  511. // Valid connection mask
  512. if (chf.areas[ai] != RC_NULL_AREA && lid == alid)
  513. {
  514. const int nx = ax - borderSize;
  515. const int ny = ay - borderSize;
  516. if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)
  517. con |= (unsigned char)(1<<dir);
  518. }
  519. }
  520. }
  521. layer->cons[idx] = (portal << 4) | con;
  522. }
  523. }
  524. }
  525. if (layer->minx > layer->maxx)
  526. layer->minx = layer->maxx = 0;
  527. if (layer->miny > layer->maxy)
  528. layer->miny = layer->maxy = 0;
  529. }
  530. ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
  531. return true;
  532. }