RecastLayers.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*
  2. Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org
  4. DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com
  5. This software is provided 'as-is', without any express or implied
  6. warranty. In no event will the authors be held liable for any damages
  7. arising from the use of this software.
  8. Permission is granted to anyone to use this software for any purpose,
  9. including commercial applications, and to alter it and redistribute it
  10. freely, subject to the following restrictions:
  11. 1. The origin of this software must not be misrepresented; you must not
  12. claim that you wrote the original software. If you use this software
  13. in a product, an acknowledgment in the product documentation would be
  14. appreciated but is not required.
  15. 2. Altered source versions must be plainly marked as such, and must not be
  16. misrepresented as being the original software.
  17. 3. This notice may not be removed or altered from any source distribution.
  18. */
  19. using System;
  20. using System.Collections.Generic;
  21. using DotRecast.Core;
  22. namespace DotRecast.Recast
  23. {
  24. using static RecastCommon;
  25. using static RcConstants;
  26. public static class RecastLayers
  27. {
  28. const int RC_MAX_LAYERS = RcConstants.RC_NOT_CONNECTED;
  29. const int RC_MAX_NEIS = 16;
  30. private static void AddUnique(List<int> a, int v)
  31. {
  32. if (!a.Contains(v))
  33. {
  34. a.Add(v);
  35. }
  36. }
  37. private static bool Contains(List<int> a, int v)
  38. {
  39. return a.Contains(v);
  40. }
  41. private static bool OverlapRange(int amin, int amax, int bmin, int bmax)
  42. {
  43. return (amin > bmax || amax < bmin) ? false : true;
  44. }
  45. public static RcHeightfieldLayerSet BuildHeightfieldLayers(RcTelemetry ctx, RcCompactHeightfield chf, int walkableHeight)
  46. {
  47. using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_BUILD_LAYERS);
  48. int w = chf.width;
  49. int h = chf.height;
  50. int borderSize = chf.borderSize;
  51. int[] srcReg = new int[chf.spanCount];
  52. Array.Fill(srcReg, 0xFF);
  53. int nsweeps = chf.width; // Math.Max(chf.width, chf.height);
  54. RcSweepSpan[] sweeps = new RcSweepSpan[nsweeps];
  55. for (int i = 0; i < sweeps.Length; i++)
  56. {
  57. sweeps[i] = new RcSweepSpan();
  58. }
  59. // Partition walkable area into monotone regions.
  60. int[] prevCount = new int[256];
  61. int regId = 0;
  62. // Sweep one line at a time.
  63. for (int y = borderSize; y < h - borderSize; ++y)
  64. {
  65. // Collect spans from this row.
  66. Array.Fill(prevCount, 0, 0, (regId) - (0));
  67. int sweepId = 0;
  68. for (int x = borderSize; x < w - borderSize; ++x)
  69. {
  70. RcCompactCell c = chf.cells[x + y * w];
  71. for (int i = c.index, ni = c.index + c.count; i < ni; ++i)
  72. {
  73. RcCompactSpan s = chf.spans[i];
  74. if (chf.areas[i] == RC_NULL_AREA)
  75. continue;
  76. int sid = 0xFF;
  77. // -x
  78. if (GetCon(s, 0) != RC_NOT_CONNECTED)
  79. {
  80. int ax = x + GetDirOffsetX(0);
  81. int ay = y + GetDirOffsetY(0);
  82. int ai = chf.cells[ax + ay * w].index + GetCon(s, 0);
  83. if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)
  84. sid = srcReg[ai];
  85. }
  86. if (sid == 0xff)
  87. {
  88. sid = sweepId++;
  89. sweeps[sid].nei = 0xff;
  90. sweeps[sid].ns = 0;
  91. }
  92. // -y
  93. if (GetCon(s, 3) != RC_NOT_CONNECTED)
  94. {
  95. int ax = x + GetDirOffsetX(3);
  96. int ay = y + GetDirOffsetY(3);
  97. int ai = chf.cells[ax + ay * w].index + GetCon(s, 3);
  98. int nr = srcReg[ai];
  99. if (nr != 0xff)
  100. {
  101. // Set neighbour when first valid neighbour is
  102. // encoutered.
  103. if (sweeps[sid].ns == 0)
  104. sweeps[sid].nei = nr;
  105. if (sweeps[sid].nei == nr)
  106. {
  107. // Update existing neighbour
  108. sweeps[sid].ns++;
  109. prevCount[nr]++;
  110. }
  111. else
  112. {
  113. // This is hit if there is nore than one
  114. // neighbour.
  115. // Invalidate the neighbour.
  116. sweeps[sid].nei = 0xff;
  117. }
  118. }
  119. }
  120. srcReg[i] = sid;
  121. }
  122. }
  123. // Create unique ID.
  124. for (int i = 0; i < sweepId; ++i)
  125. {
  126. // If the neighbour is set and there is only one continuous
  127. // connection to it,
  128. // the sweep will be merged with the previous one, else new
  129. // region is created.
  130. if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == sweeps[i].ns)
  131. {
  132. sweeps[i].id = sweeps[i].nei;
  133. }
  134. else
  135. {
  136. if (regId == 255)
  137. {
  138. throw new Exception("rcBuildHeightfieldLayers: Region ID overflow.");
  139. }
  140. sweeps[i].id = regId++;
  141. }
  142. }
  143. // Remap local sweep ids to region ids.
  144. for (int x = borderSize; x < w - borderSize; ++x)
  145. {
  146. RcCompactCell c = chf.cells[x + y * w];
  147. for (int i = c.index, ni = c.index + c.count; i < ni; ++i)
  148. {
  149. if (srcReg[i] != 0xff)
  150. srcReg[i] = sweeps[srcReg[i]].id;
  151. }
  152. }
  153. }
  154. int nregs = regId;
  155. RcLayerRegion[] regs = new RcLayerRegion[nregs];
  156. // Construct regions
  157. for (int i = 0; i < nregs; ++i)
  158. {
  159. regs[i] = new RcLayerRegion(i);
  160. }
  161. // Find region neighbours and overlapping regions.
  162. List<int> lregs = new List<int>();
  163. for (int y = 0; y < h; ++y)
  164. {
  165. for (int x = 0; x < w; ++x)
  166. {
  167. RcCompactCell c = chf.cells[x + y * w];
  168. lregs.Clear();
  169. for (int i = c.index, ni = c.index + c.count; i < ni; ++i)
  170. {
  171. RcCompactSpan s = chf.spans[i];
  172. int ri = srcReg[i];
  173. if (ri == 0xff)
  174. continue;
  175. regs[ri].ymin = Math.Min(regs[ri].ymin, s.y);
  176. regs[ri].ymax = Math.Max(regs[ri].ymax, s.y);
  177. // Collect all region layers.
  178. lregs.Add(ri);
  179. // Update neighbours
  180. for (int dir = 0; dir < 4; ++dir)
  181. {
  182. if (GetCon(s, dir) != RC_NOT_CONNECTED)
  183. {
  184. int ax = x + GetDirOffsetX(dir);
  185. int ay = y + GetDirOffsetY(dir);
  186. int ai = chf.cells[ax + ay * w].index + GetCon(s, dir);
  187. int rai = srcReg[ai];
  188. if (rai != 0xff && rai != ri)
  189. AddUnique(regs[ri].neis, rai);
  190. }
  191. }
  192. }
  193. // Update overlapping regions.
  194. for (int i = 0; i < lregs.Count - 1; ++i)
  195. {
  196. for (int j = i + 1; j < lregs.Count; ++j)
  197. {
  198. if (lregs[i] != lregs[j])
  199. {
  200. RcLayerRegion ri = regs[lregs[i]];
  201. RcLayerRegion rj = regs[lregs[j]];
  202. AddUnique(ri.layers, lregs[j]);
  203. AddUnique(rj.layers, lregs[i]);
  204. }
  205. }
  206. }
  207. }
  208. }
  209. // Create 2D layers from regions.
  210. int layerId = 0;
  211. List<int> stack = new List<int>();
  212. for (int i = 0; i < nregs; ++i)
  213. {
  214. RcLayerRegion root = regs[i];
  215. // Skip already visited.
  216. if (root.layerId != 0xff)
  217. continue;
  218. // Start search.
  219. root.layerId = layerId;
  220. root.@base = true;
  221. stack.Add(i);
  222. while (stack.Count != 0)
  223. {
  224. // Pop front
  225. int pop = stack[0]; // TODO : 여기에 stack 처럼 작동하게 했는데, 스택인지는 모르겠음
  226. stack.RemoveAt(0);
  227. RcLayerRegion reg = regs[pop];
  228. foreach (int nei in reg.neis)
  229. {
  230. RcLayerRegion regn = regs[nei];
  231. // Skip already visited.
  232. if (regn.layerId != 0xff)
  233. continue;
  234. // Skip if the neighbour is overlapping root region.
  235. if (Contains(root.layers, nei))
  236. continue;
  237. // Skip if the height range would become too large.
  238. int ymin = Math.Min(root.ymin, regn.ymin);
  239. int ymax = Math.Max(root.ymax, regn.ymax);
  240. if ((ymax - ymin) >= 255)
  241. continue;
  242. // Deepen
  243. stack.Add(nei);
  244. // Mark layer id
  245. regn.layerId = layerId;
  246. // Merge current layers to root.
  247. foreach (int layer in regn.layers)
  248. AddUnique(root.layers, layer);
  249. root.ymin = Math.Min(root.ymin, regn.ymin);
  250. root.ymax = Math.Max(root.ymax, regn.ymax);
  251. }
  252. }
  253. layerId++;
  254. }
  255. // Merge non-overlapping regions that are close in height.
  256. int mergeHeight = walkableHeight * 4;
  257. for (int i = 0; i < nregs; ++i)
  258. {
  259. RcLayerRegion ri = regs[i];
  260. if (!ri.@base)
  261. continue;
  262. int newId = ri.layerId;
  263. for (;;)
  264. {
  265. int oldId = 0xff;
  266. for (int j = 0; j < nregs; ++j)
  267. {
  268. if (i == j)
  269. continue;
  270. RcLayerRegion rj = regs[j];
  271. if (!rj.@base)
  272. continue;
  273. // Skip if the regions are not close to each other.
  274. if (!OverlapRange(ri.ymin, ri.ymax + mergeHeight, rj.ymin, rj.ymax + mergeHeight))
  275. continue;
  276. // Skip if the height range would become too large.
  277. int ymin = Math.Min(ri.ymin, rj.ymin);
  278. int ymax = Math.Max(ri.ymax, rj.ymax);
  279. if ((ymax - ymin) >= 255)
  280. continue;
  281. // Make sure that there is no overlap when merging 'ri' and
  282. // 'rj'.
  283. bool overlap = false;
  284. // Iterate over all regions which have the same layerId as
  285. // 'rj'
  286. for (int k = 0; k < nregs; ++k)
  287. {
  288. if (regs[k].layerId != rj.layerId)
  289. continue;
  290. // Check if region 'k' is overlapping region 'ri'
  291. // Index to 'regs' is the same as region id.
  292. if (Contains(ri.layers, k))
  293. {
  294. overlap = true;
  295. break;
  296. }
  297. }
  298. // Cannot merge of regions overlap.
  299. if (overlap)
  300. continue;
  301. // Can merge i and j.
  302. oldId = rj.layerId;
  303. break;
  304. }
  305. // Could not find anything to merge with, stop.
  306. if (oldId == 0xff)
  307. break;
  308. // Merge
  309. for (int j = 0; j < nregs; ++j)
  310. {
  311. RcLayerRegion rj = regs[j];
  312. if (rj.layerId == oldId)
  313. {
  314. rj.@base = false;
  315. // Remap layerIds.
  316. rj.layerId = newId;
  317. // Add overlaid layers from 'rj' to 'ri'.
  318. foreach (int layer in rj.layers)
  319. AddUnique(ri.layers, layer);
  320. // Update height bounds.
  321. ri.ymin = Math.Min(ri.ymin, rj.ymin);
  322. ri.ymax = Math.Max(ri.ymax, rj.ymax);
  323. }
  324. }
  325. }
  326. }
  327. // Compact layerIds
  328. int[] remap = new int[256];
  329. // Find number of unique layers.
  330. layerId = 0;
  331. for (int i = 0; i < nregs; ++i)
  332. remap[regs[i].layerId] = 1;
  333. for (int i = 0; i < 256; ++i)
  334. {
  335. if (remap[i] != 0)
  336. remap[i] = layerId++;
  337. else
  338. remap[i] = 0xff;
  339. }
  340. // Remap ids.
  341. for (int i = 0; i < nregs; ++i)
  342. regs[i].layerId = remap[regs[i].layerId];
  343. // No layers, return empty.
  344. if (layerId == 0)
  345. {
  346. // ctx.Stop(RC_TIMER_BUILD_LAYERS);
  347. return null;
  348. }
  349. // Create layers.
  350. // RcAssert(lset.layers == 0);
  351. int lw = w - borderSize * 2;
  352. int lh = h - borderSize * 2;
  353. // Build contracted bbox for layers.
  354. RcVec3f bmin = chf.bmin;
  355. RcVec3f bmax = chf.bmax;
  356. bmin.x += borderSize * chf.cs;
  357. bmin.z += borderSize * chf.cs;
  358. bmax.x -= borderSize * chf.cs;
  359. bmax.z -= borderSize * chf.cs;
  360. RcHeightfieldLayerSet lset = new RcHeightfieldLayerSet();
  361. lset.layers = new RcHeightfieldLayer[layerId];
  362. for (int i = 0; i < lset.layers.Length; i++)
  363. {
  364. lset.layers[i] = new RcHeightfieldLayer();
  365. }
  366. // Store layers.
  367. for (int i = 0; i < lset.layers.Length; ++i)
  368. {
  369. int curId = i;
  370. RcHeightfieldLayer layer = lset.layers[i];
  371. int gridSize = lw * lh;
  372. layer.heights = new int[gridSize];
  373. Array.Fill(layer.heights, 0xFF);
  374. layer.areas = new int[gridSize];
  375. layer.cons = new int[gridSize];
  376. // Find layer height bounds.
  377. int hmin = 0, hmax = 0;
  378. for (int j = 0; j < nregs; ++j)
  379. {
  380. if (regs[j].@base && regs[j].layerId == curId)
  381. {
  382. hmin = regs[j].ymin;
  383. hmax = regs[j].ymax;
  384. }
  385. }
  386. layer.width = lw;
  387. layer.height = lh;
  388. layer.cs = chf.cs;
  389. layer.ch = chf.ch;
  390. // Adjust the bbox to fit the heightfield.
  391. layer.bmin = bmin;
  392. layer.bmax = bmax;
  393. layer.bmin.y = bmin.y + hmin * chf.ch;
  394. layer.bmax.y = bmin.y + hmax * chf.ch;
  395. layer.hmin = hmin;
  396. layer.hmax = hmax;
  397. // Update usable data region.
  398. layer.minx = layer.width;
  399. layer.maxx = 0;
  400. layer.miny = layer.height;
  401. layer.maxy = 0;
  402. // Copy height and area from compact heightfield.
  403. for (int y = 0; y < lh; ++y)
  404. {
  405. for (int x = 0; x < lw; ++x)
  406. {
  407. int cx = borderSize + x;
  408. int cy = borderSize + y;
  409. RcCompactCell c = chf.cells[cx + cy * w];
  410. for (int j = c.index, nj = c.index + c.count; j < nj; ++j)
  411. {
  412. RcCompactSpan s = chf.spans[j];
  413. // Skip unassigned regions.
  414. if (srcReg[j] == 0xff)
  415. continue;
  416. // Skip of does nto belong to current layer.
  417. int lid = regs[srcReg[j]].layerId;
  418. if (lid != curId)
  419. continue;
  420. // Update data bounds.
  421. layer.minx = Math.Min(layer.minx, x);
  422. layer.maxx = Math.Max(layer.maxx, x);
  423. layer.miny = Math.Min(layer.miny, y);
  424. layer.maxy = Math.Max(layer.maxy, y);
  425. // Store height and area type.
  426. int idx = x + y * lw;
  427. layer.heights[idx] = (char)(s.y - hmin);
  428. layer.areas[idx] = chf.areas[j];
  429. // Check connection.
  430. char portal = (char)0;
  431. char con = (char)0;
  432. for (int dir = 0; dir < 4; ++dir)
  433. {
  434. if (GetCon(s, dir) != RC_NOT_CONNECTED)
  435. {
  436. int ax = cx + GetDirOffsetX(dir);
  437. int ay = cy + GetDirOffsetY(dir);
  438. int ai = chf.cells[ax + ay * w].index + GetCon(s, dir);
  439. int alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;
  440. // Portal mask
  441. if (chf.areas[ai] != RC_NULL_AREA && lid != alid)
  442. {
  443. portal |= (char)(1 << dir);
  444. // Update height so that it matches on both
  445. // sides of the portal.
  446. RcCompactSpan @as = chf.spans[ai];
  447. if (@as.y > hmin)
  448. layer.heights[idx] = Math.Max(layer.heights[idx], (char)(@as.y - hmin));
  449. }
  450. // Valid connection mask
  451. if (chf.areas[ai] != RC_NULL_AREA && lid == alid)
  452. {
  453. int nx = ax - borderSize;
  454. int ny = ay - borderSize;
  455. if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)
  456. con |= (char)(1 << dir);
  457. }
  458. }
  459. }
  460. layer.cons[idx] = (portal << 4) | con;
  461. }
  462. }
  463. }
  464. if (layer.minx > layer.maxx)
  465. layer.minx = layer.maxx = 0;
  466. if (layer.miny > layer.maxy)
  467. layer.miny = layer.maxy = 0;
  468. }
  469. // ctx->StopTimer(RC_TIMER_BUILD_LAYERS);
  470. return lset;
  471. }
  472. }
  473. }