RecastRegion.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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. #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. #include <new>
  28. static void calculateDistanceField(rcCompactHeightfield& chf, unsigned short* src, unsigned short& maxDist)
  29. {
  30. const int w = chf.width;
  31. const int h = chf.height;
  32. // Init distance and points.
  33. for (int i = 0; i < chf.spanCount; ++i)
  34. src[i] = 0xffff;
  35. // Mark boundary cells.
  36. for (int y = 0; y < h; ++y)
  37. {
  38. for (int x = 0; x < w; ++x)
  39. {
  40. const rcCompactCell& c = chf.cells[x+y*w];
  41. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  42. {
  43. const rcCompactSpan& s = chf.spans[i];
  44. const unsigned char area = chf.areas[i];
  45. int nc = 0;
  46. for (int dir = 0; dir < 4; ++dir)
  47. {
  48. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  49. {
  50. const int ax = x + rcGetDirOffsetX(dir);
  51. const int ay = y + rcGetDirOffsetY(dir);
  52. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  53. if (area == chf.areas[ai])
  54. nc++;
  55. }
  56. }
  57. if (nc != 4)
  58. src[i] = 0;
  59. }
  60. }
  61. }
  62. // Pass 1
  63. for (int y = 0; y < h; ++y)
  64. {
  65. for (int x = 0; x < w; ++x)
  66. {
  67. const rcCompactCell& c = chf.cells[x+y*w];
  68. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  69. {
  70. const rcCompactSpan& s = chf.spans[i];
  71. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  72. {
  73. // (-1,0)
  74. const int ax = x + rcGetDirOffsetX(0);
  75. const int ay = y + rcGetDirOffsetY(0);
  76. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  77. const rcCompactSpan& as = chf.spans[ai];
  78. if (src[ai]+2 < src[i])
  79. src[i] = src[ai]+2;
  80. // (-1,-1)
  81. if (rcGetCon(as, 3) != RC_NOT_CONNECTED)
  82. {
  83. const int aax = ax + rcGetDirOffsetX(3);
  84. const int aay = ay + rcGetDirOffsetY(3);
  85. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 3);
  86. if (src[aai]+3 < src[i])
  87. src[i] = src[aai]+3;
  88. }
  89. }
  90. if (rcGetCon(s, 3) != RC_NOT_CONNECTED)
  91. {
  92. // (0,-1)
  93. const int ax = x + rcGetDirOffsetX(3);
  94. const int ay = y + rcGetDirOffsetY(3);
  95. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  96. const rcCompactSpan& as = chf.spans[ai];
  97. if (src[ai]+2 < src[i])
  98. src[i] = src[ai]+2;
  99. // (1,-1)
  100. if (rcGetCon(as, 2) != RC_NOT_CONNECTED)
  101. {
  102. const int aax = ax + rcGetDirOffsetX(2);
  103. const int aay = ay + rcGetDirOffsetY(2);
  104. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 2);
  105. if (src[aai]+3 < src[i])
  106. src[i] = src[aai]+3;
  107. }
  108. }
  109. }
  110. }
  111. }
  112. // Pass 2
  113. for (int y = h-1; y >= 0; --y)
  114. {
  115. for (int x = w-1; x >= 0; --x)
  116. {
  117. const rcCompactCell& c = chf.cells[x+y*w];
  118. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  119. {
  120. const rcCompactSpan& s = chf.spans[i];
  121. if (rcGetCon(s, 2) != RC_NOT_CONNECTED)
  122. {
  123. // (1,0)
  124. const int ax = x + rcGetDirOffsetX(2);
  125. const int ay = y + rcGetDirOffsetY(2);
  126. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 2);
  127. const rcCompactSpan& as = chf.spans[ai];
  128. if (src[ai]+2 < src[i])
  129. src[i] = src[ai]+2;
  130. // (1,1)
  131. if (rcGetCon(as, 1) != RC_NOT_CONNECTED)
  132. {
  133. const int aax = ax + rcGetDirOffsetX(1);
  134. const int aay = ay + rcGetDirOffsetY(1);
  135. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 1);
  136. if (src[aai]+3 < src[i])
  137. src[i] = src[aai]+3;
  138. }
  139. }
  140. if (rcGetCon(s, 1) != RC_NOT_CONNECTED)
  141. {
  142. // (0,1)
  143. const int ax = x + rcGetDirOffsetX(1);
  144. const int ay = y + rcGetDirOffsetY(1);
  145. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 1);
  146. const rcCompactSpan& as = chf.spans[ai];
  147. if (src[ai]+2 < src[i])
  148. src[i] = src[ai]+2;
  149. // (-1,1)
  150. if (rcGetCon(as, 0) != RC_NOT_CONNECTED)
  151. {
  152. const int aax = ax + rcGetDirOffsetX(0);
  153. const int aay = ay + rcGetDirOffsetY(0);
  154. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 0);
  155. if (src[aai]+3 < src[i])
  156. src[i] = src[aai]+3;
  157. }
  158. }
  159. }
  160. }
  161. }
  162. maxDist = 0;
  163. for (int i = 0; i < chf.spanCount; ++i)
  164. maxDist = rcMax(src[i], maxDist);
  165. }
  166. static unsigned short* boxBlur(rcCompactHeightfield& chf, int thr,
  167. unsigned short* src, unsigned short* dst)
  168. {
  169. const int w = chf.width;
  170. const int h = chf.height;
  171. thr *= 2;
  172. for (int y = 0; y < h; ++y)
  173. {
  174. for (int x = 0; x < w; ++x)
  175. {
  176. const rcCompactCell& c = chf.cells[x+y*w];
  177. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  178. {
  179. const rcCompactSpan& s = chf.spans[i];
  180. const unsigned short cd = src[i];
  181. if (cd <= thr)
  182. {
  183. dst[i] = cd;
  184. continue;
  185. }
  186. int d = (int)cd;
  187. for (int dir = 0; dir < 4; ++dir)
  188. {
  189. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  190. {
  191. const int ax = x + rcGetDirOffsetX(dir);
  192. const int ay = y + rcGetDirOffsetY(dir);
  193. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  194. d += (int)src[ai];
  195. const rcCompactSpan& as = chf.spans[ai];
  196. const int dir2 = (dir+1) & 0x3;
  197. if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
  198. {
  199. const int ax2 = ax + rcGetDirOffsetX(dir2);
  200. const int ay2 = ay + rcGetDirOffsetY(dir2);
  201. const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
  202. d += (int)src[ai2];
  203. }
  204. else
  205. {
  206. d += cd;
  207. }
  208. }
  209. else
  210. {
  211. d += cd*2;
  212. }
  213. }
  214. dst[i] = (unsigned short)((d+5)/9);
  215. }
  216. }
  217. }
  218. return dst;
  219. }
  220. static bool floodRegion(int x, int y, int i,
  221. unsigned short level, unsigned short r,
  222. rcCompactHeightfield& chf,
  223. unsigned short* srcReg, unsigned short* srcDist,
  224. rcIntArray& stack)
  225. {
  226. const int w = chf.width;
  227. const unsigned char area = chf.areas[i];
  228. // Flood fill mark region.
  229. stack.resize(0);
  230. stack.push((int)x);
  231. stack.push((int)y);
  232. stack.push((int)i);
  233. srcReg[i] = r;
  234. srcDist[i] = 0;
  235. unsigned short lev = level >= 2 ? level-2 : 0;
  236. int count = 0;
  237. while (stack.size() > 0)
  238. {
  239. int ci = stack.pop();
  240. int cy = stack.pop();
  241. int cx = stack.pop();
  242. const rcCompactSpan& cs = chf.spans[ci];
  243. // Check if any of the neighbours already have a valid region set.
  244. unsigned short ar = 0;
  245. for (int dir = 0; dir < 4; ++dir)
  246. {
  247. // 8 connected
  248. if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
  249. {
  250. const int ax = cx + rcGetDirOffsetX(dir);
  251. const int ay = cy + rcGetDirOffsetY(dir);
  252. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
  253. if (chf.areas[ai] != area)
  254. continue;
  255. unsigned short nr = srcReg[ai];
  256. if (nr & RC_BORDER_REG) // Do not take borders into account.
  257. continue;
  258. if (nr != 0 && nr != r)
  259. {
  260. ar = nr;
  261. break;
  262. }
  263. const rcCompactSpan& as = chf.spans[ai];
  264. const int dir2 = (dir+1) & 0x3;
  265. if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
  266. {
  267. const int ax2 = ax + rcGetDirOffsetX(dir2);
  268. const int ay2 = ay + rcGetDirOffsetY(dir2);
  269. const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
  270. if (chf.areas[ai2] != area)
  271. continue;
  272. unsigned short nr2 = srcReg[ai2];
  273. if (nr2 != 0 && nr2 != r)
  274. {
  275. ar = nr2;
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. if (ar != 0)
  282. {
  283. srcReg[ci] = 0;
  284. continue;
  285. }
  286. count++;
  287. // Expand neighbours.
  288. for (int dir = 0; dir < 4; ++dir)
  289. {
  290. if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
  291. {
  292. const int ax = cx + rcGetDirOffsetX(dir);
  293. const int ay = cy + rcGetDirOffsetY(dir);
  294. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
  295. if (chf.areas[ai] != area)
  296. continue;
  297. if (chf.dist[ai] >= lev && srcReg[ai] == 0)
  298. {
  299. srcReg[ai] = r;
  300. srcDist[ai] = 0;
  301. stack.push(ax);
  302. stack.push(ay);
  303. stack.push(ai);
  304. }
  305. }
  306. }
  307. }
  308. return count > 0;
  309. }
  310. static unsigned short* expandRegions(int maxIter, unsigned short level,
  311. rcCompactHeightfield& chf,
  312. unsigned short* srcReg, unsigned short* srcDist,
  313. unsigned short* dstReg, unsigned short* dstDist,
  314. rcIntArray& stack,
  315. bool fillStack)
  316. {
  317. const int w = chf.width;
  318. const int h = chf.height;
  319. if (fillStack)
  320. {
  321. // Find cells revealed by the raised level.
  322. stack.resize(0);
  323. for (int y = 0; y < h; ++y)
  324. {
  325. for (int x = 0; x < w; ++x)
  326. {
  327. const rcCompactCell& c = chf.cells[x+y*w];
  328. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  329. {
  330. if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
  331. {
  332. stack.push(x);
  333. stack.push(y);
  334. stack.push(i);
  335. }
  336. }
  337. }
  338. }
  339. }
  340. else // use cells in the input stack
  341. {
  342. // mark all cells which already have a region
  343. for (int j=0; j<stack.size(); j+=3)
  344. {
  345. int i = stack[j+2];
  346. if (srcReg[i] != 0)
  347. stack[j+2] = -1;
  348. }
  349. }
  350. int iter = 0;
  351. while (stack.size() > 0)
  352. {
  353. int failed = 0;
  354. memcpy(dstReg, srcReg, sizeof(unsigned short)*chf.spanCount);
  355. memcpy(dstDist, srcDist, sizeof(unsigned short)*chf.spanCount);
  356. for (int j = 0; j < stack.size(); j += 3)
  357. {
  358. int x = stack[j+0];
  359. int y = stack[j+1];
  360. int i = stack[j+2];
  361. if (i < 0)
  362. {
  363. failed++;
  364. continue;
  365. }
  366. unsigned short r = srcReg[i];
  367. unsigned short d2 = 0xffff;
  368. const unsigned char area = chf.areas[i];
  369. const rcCompactSpan& s = chf.spans[i];
  370. for (int dir = 0; dir < 4; ++dir)
  371. {
  372. if (rcGetCon(s, dir) == RC_NOT_CONNECTED) continue;
  373. const int ax = x + rcGetDirOffsetX(dir);
  374. const int ay = y + rcGetDirOffsetY(dir);
  375. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  376. if (chf.areas[ai] != area) continue;
  377. if (srcReg[ai] > 0 && (srcReg[ai] & RC_BORDER_REG) == 0)
  378. {
  379. if ((int)srcDist[ai]+2 < (int)d2)
  380. {
  381. r = srcReg[ai];
  382. d2 = srcDist[ai]+2;
  383. }
  384. }
  385. }
  386. if (r)
  387. {
  388. stack[j+2] = -1; // mark as used
  389. dstReg[i] = r;
  390. dstDist[i] = d2;
  391. }
  392. else
  393. {
  394. failed++;
  395. }
  396. }
  397. // rcSwap source and dest.
  398. rcSwap(srcReg, dstReg);
  399. rcSwap(srcDist, dstDist);
  400. if (failed*3 == stack.size())
  401. break;
  402. if (level > 0)
  403. {
  404. ++iter;
  405. if (iter >= maxIter)
  406. break;
  407. }
  408. }
  409. return srcReg;
  410. }
  411. static void sortCellsByLevel(unsigned short startLevel,
  412. rcCompactHeightfield& chf,
  413. unsigned short* srcReg,
  414. unsigned int nbStacks, rcIntArray* stacks,
  415. unsigned short loglevelsPerStack) // the levels per stack (2 in our case) as a bit shift
  416. {
  417. const int w = chf.width;
  418. const int h = chf.height;
  419. startLevel = startLevel >> loglevelsPerStack;
  420. for (unsigned int j=0; j<nbStacks; ++j)
  421. stacks[j].resize(0);
  422. // put all cells in the level range into the appropriate stacks
  423. for (int y = 0; y < h; ++y)
  424. {
  425. for (int x = 0; x < w; ++x)
  426. {
  427. const rcCompactCell& c = chf.cells[x+y*w];
  428. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  429. {
  430. if (chf.areas[i] == RC_NULL_AREA || srcReg[i] != 0)
  431. continue;
  432. int level = chf.dist[i] >> loglevelsPerStack;
  433. int sId = startLevel - level;
  434. if (sId >= (int)nbStacks)
  435. continue;
  436. if (sId < 0)
  437. sId = 0;
  438. stacks[sId].push(x);
  439. stacks[sId].push(y);
  440. stacks[sId].push(i);
  441. }
  442. }
  443. }
  444. }
  445. static void appendStacks(rcIntArray& srcStack, rcIntArray& dstStack,
  446. unsigned short* srcReg)
  447. {
  448. for (int j=0; j<srcStack.size(); j+=3)
  449. {
  450. int i = srcStack[j+2];
  451. if ((i < 0) || (srcReg[i] != 0))
  452. continue;
  453. dstStack.push(srcStack[j]);
  454. dstStack.push(srcStack[j+1]);
  455. dstStack.push(srcStack[j+2]);
  456. }
  457. }
  458. struct rcRegion
  459. {
  460. inline rcRegion(unsigned short i) :
  461. spanCount(0),
  462. id(i),
  463. areaType(0),
  464. remap(false),
  465. visited(false)
  466. {}
  467. int spanCount; // Number of spans belonging to this region
  468. unsigned short id; // ID of the region
  469. unsigned char areaType; // Are type.
  470. bool remap;
  471. bool visited;
  472. rcIntArray connections;
  473. rcIntArray floors;
  474. };
  475. static void removeAdjacentNeighbours(rcRegion& reg)
  476. {
  477. // Remove adjacent duplicates.
  478. for (int i = 0; i < reg.connections.size() && reg.connections.size() > 1; )
  479. {
  480. int ni = (i+1) % reg.connections.size();
  481. if (reg.connections[i] == reg.connections[ni])
  482. {
  483. // Remove duplicate
  484. for (int j = i; j < reg.connections.size()-1; ++j)
  485. reg.connections[j] = reg.connections[j+1];
  486. reg.connections.pop();
  487. }
  488. else
  489. ++i;
  490. }
  491. }
  492. static void replaceNeighbour(rcRegion& reg, unsigned short oldId, unsigned short newId)
  493. {
  494. bool neiChanged = false;
  495. for (int i = 0; i < reg.connections.size(); ++i)
  496. {
  497. if (reg.connections[i] == oldId)
  498. {
  499. reg.connections[i] = newId;
  500. neiChanged = true;
  501. }
  502. }
  503. for (int i = 0; i < reg.floors.size(); ++i)
  504. {
  505. if (reg.floors[i] == oldId)
  506. reg.floors[i] = newId;
  507. }
  508. if (neiChanged)
  509. removeAdjacentNeighbours(reg);
  510. }
  511. static bool canMergeWithRegion(const rcRegion& rega, const rcRegion& regb)
  512. {
  513. if (rega.areaType != regb.areaType)
  514. return false;
  515. int n = 0;
  516. for (int i = 0; i < rega.connections.size(); ++i)
  517. {
  518. if (rega.connections[i] == regb.id)
  519. n++;
  520. }
  521. if (n > 1)
  522. return false;
  523. for (int i = 0; i < rega.floors.size(); ++i)
  524. {
  525. if (rega.floors[i] == regb.id)
  526. return false;
  527. }
  528. return true;
  529. }
  530. static void addUniqueFloorRegion(rcRegion& reg, int n)
  531. {
  532. for (int i = 0; i < reg.floors.size(); ++i)
  533. if (reg.floors[i] == n)
  534. return;
  535. reg.floors.push(n);
  536. }
  537. static bool mergeRegions(rcRegion& rega, rcRegion& regb)
  538. {
  539. unsigned short aid = rega.id;
  540. unsigned short bid = regb.id;
  541. // Duplicate current neighbourhood.
  542. rcIntArray acon;
  543. acon.resize(rega.connections.size());
  544. for (int i = 0; i < rega.connections.size(); ++i)
  545. acon[i] = rega.connections[i];
  546. rcIntArray& bcon = regb.connections;
  547. // Find insertion point on A.
  548. int insa = -1;
  549. for (int i = 0; i < acon.size(); ++i)
  550. {
  551. if (acon[i] == bid)
  552. {
  553. insa = i;
  554. break;
  555. }
  556. }
  557. if (insa == -1)
  558. return false;
  559. // Find insertion point on B.
  560. int insb = -1;
  561. for (int i = 0; i < bcon.size(); ++i)
  562. {
  563. if (bcon[i] == aid)
  564. {
  565. insb = i;
  566. break;
  567. }
  568. }
  569. if (insb == -1)
  570. return false;
  571. // Merge neighbours.
  572. rega.connections.resize(0);
  573. for (int i = 0, ni = acon.size(); i < ni-1; ++i)
  574. rega.connections.push(acon[(insa+1+i) % ni]);
  575. for (int i = 0, ni = bcon.size(); i < ni-1; ++i)
  576. rega.connections.push(bcon[(insb+1+i) % ni]);
  577. removeAdjacentNeighbours(rega);
  578. for (int j = 0; j < regb.floors.size(); ++j)
  579. addUniqueFloorRegion(rega, regb.floors[j]);
  580. rega.spanCount += regb.spanCount;
  581. regb.spanCount = 0;
  582. regb.connections.resize(0);
  583. return true;
  584. }
  585. static bool isRegionConnectedToBorder(const rcRegion& reg)
  586. {
  587. // Region is connected to border if
  588. // one of the neighbours is null id.
  589. for (int i = 0; i < reg.connections.size(); ++i)
  590. {
  591. if (reg.connections[i] == 0)
  592. return true;
  593. }
  594. return false;
  595. }
  596. static bool isSolidEdge(rcCompactHeightfield& chf, unsigned short* srcReg,
  597. int x, int y, int i, int dir)
  598. {
  599. const rcCompactSpan& s = chf.spans[i];
  600. unsigned short r = 0;
  601. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  602. {
  603. const int ax = x + rcGetDirOffsetX(dir);
  604. const int ay = y + rcGetDirOffsetY(dir);
  605. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  606. r = srcReg[ai];
  607. }
  608. if (r == srcReg[i])
  609. return false;
  610. return true;
  611. }
  612. static void walkContour(int x, int y, int i, int dir,
  613. rcCompactHeightfield& chf,
  614. unsigned short* srcReg,
  615. rcIntArray& cont)
  616. {
  617. int startDir = dir;
  618. int starti = i;
  619. const rcCompactSpan& ss = chf.spans[i];
  620. unsigned short curReg = 0;
  621. if (rcGetCon(ss, dir) != RC_NOT_CONNECTED)
  622. {
  623. const int ax = x + rcGetDirOffsetX(dir);
  624. const int ay = y + rcGetDirOffsetY(dir);
  625. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(ss, dir);
  626. curReg = srcReg[ai];
  627. }
  628. cont.push(curReg);
  629. int iter = 0;
  630. while (++iter < 40000)
  631. {
  632. const rcCompactSpan& s = chf.spans[i];
  633. if (isSolidEdge(chf, srcReg, x, y, i, dir))
  634. {
  635. // Choose the edge corner
  636. unsigned short r = 0;
  637. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  638. {
  639. const int ax = x + rcGetDirOffsetX(dir);
  640. const int ay = y + rcGetDirOffsetY(dir);
  641. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  642. r = srcReg[ai];
  643. }
  644. if (r != curReg)
  645. {
  646. curReg = r;
  647. cont.push(curReg);
  648. }
  649. dir = (dir+1) & 0x3; // Rotate CW
  650. }
  651. else
  652. {
  653. int ni = -1;
  654. const int nx = x + rcGetDirOffsetX(dir);
  655. const int ny = y + rcGetDirOffsetY(dir);
  656. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  657. {
  658. const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
  659. ni = (int)nc.index + rcGetCon(s, dir);
  660. }
  661. if (ni == -1)
  662. {
  663. // Should not happen.
  664. return;
  665. }
  666. x = nx;
  667. y = ny;
  668. i = ni;
  669. dir = (dir+3) & 0x3; // Rotate CCW
  670. }
  671. if (starti == i && startDir == dir)
  672. {
  673. break;
  674. }
  675. }
  676. // Remove adjacent duplicates.
  677. if (cont.size() > 1)
  678. {
  679. for (int j = 0; j < cont.size(); )
  680. {
  681. int nj = (j+1) % cont.size();
  682. if (cont[j] == cont[nj])
  683. {
  684. for (int k = j; k < cont.size()-1; ++k)
  685. cont[k] = cont[k+1];
  686. cont.pop();
  687. }
  688. else
  689. ++j;
  690. }
  691. }
  692. }
  693. static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
  694. unsigned short& maxRegionId,
  695. rcCompactHeightfield& chf,
  696. unsigned short* srcReg)
  697. {
  698. const int w = chf.width;
  699. const int h = chf.height;
  700. const int nreg = maxRegionId+1;
  701. rcRegion* regions = (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
  702. if (!regions)
  703. {
  704. ctx->log(RC_LOG_ERROR, "filterSmallRegions: Out of memory 'regions' (%d).", nreg);
  705. return false;
  706. }
  707. // Construct regions
  708. for (int i = 0; i < nreg; ++i)
  709. new(&regions[i]) rcRegion((unsigned short)i);
  710. // Find edge of a region and find connections around the contour.
  711. for (int y = 0; y < h; ++y)
  712. {
  713. for (int x = 0; x < w; ++x)
  714. {
  715. const rcCompactCell& c = chf.cells[x+y*w];
  716. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  717. {
  718. unsigned short r = srcReg[i];
  719. if (r == 0 || r >= nreg)
  720. continue;
  721. rcRegion& reg = regions[r];
  722. reg.spanCount++;
  723. // Update floors.
  724. for (int j = (int)c.index; j < ni; ++j)
  725. {
  726. if (i == j) continue;
  727. unsigned short floorId = srcReg[j];
  728. if (floorId == 0 || floorId >= nreg)
  729. continue;
  730. addUniqueFloorRegion(reg, floorId);
  731. }
  732. // Have found contour
  733. if (reg.connections.size() > 0)
  734. continue;
  735. reg.areaType = chf.areas[i];
  736. // Check if this cell is next to a border.
  737. int ndir = -1;
  738. for (int dir = 0; dir < 4; ++dir)
  739. {
  740. if (isSolidEdge(chf, srcReg, x, y, i, dir))
  741. {
  742. ndir = dir;
  743. break;
  744. }
  745. }
  746. if (ndir != -1)
  747. {
  748. // The cell is at border.
  749. // Walk around the contour to find all the neighbours.
  750. walkContour(x, y, i, ndir, chf, srcReg, reg.connections);
  751. }
  752. }
  753. }
  754. }
  755. // Remove too small regions.
  756. rcIntArray stack(32);
  757. rcIntArray trace(32);
  758. for (int i = 0; i < nreg; ++i)
  759. {
  760. rcRegion& reg = regions[i];
  761. if (reg.id == 0 || (reg.id & RC_BORDER_REG))
  762. continue;
  763. if (reg.spanCount == 0)
  764. continue;
  765. if (reg.visited)
  766. continue;
  767. // Count the total size of all the connected regions.
  768. // Also keep track of the regions connects to a tile border.
  769. bool connectsToBorder = false;
  770. int spanCount = 0;
  771. stack.resize(0);
  772. trace.resize(0);
  773. reg.visited = true;
  774. stack.push(i);
  775. while (stack.size())
  776. {
  777. // Pop
  778. int ri = stack.pop();
  779. rcRegion& creg = regions[ri];
  780. spanCount += creg.spanCount;
  781. trace.push(ri);
  782. for (int j = 0; j < creg.connections.size(); ++j)
  783. {
  784. if (creg.connections[j] & RC_BORDER_REG)
  785. {
  786. connectsToBorder = true;
  787. continue;
  788. }
  789. rcRegion& neireg = regions[creg.connections[j]];
  790. if (neireg.visited)
  791. continue;
  792. if (neireg.id == 0 || (neireg.id & RC_BORDER_REG))
  793. continue;
  794. // Visit
  795. stack.push(neireg.id);
  796. neireg.visited = true;
  797. }
  798. }
  799. // If the accumulated regions size is too small, remove it.
  800. // Do not remove areas which connect to tile borders
  801. // as their size cannot be estimated correctly and removing them
  802. // can potentially remove necessary areas.
  803. if (spanCount < minRegionArea && !connectsToBorder)
  804. {
  805. // Kill all visited regions.
  806. for (int j = 0; j < trace.size(); ++j)
  807. {
  808. regions[trace[j]].spanCount = 0;
  809. regions[trace[j]].id = 0;
  810. }
  811. }
  812. }
  813. // Merge too small regions to neighbour regions.
  814. int mergeCount = 0 ;
  815. do
  816. {
  817. mergeCount = 0;
  818. for (int i = 0; i < nreg; ++i)
  819. {
  820. rcRegion& reg = regions[i];
  821. if (reg.id == 0 || (reg.id & RC_BORDER_REG))
  822. continue;
  823. if (reg.spanCount == 0)
  824. continue;
  825. // Check to see if the region should be merged.
  826. if (reg.spanCount > mergeRegionSize && isRegionConnectedToBorder(reg))
  827. continue;
  828. // Small region with more than 1 connection.
  829. // Or region which is not connected to a border at all.
  830. // Find smallest neighbour region that connects to this one.
  831. int smallest = 0xfffffff;
  832. unsigned short mergeId = reg.id;
  833. for (int j = 0; j < reg.connections.size(); ++j)
  834. {
  835. if (reg.connections[j] & RC_BORDER_REG) continue;
  836. rcRegion& mreg = regions[reg.connections[j]];
  837. if (mreg.id == 0 || (mreg.id & RC_BORDER_REG)) continue;
  838. if (mreg.spanCount < smallest &&
  839. canMergeWithRegion(reg, mreg) &&
  840. canMergeWithRegion(mreg, reg))
  841. {
  842. smallest = mreg.spanCount;
  843. mergeId = mreg.id;
  844. }
  845. }
  846. // Found new id.
  847. if (mergeId != reg.id)
  848. {
  849. unsigned short oldId = reg.id;
  850. rcRegion& target = regions[mergeId];
  851. // Merge neighbours.
  852. if (mergeRegions(target, reg))
  853. {
  854. // Fixup regions pointing to current region.
  855. for (int j = 0; j < nreg; ++j)
  856. {
  857. if (regions[j].id == 0 || (regions[j].id & RC_BORDER_REG)) continue;
  858. // If another region was already merged into current region
  859. // change the nid of the previous region too.
  860. if (regions[j].id == oldId)
  861. regions[j].id = mergeId;
  862. // Replace the current region with the new one if the
  863. // current regions is neighbour.
  864. replaceNeighbour(regions[j], oldId, mergeId);
  865. }
  866. mergeCount++;
  867. }
  868. }
  869. }
  870. }
  871. while (mergeCount > 0);
  872. // Compress region Ids.
  873. for (int i = 0; i < nreg; ++i)
  874. {
  875. regions[i].remap = false;
  876. if (regions[i].id == 0) continue; // Skip nil regions.
  877. if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
  878. regions[i].remap = true;
  879. }
  880. unsigned short regIdGen = 0;
  881. for (int i = 0; i < nreg; ++i)
  882. {
  883. if (!regions[i].remap)
  884. continue;
  885. unsigned short oldId = regions[i].id;
  886. unsigned short newId = ++regIdGen;
  887. for (int j = i; j < nreg; ++j)
  888. {
  889. if (regions[j].id == oldId)
  890. {
  891. regions[j].id = newId;
  892. regions[j].remap = false;
  893. }
  894. }
  895. }
  896. maxRegionId = regIdGen;
  897. // Remap regions.
  898. for (int i = 0; i < chf.spanCount; ++i)
  899. {
  900. if ((srcReg[i] & RC_BORDER_REG) == 0)
  901. srcReg[i] = regions[srcReg[i]].id;
  902. }
  903. for (int i = 0; i < nreg; ++i)
  904. regions[i].~rcRegion();
  905. rcFree(regions);
  906. return true;
  907. }
  908. /// @par
  909. ///
  910. /// This is usually the second to the last step in creating a fully built
  911. /// compact heightfield. This step is required before regions are built
  912. /// using #rcBuildRegions or #rcBuildRegionsMonotone.
  913. ///
  914. /// After this step, the distance data is available via the rcCompactHeightfield::maxDistance
  915. /// and rcCompactHeightfield::dist fields.
  916. ///
  917. /// @see rcCompactHeightfield, rcBuildRegions, rcBuildRegionsMonotone
  918. bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
  919. {
  920. rcAssert(ctx);
  921. ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD);
  922. if (chf.dist)
  923. {
  924. rcFree(chf.dist);
  925. chf.dist = 0;
  926. }
  927. unsigned short* src = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
  928. if (!src)
  929. {
  930. ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'src' (%d).", chf.spanCount);
  931. return false;
  932. }
  933. unsigned short* dst = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
  934. if (!dst)
  935. {
  936. ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'dst' (%d).", chf.spanCount);
  937. rcFree(src);
  938. return false;
  939. }
  940. unsigned short maxDist = 0;
  941. ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
  942. calculateDistanceField(chf, src, maxDist);
  943. chf.maxDistance = maxDist;
  944. ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
  945. ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
  946. // Blur
  947. if (boxBlur(chf, 1, src, dst) != src)
  948. rcSwap(src, dst);
  949. // Store distance.
  950. chf.dist = src;
  951. ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
  952. ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD);
  953. rcFree(dst);
  954. return true;
  955. }
  956. static void paintRectRegion(int minx, int maxx, int miny, int maxy, unsigned short regId,
  957. rcCompactHeightfield& chf, unsigned short* srcReg)
  958. {
  959. const int w = chf.width;
  960. for (int y = miny; y < maxy; ++y)
  961. {
  962. for (int x = minx; x < maxx; ++x)
  963. {
  964. const rcCompactCell& c = chf.cells[x+y*w];
  965. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  966. {
  967. if (chf.areas[i] != RC_NULL_AREA)
  968. srcReg[i] = regId;
  969. }
  970. }
  971. }
  972. }
  973. static const unsigned short RC_NULL_NEI = 0xffff;
  974. struct rcSweepSpan
  975. {
  976. unsigned short rid; // row id
  977. unsigned short id; // region id
  978. unsigned short ns; // number samples
  979. unsigned short nei; // neighbour id
  980. };
  981. /// @par
  982. ///
  983. /// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
  984. /// Contours will form simple polygons.
  985. ///
  986. /// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
  987. /// re-assigned to the zero (null) region.
  988. ///
  989. /// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps
  990. /// reduce unecessarily small regions.
  991. ///
  992. /// See the #rcConfig documentation for more information on the configuration parameters.
  993. ///
  994. /// The region data will be available via the rcCompactHeightfield::maxRegions
  995. /// and rcCompactSpan::reg fields.
  996. ///
  997. /// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
  998. ///
  999. /// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
  1000. bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
  1001. const int borderSize, const int minRegionArea, const int mergeRegionArea)
  1002. {
  1003. rcAssert(ctx);
  1004. ctx->startTimer(RC_TIMER_BUILD_REGIONS);
  1005. const int w = chf.width;
  1006. const int h = chf.height;
  1007. unsigned short id = 1;
  1008. rcScopedDelete<unsigned short> srcReg = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
  1009. if (!srcReg)
  1010. {
  1011. ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
  1012. return false;
  1013. }
  1014. memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
  1015. const int nsweeps = rcMax(chf.width,chf.height);
  1016. rcScopedDelete<rcSweepSpan> sweeps = (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
  1017. if (!sweeps)
  1018. {
  1019. ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
  1020. return false;
  1021. }
  1022. // Mark border regions.
  1023. if (borderSize > 0)
  1024. {
  1025. // Make sure border will not overflow.
  1026. const int bw = rcMin(w, borderSize);
  1027. const int bh = rcMin(h, borderSize);
  1028. // Paint regions
  1029. paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1030. paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1031. paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
  1032. paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1033. chf.borderSize = borderSize;
  1034. }
  1035. rcIntArray prev(256);
  1036. // Sweep one line at a time.
  1037. for (int y = borderSize; y < h-borderSize; ++y)
  1038. {
  1039. // Collect spans from this row.
  1040. prev.resize(id+1);
  1041. memset(&prev[0],0,sizeof(int)*id);
  1042. unsigned short rid = 1;
  1043. for (int x = borderSize; x < w-borderSize; ++x)
  1044. {
  1045. const rcCompactCell& c = chf.cells[x+y*w];
  1046. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1047. {
  1048. const rcCompactSpan& s = chf.spans[i];
  1049. if (chf.areas[i] == RC_NULL_AREA) continue;
  1050. // -x
  1051. unsigned short previd = 0;
  1052. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  1053. {
  1054. const int ax = x + rcGetDirOffsetX(0);
  1055. const int ay = y + rcGetDirOffsetY(0);
  1056. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  1057. if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1058. previd = srcReg[ai];
  1059. }
  1060. if (!previd)
  1061. {
  1062. previd = rid++;
  1063. sweeps[previd].rid = previd;
  1064. sweeps[previd].ns = 0;
  1065. sweeps[previd].nei = 0;
  1066. }
  1067. // -y
  1068. if (rcGetCon(s,3) != RC_NOT_CONNECTED)
  1069. {
  1070. const int ax = x + rcGetDirOffsetX(3);
  1071. const int ay = y + rcGetDirOffsetY(3);
  1072. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  1073. if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1074. {
  1075. unsigned short nr = srcReg[ai];
  1076. if (!sweeps[previd].nei || sweeps[previd].nei == nr)
  1077. {
  1078. sweeps[previd].nei = nr;
  1079. sweeps[previd].ns++;
  1080. prev[nr]++;
  1081. }
  1082. else
  1083. {
  1084. sweeps[previd].nei = RC_NULL_NEI;
  1085. }
  1086. }
  1087. }
  1088. srcReg[i] = previd;
  1089. }
  1090. }
  1091. // Create unique ID.
  1092. for (int i = 1; i < rid; ++i)
  1093. {
  1094. if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 &&
  1095. prev[sweeps[i].nei] == (int)sweeps[i].ns)
  1096. {
  1097. sweeps[i].id = sweeps[i].nei;
  1098. }
  1099. else
  1100. {
  1101. sweeps[i].id = id++;
  1102. }
  1103. }
  1104. // Remap IDs
  1105. for (int x = borderSize; x < w-borderSize; ++x)
  1106. {
  1107. const rcCompactCell& c = chf.cells[x+y*w];
  1108. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1109. {
  1110. if (srcReg[i] > 0 && srcReg[i] < rid)
  1111. srcReg[i] = sweeps[srcReg[i]].id;
  1112. }
  1113. }
  1114. }
  1115. ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
  1116. // Filter out small regions.
  1117. chf.maxRegions = id;
  1118. if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
  1119. return false;
  1120. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
  1121. // Store the result out.
  1122. for (int i = 0; i < chf.spanCount; ++i)
  1123. chf.spans[i].reg = srcReg[i];
  1124. ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
  1125. return true;
  1126. }
  1127. /// @par
  1128. ///
  1129. /// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
  1130. /// Contours will form simple polygons.
  1131. ///
  1132. /// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
  1133. /// re-assigned to the zero (null) region.
  1134. ///
  1135. /// Watershed partitioning can result in smaller than necessary regions, especially in diagonal corridors.
  1136. /// @p mergeRegionArea helps reduce unecessarily small regions.
  1137. ///
  1138. /// See the #rcConfig documentation for more information on the configuration parameters.
  1139. ///
  1140. /// The region data will be available via the rcCompactHeightfield::maxRegions
  1141. /// and rcCompactSpan::reg fields.
  1142. ///
  1143. /// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
  1144. ///
  1145. /// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
  1146. bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
  1147. const int borderSize, const int minRegionArea, const int mergeRegionArea)
  1148. {
  1149. rcAssert(ctx);
  1150. ctx->startTimer(RC_TIMER_BUILD_REGIONS);
  1151. const int w = chf.width;
  1152. const int h = chf.height;
  1153. rcScopedDelete<unsigned short> buf = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*4, RC_ALLOC_TEMP);
  1154. if (!buf)
  1155. {
  1156. ctx->log(RC_LOG_ERROR, "rcBuildRegions: Out of memory 'tmp' (%d).", chf.spanCount*4);
  1157. return false;
  1158. }
  1159. ctx->startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
  1160. const int LOG_NB_STACKS = 3;
  1161. const int NB_STACKS = 1 << LOG_NB_STACKS;
  1162. rcIntArray lvlStacks[NB_STACKS];
  1163. for (int i=0; i<NB_STACKS; ++i)
  1164. lvlStacks[i].resize(1024);
  1165. rcIntArray stack(1024);
  1166. rcIntArray visited(1024);
  1167. unsigned short* srcReg = buf;
  1168. unsigned short* srcDist = buf+chf.spanCount;
  1169. unsigned short* dstReg = buf+chf.spanCount*2;
  1170. unsigned short* dstDist = buf+chf.spanCount*3;
  1171. memset(srcReg, 0, sizeof(unsigned short)*chf.spanCount);
  1172. memset(srcDist, 0, sizeof(unsigned short)*chf.spanCount);
  1173. unsigned short regionId = 1;
  1174. unsigned short level = (chf.maxDistance+1) & ~1;
  1175. // TODO: Figure better formula, expandIters defines how much the
  1176. // watershed "overflows" and simplifies the regions. Tying it to
  1177. // agent radius was usually good indication how greedy it could be.
  1178. // const int expandIters = 4 + walkableRadius * 2;
  1179. const int expandIters = 8;
  1180. if (borderSize > 0)
  1181. {
  1182. // Make sure border will not overflow.
  1183. const int bw = rcMin(w, borderSize);
  1184. const int bh = rcMin(h, borderSize);
  1185. // Paint regions
  1186. paintRectRegion(0, bw, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1187. paintRectRegion(w-bw, w, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1188. paintRectRegion(0, w, 0, bh, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1189. paintRectRegion(0, w, h-bh, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1190. chf.borderSize = borderSize;
  1191. }
  1192. int sId = -1;
  1193. while (level > 0)
  1194. {
  1195. level = level >= 2 ? level-2 : 0;
  1196. sId = (sId+1) & (NB_STACKS-1);
  1197. // ctx->startTimer(RC_TIMER_DIVIDE_TO_LEVELS);
  1198. if (sId == 0)
  1199. sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1);
  1200. else
  1201. appendStacks(lvlStacks[sId-1], lvlStacks[sId], srcReg); // copy left overs from last level
  1202. // ctx->stopTimer(RC_TIMER_DIVIDE_TO_LEVELS);
  1203. ctx->startTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
  1204. // Expand current regions until no empty connected cells found.
  1205. if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, lvlStacks[sId], false) != srcReg)
  1206. {
  1207. rcSwap(srcReg, dstReg);
  1208. rcSwap(srcDist, dstDist);
  1209. }
  1210. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
  1211. ctx->startTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
  1212. // Mark new regions with IDs.
  1213. for (int j=0; j<lvlStacks[sId].size(); j+=3)
  1214. {
  1215. int x = lvlStacks[sId][j];
  1216. int y = lvlStacks[sId][j+1];
  1217. int i = lvlStacks[sId][j+2];
  1218. if (i >= 0 && srcReg[i] == 0)
  1219. {
  1220. if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
  1221. regionId++;
  1222. }
  1223. }
  1224. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
  1225. }
  1226. // Expand current regions until no empty connected cells found.
  1227. if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, stack, true) != srcReg)
  1228. {
  1229. rcSwap(srcReg, dstReg);
  1230. rcSwap(srcDist, dstDist);
  1231. }
  1232. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
  1233. ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
  1234. // Filter out small regions.
  1235. chf.maxRegions = regionId;
  1236. if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
  1237. return false;
  1238. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
  1239. // Write the result out.
  1240. for (int i = 0; i < chf.spanCount; ++i)
  1241. chf.spans[i].reg = srcReg[i];
  1242. ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
  1243. return true;
  1244. }