RecastMesh.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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. #define _USE_MATH_DEFINES
  19. #include <math.h>
  20. #include <string.h>
  21. #include <stdio.h>
  22. #include "Recast.h"
  23. #include "RecastAlloc.h"
  24. #include "RecastAssert.h"
  25. struct rcEdge
  26. {
  27. unsigned short vert[2];
  28. unsigned short polyEdge[2];
  29. unsigned short poly[2];
  30. };
  31. static bool buildMeshAdjacency(unsigned short* polys, const int npolys,
  32. const int nverts, const int vertsPerPoly)
  33. {
  34. // Based on code by Eric Lengyel from:
  35. // http://www.terathon.com/code/edges.php
  36. int maxEdgeCount = npolys*vertsPerPoly;
  37. unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP);
  38. if (!firstEdge)
  39. return false;
  40. unsigned short* nextEdge = firstEdge + nverts;
  41. int edgeCount = 0;
  42. rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP);
  43. if (!edges)
  44. {
  45. rcFree(firstEdge);
  46. return false;
  47. }
  48. for (int i = 0; i < nverts; i++)
  49. firstEdge[i] = RC_MESH_NULL_IDX;
  50. for (int i = 0; i < npolys; ++i)
  51. {
  52. unsigned short* t = &polys[i*vertsPerPoly*2];
  53. for (int j = 0; j < vertsPerPoly; ++j)
  54. {
  55. if (t[j] == RC_MESH_NULL_IDX) break;
  56. unsigned short v0 = t[j];
  57. unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
  58. if (v0 < v1)
  59. {
  60. rcEdge& edge = edges[edgeCount];
  61. edge.vert[0] = v0;
  62. edge.vert[1] = v1;
  63. edge.poly[0] = (unsigned short)i;
  64. edge.polyEdge[0] = (unsigned short)j;
  65. edge.poly[1] = (unsigned short)i;
  66. edge.polyEdge[1] = 0;
  67. // Insert edge
  68. nextEdge[edgeCount] = firstEdge[v0];
  69. firstEdge[v0] = (unsigned short)edgeCount;
  70. edgeCount++;
  71. }
  72. }
  73. }
  74. for (int i = 0; i < npolys; ++i)
  75. {
  76. unsigned short* t = &polys[i*vertsPerPoly*2];
  77. for (int j = 0; j < vertsPerPoly; ++j)
  78. {
  79. if (t[j] == RC_MESH_NULL_IDX) break;
  80. unsigned short v0 = t[j];
  81. unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
  82. if (v0 > v1)
  83. {
  84. for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e])
  85. {
  86. rcEdge& edge = edges[e];
  87. if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])
  88. {
  89. edge.poly[1] = (unsigned short)i;
  90. edge.polyEdge[1] = (unsigned short)j;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. // Store adjacency
  98. for (int i = 0; i < edgeCount; ++i)
  99. {
  100. const rcEdge& e = edges[i];
  101. if (e.poly[0] != e.poly[1])
  102. {
  103. unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2];
  104. unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2];
  105. p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1];
  106. p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0];
  107. }
  108. }
  109. rcFree(firstEdge);
  110. rcFree(edges);
  111. return true;
  112. }
  113. static const int VERTEX_BUCKET_COUNT = (1<<12);
  114. inline int computeVertexHash(int x, int y, int z)
  115. {
  116. const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
  117. const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
  118. const unsigned int h3 = 0xcb1ab31f;
  119. unsigned int n = h1 * x + h2 * y + h3 * z;
  120. return (int)(n & (VERTEX_BUCKET_COUNT-1));
  121. }
  122. static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,
  123. unsigned short* verts, int* firstVert, int* nextVert, int& nv)
  124. {
  125. int bucket = computeVertexHash(x, 0, z);
  126. int i = firstVert[bucket];
  127. while (i != -1)
  128. {
  129. const unsigned short* v = &verts[i*3];
  130. if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z)
  131. return (unsigned short)i;
  132. i = nextVert[i]; // next
  133. }
  134. // Could not find, create new.
  135. i = nv; nv++;
  136. unsigned short* v = &verts[i*3];
  137. v[0] = x;
  138. v[1] = y;
  139. v[2] = z;
  140. nextVert[i] = firstVert[bucket];
  141. firstVert[bucket] = i;
  142. return (unsigned short)i;
  143. }
  144. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  145. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  146. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  147. inline int area2(const int* a, const int* b, const int* c)
  148. {
  149. return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
  150. }
  151. // Exclusive or: true iff exactly one argument is true.
  152. // The arguments are negated to ensure that they are 0/1
  153. // values. Then the bitwise Xor operator may apply.
  154. // (This idea is due to Michael Baldwin.)
  155. inline bool xorb(bool x, bool y)
  156. {
  157. return !x ^ !y;
  158. }
  159. // Returns true iff c is strictly to the left of the directed
  160. // line through a to b.
  161. inline bool left(const int* a, const int* b, const int* c)
  162. {
  163. return area2(a, b, c) < 0;
  164. }
  165. inline bool leftOn(const int* a, const int* b, const int* c)
  166. {
  167. return area2(a, b, c) <= 0;
  168. }
  169. inline bool collinear(const int* a, const int* b, const int* c)
  170. {
  171. return area2(a, b, c) == 0;
  172. }
  173. // Returns true iff ab properly intersects cd: they share
  174. // a point interior to both segments. The properness of the
  175. // intersection is ensured by using strict leftness.
  176. static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
  177. {
  178. // Eliminate improper cases.
  179. if (collinear(a,b,c) || collinear(a,b,d) ||
  180. collinear(c,d,a) || collinear(c,d,b))
  181. return false;
  182. return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
  183. }
  184. // Returns T iff (a,b,c) are collinear and point c lies
  185. // on the closed segement ab.
  186. static bool between(const int* a, const int* b, const int* c)
  187. {
  188. if (!collinear(a, b, c))
  189. return false;
  190. // If ab not vertical, check betweenness on x; else on y.
  191. if (a[0] != b[0])
  192. return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
  193. else
  194. return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
  195. }
  196. // Returns true iff segments ab and cd intersect, properly or improperly.
  197. static bool intersect(const int* a, const int* b, const int* c, const int* d)
  198. {
  199. if (intersectProp(a, b, c, d))
  200. return true;
  201. else if (between(a, b, c) || between(a, b, d) ||
  202. between(c, d, a) || between(c, d, b))
  203. return true;
  204. else
  205. return false;
  206. }
  207. static bool vequal(const int* a, const int* b)
  208. {
  209. return a[0] == b[0] && a[2] == b[2];
  210. }
  211. // Returns T iff (v_i, v_j) is a proper internal *or* external
  212. // diagonal of P, *ignoring edges incident to v_i and v_j*.
  213. static bool diagonalie(int i, int j, int n, const int* verts, int* indices)
  214. {
  215. const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
  216. const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
  217. // For each edge (k,k+1) of P
  218. for (int k = 0; k < n; k++)
  219. {
  220. int k1 = next(k, n);
  221. // Skip edges incident to i or j
  222. if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
  223. {
  224. const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
  225. const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
  226. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  227. continue;
  228. if (intersect(d0, d1, p0, p1))
  229. return false;
  230. }
  231. }
  232. return true;
  233. }
  234. // Returns true iff the diagonal (i,j) is strictly internal to the
  235. // polygon P in the neighborhood of the i endpoint.
  236. static bool inCone(int i, int j, int n, const int* verts, int* indices)
  237. {
  238. const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
  239. const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
  240. const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
  241. const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
  242. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  243. if (leftOn(pin1, pi, pi1))
  244. return left(pi, pj, pin1) && left(pj, pi, pi1);
  245. // Assume (i-1,i,i+1) not collinear.
  246. // else P[i] is reflex.
  247. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  248. }
  249. // Returns T iff (v_i, v_j) is a proper internal
  250. // diagonal of P.
  251. static bool diagonal(int i, int j, int n, const int* verts, int* indices)
  252. {
  253. return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
  254. }
  255. static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)
  256. {
  257. const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
  258. const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
  259. // For each edge (k,k+1) of P
  260. for (int k = 0; k < n; k++)
  261. {
  262. int k1 = next(k, n);
  263. // Skip edges incident to i or j
  264. if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
  265. {
  266. const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
  267. const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
  268. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  269. continue;
  270. if (intersectProp(d0, d1, p0, p1))
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)
  277. {
  278. const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
  279. const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
  280. const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
  281. const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
  282. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  283. if (leftOn(pin1, pi, pi1))
  284. return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);
  285. // Assume (i-1,i,i+1) not collinear.
  286. // else P[i] is reflex.
  287. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  288. }
  289. static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)
  290. {
  291. return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);
  292. }
  293. static int triangulate(int n, const int* verts, int* indices, int* tris)
  294. {
  295. int ntris = 0;
  296. int* dst = tris;
  297. // The last bit of the index is used to indicate if the vertex can be removed.
  298. for (int i = 0; i < n; i++)
  299. {
  300. int i1 = next(i, n);
  301. int i2 = next(i1, n);
  302. if (diagonal(i, i2, n, verts, indices))
  303. indices[i1] |= 0x80000000;
  304. }
  305. while (n > 3)
  306. {
  307. int minLen = -1;
  308. int mini = -1;
  309. for (int i = 0; i < n; i++)
  310. {
  311. int i1 = next(i, n);
  312. if (indices[i1] & 0x80000000)
  313. {
  314. const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
  315. const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4];
  316. int dx = p2[0] - p0[0];
  317. int dy = p2[2] - p0[2];
  318. int len = dx*dx + dy*dy;
  319. if (minLen < 0 || len < minLen)
  320. {
  321. minLen = len;
  322. mini = i;
  323. }
  324. }
  325. }
  326. if (mini == -1)
  327. {
  328. // We might get here because the contour has overlapping segments, like this:
  329. //
  330. // A o-o=====o---o B
  331. // / |C D| \.
  332. // o o o o
  333. // : : : :
  334. // We'll try to recover by loosing up the inCone test a bit so that a diagonal
  335. // like A-B or C-D can be found and we can continue.
  336. minLen = -1;
  337. mini = -1;
  338. for (int i = 0; i < n; i++)
  339. {
  340. int i1 = next(i, n);
  341. int i2 = next(i1, n);
  342. if (diagonalLoose(i, i2, n, verts, indices))
  343. {
  344. const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
  345. const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];
  346. int dx = p2[0] - p0[0];
  347. int dy = p2[2] - p0[2];
  348. int len = dx*dx + dy*dy;
  349. if (minLen < 0 || len < minLen)
  350. {
  351. minLen = len;
  352. mini = i;
  353. }
  354. }
  355. }
  356. if (mini == -1)
  357. {
  358. // The contour is messed up. This sometimes happens
  359. // if the contour simplification is too aggressive.
  360. return -ntris;
  361. }
  362. }
  363. int i = mini;
  364. int i1 = next(i, n);
  365. int i2 = next(i1, n);
  366. *dst++ = indices[i] & 0x0fffffff;
  367. *dst++ = indices[i1] & 0x0fffffff;
  368. *dst++ = indices[i2] & 0x0fffffff;
  369. ntris++;
  370. // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
  371. n--;
  372. for (int k = i1; k < n; k++)
  373. indices[k] = indices[k+1];
  374. if (i1 >= n) i1 = 0;
  375. i = prev(i1,n);
  376. // Update diagonal flags.
  377. if (diagonal(prev(i, n), i1, n, verts, indices))
  378. indices[i] |= 0x80000000;
  379. else
  380. indices[i] &= 0x0fffffff;
  381. if (diagonal(i, next(i1, n), n, verts, indices))
  382. indices[i1] |= 0x80000000;
  383. else
  384. indices[i1] &= 0x0fffffff;
  385. }
  386. // Append the remaining triangle.
  387. *dst++ = indices[0] & 0x0fffffff;
  388. *dst++ = indices[1] & 0x0fffffff;
  389. *dst++ = indices[2] & 0x0fffffff;
  390. ntris++;
  391. return ntris;
  392. }
  393. static int countPolyVerts(const unsigned short* p, const int nvp)
  394. {
  395. for (int i = 0; i < nvp; ++i)
  396. if (p[i] == RC_MESH_NULL_IDX)
  397. return i;
  398. return nvp;
  399. }
  400. inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
  401. {
  402. return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -
  403. ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;
  404. }
  405. static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
  406. const unsigned short* verts, int& ea, int& eb,
  407. const int nvp)
  408. {
  409. const int na = countPolyVerts(pa, nvp);
  410. const int nb = countPolyVerts(pb, nvp);
  411. // If the merged polygon would be too big, do not merge.
  412. if (na+nb-2 > nvp)
  413. return -1;
  414. // Check if the polygons share an edge.
  415. ea = -1;
  416. eb = -1;
  417. for (int i = 0; i < na; ++i)
  418. {
  419. unsigned short va0 = pa[i];
  420. unsigned short va1 = pa[(i+1) % na];
  421. if (va0 > va1)
  422. rcSwap(va0, va1);
  423. for (int j = 0; j < nb; ++j)
  424. {
  425. unsigned short vb0 = pb[j];
  426. unsigned short vb1 = pb[(j+1) % nb];
  427. if (vb0 > vb1)
  428. rcSwap(vb0, vb1);
  429. if (va0 == vb0 && va1 == vb1)
  430. {
  431. ea = i;
  432. eb = j;
  433. break;
  434. }
  435. }
  436. }
  437. // No common edge, cannot merge.
  438. if (ea == -1 || eb == -1)
  439. return -1;
  440. // Check to see if the merged polygon would be convex.
  441. unsigned short va, vb, vc;
  442. va = pa[(ea+na-1) % na];
  443. vb = pa[ea];
  444. vc = pb[(eb+2) % nb];
  445. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  446. return -1;
  447. va = pb[(eb+nb-1) % nb];
  448. vb = pb[eb];
  449. vc = pa[(ea+2) % na];
  450. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  451. return -1;
  452. va = pa[ea];
  453. vb = pa[(ea+1)%na];
  454. int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
  455. int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
  456. return dx*dx + dy*dy;
  457. }
  458. static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,
  459. unsigned short* tmp, const int nvp)
  460. {
  461. const int na = countPolyVerts(pa, nvp);
  462. const int nb = countPolyVerts(pb, nvp);
  463. // Merge polygons.
  464. memset(tmp, 0xff, sizeof(unsigned short)*nvp);
  465. int n = 0;
  466. // Add pa
  467. for (int i = 0; i < na-1; ++i)
  468. tmp[n++] = pa[(ea+1+i) % na];
  469. // Add pb
  470. for (int i = 0; i < nb-1; ++i)
  471. tmp[n++] = pb[(eb+1+i) % nb];
  472. memcpy(pa, tmp, sizeof(unsigned short)*nvp);
  473. }
  474. static void pushFront(int v, int* arr, int& an)
  475. {
  476. an++;
  477. for (int i = an-1; i > 0; --i) arr[i] = arr[i-1];
  478. arr[0] = v;
  479. }
  480. static void pushBack(int v, int* arr, int& an)
  481. {
  482. arr[an] = v;
  483. an++;
  484. }
  485. static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem)
  486. {
  487. const int nvp = mesh.nvp;
  488. // Count number of polygons to remove.
  489. int numTouchedVerts = 0;
  490. int numRemainingEdges = 0;
  491. for (int i = 0; i < mesh.npolys; ++i)
  492. {
  493. unsigned short* p = &mesh.polys[i*nvp*2];
  494. const int nv = countPolyVerts(p, nvp);
  495. int numRemoved = 0;
  496. int numVerts = 0;
  497. for (int j = 0; j < nv; ++j)
  498. {
  499. if (p[j] == rem)
  500. {
  501. numTouchedVerts++;
  502. numRemoved++;
  503. }
  504. numVerts++;
  505. }
  506. if (numRemoved)
  507. {
  508. numRemainingEdges += numVerts-(numRemoved+1);
  509. }
  510. }
  511. // There would be too few edges remaining to create a polygon.
  512. // This can happen for example when a tip of a triangle is marked
  513. // as deletion, but there are no other polys that share the vertex.
  514. // In this case, the vertex should not be removed.
  515. if (numRemainingEdges <= 2)
  516. return false;
  517. // Find edges which share the removed vertex.
  518. const int maxEdges = numTouchedVerts*2;
  519. int nedges = 0;
  520. rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));
  521. if (!edges)
  522. {
  523. ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);
  524. return false;
  525. }
  526. for (int i = 0; i < mesh.npolys; ++i)
  527. {
  528. unsigned short* p = &mesh.polys[i*nvp*2];
  529. const int nv = countPolyVerts(p, nvp);
  530. // Collect edges which touches the removed vertex.
  531. for (int j = 0, k = nv-1; j < nv; k = j++)
  532. {
  533. if (p[j] == rem || p[k] == rem)
  534. {
  535. // Arrange edge so that a=rem.
  536. int a = p[j], b = p[k];
  537. if (b == rem)
  538. rcSwap(a,b);
  539. // Check if the edge exists
  540. bool exists = false;
  541. for (int m = 0; m < nedges; ++m)
  542. {
  543. int* e = &edges[m*3];
  544. if (e[1] == b)
  545. {
  546. // Exists, increment vertex share count.
  547. e[2]++;
  548. exists = true;
  549. }
  550. }
  551. // Add new edge.
  552. if (!exists)
  553. {
  554. int* e = &edges[nedges*3];
  555. e[0] = a;
  556. e[1] = b;
  557. e[2] = 1;
  558. nedges++;
  559. }
  560. }
  561. }
  562. }
  563. // There should be no more than 2 open edges.
  564. // This catches the case that two non-adjacent polygons
  565. // share the removed vertex. In that case, do not remove the vertex.
  566. int numOpenEdges = 0;
  567. for (int i = 0; i < nedges; ++i)
  568. {
  569. if (edges[i*3+2] < 2)
  570. numOpenEdges++;
  571. }
  572. if (numOpenEdges > 2)
  573. return false;
  574. return true;
  575. }
  576. static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris)
  577. {
  578. const int nvp = mesh.nvp;
  579. // Count number of polygons to remove.
  580. int numRemovedVerts = 0;
  581. for (int i = 0; i < mesh.npolys; ++i)
  582. {
  583. unsigned short* p = &mesh.polys[i*nvp*2];
  584. const int nv = countPolyVerts(p, nvp);
  585. for (int j = 0; j < nv; ++j)
  586. {
  587. if (p[j] == rem)
  588. numRemovedVerts++;
  589. }
  590. }
  591. int nedges = 0;
  592. rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));
  593. if (!edges)
  594. {
  595. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);
  596. return false;
  597. }
  598. int nhole = 0;
  599. rcScopedDelete<int> hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  600. if (!hole)
  601. {
  602. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);
  603. return false;
  604. }
  605. int nhreg = 0;
  606. rcScopedDelete<int> hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  607. if (!hreg)
  608. {
  609. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);
  610. return false;
  611. }
  612. int nharea = 0;
  613. rcScopedDelete<int> harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  614. if (!harea)
  615. {
  616. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);
  617. return false;
  618. }
  619. for (int i = 0; i < mesh.npolys; ++i)
  620. {
  621. unsigned short* p = &mesh.polys[i*nvp*2];
  622. const int nv = countPolyVerts(p, nvp);
  623. bool hasRem = false;
  624. for (int j = 0; j < nv; ++j)
  625. if (p[j] == rem) hasRem = true;
  626. if (hasRem)
  627. {
  628. // Collect edges which does not touch the removed vertex.
  629. for (int j = 0, k = nv-1; j < nv; k = j++)
  630. {
  631. if (p[j] != rem && p[k] != rem)
  632. {
  633. int* e = &edges[nedges*4];
  634. e[0] = p[k];
  635. e[1] = p[j];
  636. e[2] = mesh.regs[i];
  637. e[3] = mesh.areas[i];
  638. nedges++;
  639. }
  640. }
  641. // Remove the polygon.
  642. unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];
  643. if (p != p2)
  644. memcpy(p,p2,sizeof(unsigned short)*nvp);
  645. memset(p+nvp,0xff,sizeof(unsigned short)*nvp);
  646. mesh.regs[i] = mesh.regs[mesh.npolys-1];
  647. mesh.areas[i] = mesh.areas[mesh.npolys-1];
  648. mesh.npolys--;
  649. --i;
  650. }
  651. }
  652. // Remove vertex.
  653. for (int i = (int)rem; i < mesh.nverts - 1; ++i)
  654. {
  655. mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
  656. mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
  657. mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
  658. }
  659. mesh.nverts--;
  660. // Adjust indices to match the removed vertex layout.
  661. for (int i = 0; i < mesh.npolys; ++i)
  662. {
  663. unsigned short* p = &mesh.polys[i*nvp*2];
  664. const int nv = countPolyVerts(p, nvp);
  665. for (int j = 0; j < nv; ++j)
  666. if (p[j] > rem) p[j]--;
  667. }
  668. for (int i = 0; i < nedges; ++i)
  669. {
  670. if (edges[i*4+0] > rem) edges[i*4+0]--;
  671. if (edges[i*4+1] > rem) edges[i*4+1]--;
  672. }
  673. if (nedges == 0)
  674. return true;
  675. // Start with one vertex, keep appending connected
  676. // segments to the start and end of the hole.
  677. pushBack(edges[0], hole, nhole);
  678. pushBack(edges[2], hreg, nhreg);
  679. pushBack(edges[3], harea, nharea);
  680. while (nedges)
  681. {
  682. bool match = false;
  683. for (int i = 0; i < nedges; ++i)
  684. {
  685. const int ea = edges[i*4+0];
  686. const int eb = edges[i*4+1];
  687. const int r = edges[i*4+2];
  688. const int a = edges[i*4+3];
  689. bool add = false;
  690. if (hole[0] == eb)
  691. {
  692. // The segment matches the beginning of the hole boundary.
  693. pushFront(ea, hole, nhole);
  694. pushFront(r, hreg, nhreg);
  695. pushFront(a, harea, nharea);
  696. add = true;
  697. }
  698. else if (hole[nhole-1] == ea)
  699. {
  700. // The segment matches the end of the hole boundary.
  701. pushBack(eb, hole, nhole);
  702. pushBack(r, hreg, nhreg);
  703. pushBack(a, harea, nharea);
  704. add = true;
  705. }
  706. if (add)
  707. {
  708. // The edge segment was added, remove it.
  709. edges[i*4+0] = edges[(nedges-1)*4+0];
  710. edges[i*4+1] = edges[(nedges-1)*4+1];
  711. edges[i*4+2] = edges[(nedges-1)*4+2];
  712. edges[i*4+3] = edges[(nedges-1)*4+3];
  713. --nedges;
  714. match = true;
  715. --i;
  716. }
  717. }
  718. if (!match)
  719. break;
  720. }
  721. rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
  722. if (!tris)
  723. {
  724. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);
  725. return false;
  726. }
  727. rcScopedDelete<int> tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));
  728. if (!tverts)
  729. {
  730. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);
  731. return false;
  732. }
  733. rcScopedDelete<int> thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));
  734. if (!thole)
  735. {
  736. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);
  737. return false;
  738. }
  739. // Generate temp vertex array for triangulation.
  740. for (int i = 0; i < nhole; ++i)
  741. {
  742. const int pi = hole[i];
  743. tverts[i*4+0] = mesh.verts[pi*3+0];
  744. tverts[i*4+1] = mesh.verts[pi*3+1];
  745. tverts[i*4+2] = mesh.verts[pi*3+2];
  746. tverts[i*4+3] = 0;
  747. thole[i] = i;
  748. }
  749. // Triangulate the hole.
  750. int ntris = triangulate(nhole, &tverts[0], &thole[0], tris);
  751. if (ntris < 0)
  752. {
  753. ntris = -ntris;
  754. ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results.");
  755. }
  756. // Merge the hole triangles back to polygons.
  757. rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));
  758. if (!polys)
  759. {
  760. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);
  761. return false;
  762. }
  763. rcScopedDelete<unsigned short> pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));
  764. if (!pregs)
  765. {
  766. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);
  767. return false;
  768. }
  769. rcScopedDelete<unsigned char> pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));
  770. if (!pareas)
  771. {
  772. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);
  773. return false;
  774. }
  775. unsigned short* tmpPoly = &polys[ntris*nvp];
  776. // Build initial polygons.
  777. int npolys = 0;
  778. memset(polys, 0xff, ntris*nvp*sizeof(unsigned short));
  779. for (int j = 0; j < ntris; ++j)
  780. {
  781. int* t = &tris[j*3];
  782. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  783. {
  784. polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
  785. polys[npolys*nvp+1] = (unsigned short)hole[t[1]];
  786. polys[npolys*nvp+2] = (unsigned short)hole[t[2]];
  787. // If this polygon covers multiple region types then
  788. // mark it as such
  789. if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])
  790. pregs[npolys] = RC_MULTIPLE_REGS;
  791. else
  792. pregs[npolys] = (unsigned short)hreg[t[0]];
  793. pareas[npolys] = (unsigned char)harea[t[0]];
  794. npolys++;
  795. }
  796. }
  797. if (!npolys)
  798. return true;
  799. // Merge polygons.
  800. if (nvp > 3)
  801. {
  802. for (;;)
  803. {
  804. // Find best polygons to merge.
  805. int bestMergeVal = 0;
  806. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  807. for (int j = 0; j < npolys-1; ++j)
  808. {
  809. unsigned short* pj = &polys[j*nvp];
  810. for (int k = j+1; k < npolys; ++k)
  811. {
  812. unsigned short* pk = &polys[k*nvp];
  813. int ea, eb;
  814. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
  815. if (v > bestMergeVal)
  816. {
  817. bestMergeVal = v;
  818. bestPa = j;
  819. bestPb = k;
  820. bestEa = ea;
  821. bestEb = eb;
  822. }
  823. }
  824. }
  825. if (bestMergeVal > 0)
  826. {
  827. // Found best, merge.
  828. unsigned short* pa = &polys[bestPa*nvp];
  829. unsigned short* pb = &polys[bestPb*nvp];
  830. mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
  831. if (pregs[bestPa] != pregs[bestPb])
  832. pregs[bestPa] = RC_MULTIPLE_REGS;
  833. unsigned short* last = &polys[(npolys-1)*nvp];
  834. if (pb != last)
  835. memcpy(pb, last, sizeof(unsigned short)*nvp);
  836. pregs[bestPb] = pregs[npolys-1];
  837. pareas[bestPb] = pareas[npolys-1];
  838. npolys--;
  839. }
  840. else
  841. {
  842. // Could not merge any polygons, stop.
  843. break;
  844. }
  845. }
  846. }
  847. // Store polygons.
  848. for (int i = 0; i < npolys; ++i)
  849. {
  850. if (mesh.npolys >= maxTris) break;
  851. unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
  852. memset(p,0xff,sizeof(unsigned short)*nvp*2);
  853. for (int j = 0; j < nvp; ++j)
  854. p[j] = polys[i*nvp+j];
  855. mesh.regs[mesh.npolys] = pregs[i];
  856. mesh.areas[mesh.npolys] = pareas[i];
  857. mesh.npolys++;
  858. if (mesh.npolys > maxTris)
  859. {
  860. ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
  861. return false;
  862. }
  863. }
  864. return true;
  865. }
  866. /// @par
  867. ///
  868. /// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper
  869. /// limit must be retricted to <= #DT_VERTS_PER_POLYGON.
  870. ///
  871. /// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig
  872. bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMesh& mesh)
  873. {
  874. rcAssert(ctx);
  875. rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);
  876. rcVcopy(mesh.bmin, cset.bmin);
  877. rcVcopy(mesh.bmax, cset.bmax);
  878. mesh.cs = cset.cs;
  879. mesh.ch = cset.ch;
  880. mesh.borderSize = cset.borderSize;
  881. mesh.maxEdgeError = cset.maxError;
  882. int maxVertices = 0;
  883. int maxTris = 0;
  884. int maxVertsPerCont = 0;
  885. for (int i = 0; i < cset.nconts; ++i)
  886. {
  887. // Skip null contours.
  888. if (cset.conts[i].nverts < 3) continue;
  889. maxVertices += cset.conts[i].nverts;
  890. maxTris += cset.conts[i].nverts - 2;
  891. maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts);
  892. }
  893. if (maxVertices >= 0xfffe)
  894. {
  895. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices);
  896. return false;
  897. }
  898. rcScopedDelete<unsigned char> vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));
  899. if (!vflags)
  900. {
  901. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);
  902. return false;
  903. }
  904. memset(vflags, 0, maxVertices);
  905. mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM);
  906. if (!mesh.verts)
  907. {
  908. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);
  909. return false;
  910. }
  911. mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM);
  912. if (!mesh.polys)
  913. {
  914. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2);
  915. return false;
  916. }
  917. mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM);
  918. if (!mesh.regs)
  919. {
  920. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris);
  921. return false;
  922. }
  923. mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM);
  924. if (!mesh.areas)
  925. {
  926. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris);
  927. return false;
  928. }
  929. mesh.nverts = 0;
  930. mesh.npolys = 0;
  931. mesh.nvp = nvp;
  932. mesh.maxpolys = maxTris;
  933. memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
  934. memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2);
  935. memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);
  936. memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
  937. rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));
  938. if (!nextVert)
  939. {
  940. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);
  941. return false;
  942. }
  943. memset(nextVert, 0, sizeof(int)*maxVertices);
  944. rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
  945. if (!firstVert)
  946. {
  947. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
  948. return false;
  949. }
  950. for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
  951. firstVert[i] = -1;
  952. rcScopedDelete<int> indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));
  953. if (!indices)
  954. {
  955. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);
  956. return false;
  957. }
  958. rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));
  959. if (!tris)
  960. {
  961. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);
  962. return false;
  963. }
  964. rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));
  965. if (!polys)
  966. {
  967. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);
  968. return false;
  969. }
  970. unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp];
  971. for (int i = 0; i < cset.nconts; ++i)
  972. {
  973. rcContour& cont = cset.conts[i];
  974. // Skip null contours.
  975. if (cont.nverts < 3)
  976. continue;
  977. // Triangulate contour
  978. for (int j = 0; j < cont.nverts; ++j)
  979. indices[j] = j;
  980. int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
  981. if (ntris <= 0)
  982. {
  983. // Bad triangulation, should not happen.
  984. /* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]);
  985. printf("\tconst float cs = %ff;\n", cset.cs);
  986. printf("\tconst float ch = %ff;\n", cset.ch);
  987. printf("\tconst int verts[] = {\n");
  988. for (int k = 0; k < cont.nverts; ++k)
  989. {
  990. const int* v = &cont.verts[k*4];
  991. printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]);
  992. }
  993. printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/
  994. ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i);
  995. ntris = -ntris;
  996. }
  997. // Add and merge vertices.
  998. for (int j = 0; j < cont.nverts; ++j)
  999. {
  1000. const int* v = &cont.verts[j*4];
  1001. indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
  1002. mesh.verts, firstVert, nextVert, mesh.nverts);
  1003. if (v[3] & RC_BORDER_VERTEX)
  1004. {
  1005. // This vertex should be removed.
  1006. vflags[indices[j]] = 1;
  1007. }
  1008. }
  1009. // Build initial polygons.
  1010. int npolys = 0;
  1011. memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));
  1012. for (int j = 0; j < ntris; ++j)
  1013. {
  1014. int* t = &tris[j*3];
  1015. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  1016. {
  1017. polys[npolys*nvp+0] = (unsigned short)indices[t[0]];
  1018. polys[npolys*nvp+1] = (unsigned short)indices[t[1]];
  1019. polys[npolys*nvp+2] = (unsigned short)indices[t[2]];
  1020. npolys++;
  1021. }
  1022. }
  1023. if (!npolys)
  1024. continue;
  1025. // Merge polygons.
  1026. if (nvp > 3)
  1027. {
  1028. for(;;)
  1029. {
  1030. // Find best polygons to merge.
  1031. int bestMergeVal = 0;
  1032. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  1033. for (int j = 0; j < npolys-1; ++j)
  1034. {
  1035. unsigned short* pj = &polys[j*nvp];
  1036. for (int k = j+1; k < npolys; ++k)
  1037. {
  1038. unsigned short* pk = &polys[k*nvp];
  1039. int ea, eb;
  1040. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
  1041. if (v > bestMergeVal)
  1042. {
  1043. bestMergeVal = v;
  1044. bestPa = j;
  1045. bestPb = k;
  1046. bestEa = ea;
  1047. bestEb = eb;
  1048. }
  1049. }
  1050. }
  1051. if (bestMergeVal > 0)
  1052. {
  1053. // Found best, merge.
  1054. unsigned short* pa = &polys[bestPa*nvp];
  1055. unsigned short* pb = &polys[bestPb*nvp];
  1056. mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
  1057. unsigned short* lastPoly = &polys[(npolys-1)*nvp];
  1058. if (pb != lastPoly)
  1059. memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);
  1060. npolys--;
  1061. }
  1062. else
  1063. {
  1064. // Could not merge any polygons, stop.
  1065. break;
  1066. }
  1067. }
  1068. }
  1069. // Store polygons.
  1070. for (int j = 0; j < npolys; ++j)
  1071. {
  1072. unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
  1073. unsigned short* q = &polys[j*nvp];
  1074. for (int k = 0; k < nvp; ++k)
  1075. p[k] = q[k];
  1076. mesh.regs[mesh.npolys] = cont.reg;
  1077. mesh.areas[mesh.npolys] = cont.area;
  1078. mesh.npolys++;
  1079. if (mesh.npolys > maxTris)
  1080. {
  1081. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
  1082. return false;
  1083. }
  1084. }
  1085. }
  1086. // Remove edge vertices.
  1087. for (int i = 0; i < mesh.nverts; ++i)
  1088. {
  1089. if (vflags[i])
  1090. {
  1091. if (!canRemoveVertex(ctx, mesh, (unsigned short)i))
  1092. continue;
  1093. if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris))
  1094. {
  1095. // Failed to remove vertex
  1096. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i);
  1097. return false;
  1098. }
  1099. // Remove vertex
  1100. // Note: mesh.nverts is already decremented inside removeVertex()!
  1101. // Fixup vertex flags
  1102. for (int j = i; j < mesh.nverts; ++j)
  1103. vflags[j] = vflags[j+1];
  1104. --i;
  1105. }
  1106. }
  1107. // Calculate adjacency.
  1108. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp))
  1109. {
  1110. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed.");
  1111. return false;
  1112. }
  1113. // Find portal edges
  1114. if (mesh.borderSize > 0)
  1115. {
  1116. const int w = cset.width;
  1117. const int h = cset.height;
  1118. for (int i = 0; i < mesh.npolys; ++i)
  1119. {
  1120. unsigned short* p = &mesh.polys[i*2*nvp];
  1121. for (int j = 0; j < nvp; ++j)
  1122. {
  1123. if (p[j] == RC_MESH_NULL_IDX) break;
  1124. // Skip connected edges.
  1125. if (p[nvp+j] != RC_MESH_NULL_IDX)
  1126. continue;
  1127. int nj = j+1;
  1128. if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0;
  1129. const unsigned short* va = &mesh.verts[p[j]*3];
  1130. const unsigned short* vb = &mesh.verts[p[nj]*3];
  1131. if ((int)va[0] == 0 && (int)vb[0] == 0)
  1132. p[nvp+j] = 0x8000 | 0;
  1133. else if ((int)va[2] == h && (int)vb[2] == h)
  1134. p[nvp+j] = 0x8000 | 1;
  1135. else if ((int)va[0] == w && (int)vb[0] == w)
  1136. p[nvp+j] = 0x8000 | 2;
  1137. else if ((int)va[2] == 0 && (int)vb[2] == 0)
  1138. p[nvp+j] = 0x8000 | 3;
  1139. }
  1140. }
  1141. }
  1142. // Just allocate the mesh flags array. The user is resposible to fill it.
  1143. mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM);
  1144. if (!mesh.flags)
  1145. {
  1146. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys);
  1147. return false;
  1148. }
  1149. memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys);
  1150. if (mesh.nverts > 0xffff)
  1151. {
  1152. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
  1153. }
  1154. if (mesh.npolys > 0xffff)
  1155. {
  1156. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
  1157. }
  1158. return true;
  1159. }
  1160. /// @see rcAllocPolyMesh, rcPolyMesh
  1161. bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh)
  1162. {
  1163. rcAssert(ctx);
  1164. if (!nmeshes || !meshes)
  1165. return true;
  1166. rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);
  1167. mesh.nvp = meshes[0]->nvp;
  1168. mesh.cs = meshes[0]->cs;
  1169. mesh.ch = meshes[0]->ch;
  1170. rcVcopy(mesh.bmin, meshes[0]->bmin);
  1171. rcVcopy(mesh.bmax, meshes[0]->bmax);
  1172. int maxVerts = 0;
  1173. int maxPolys = 0;
  1174. int maxVertsPerMesh = 0;
  1175. for (int i = 0; i < nmeshes; ++i)
  1176. {
  1177. rcVmin(mesh.bmin, meshes[i]->bmin);
  1178. rcVmax(mesh.bmax, meshes[i]->bmax);
  1179. maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts);
  1180. maxVerts += meshes[i]->nverts;
  1181. maxPolys += meshes[i]->npolys;
  1182. }
  1183. mesh.nverts = 0;
  1184. mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM);
  1185. if (!mesh.verts)
  1186. {
  1187. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3);
  1188. return false;
  1189. }
  1190. mesh.npolys = 0;
  1191. mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM);
  1192. if (!mesh.polys)
  1193. {
  1194. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp);
  1195. return false;
  1196. }
  1197. memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp);
  1198. mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
  1199. if (!mesh.regs)
  1200. {
  1201. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys);
  1202. return false;
  1203. }
  1204. memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys);
  1205. mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM);
  1206. if (!mesh.areas)
  1207. {
  1208. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys);
  1209. return false;
  1210. }
  1211. memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys);
  1212. mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
  1213. if (!mesh.flags)
  1214. {
  1215. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys);
  1216. return false;
  1217. }
  1218. memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);
  1219. rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));
  1220. if (!nextVert)
  1221. {
  1222. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);
  1223. return false;
  1224. }
  1225. memset(nextVert, 0, sizeof(int)*maxVerts);
  1226. rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
  1227. if (!firstVert)
  1228. {
  1229. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
  1230. return false;
  1231. }
  1232. for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
  1233. firstVert[i] = -1;
  1234. rcScopedDelete<unsigned short> vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));
  1235. if (!vremap)
  1236. {
  1237. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);
  1238. return false;
  1239. }
  1240. memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);
  1241. for (int i = 0; i < nmeshes; ++i)
  1242. {
  1243. const rcPolyMesh* pmesh = meshes[i];
  1244. const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);
  1245. const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);
  1246. bool isMinX = (ox == 0);
  1247. bool isMinZ = (oz == 0);
  1248. bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;
  1249. bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;
  1250. bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);
  1251. for (int j = 0; j < pmesh->nverts; ++j)
  1252. {
  1253. unsigned short* v = &pmesh->verts[j*3];
  1254. vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz,
  1255. mesh.verts, firstVert, nextVert, mesh.nverts);
  1256. }
  1257. for (int j = 0; j < pmesh->npolys; ++j)
  1258. {
  1259. unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp];
  1260. unsigned short* src = &pmesh->polys[j*2*mesh.nvp];
  1261. mesh.regs[mesh.npolys] = pmesh->regs[j];
  1262. mesh.areas[mesh.npolys] = pmesh->areas[j];
  1263. mesh.flags[mesh.npolys] = pmesh->flags[j];
  1264. mesh.npolys++;
  1265. for (int k = 0; k < mesh.nvp; ++k)
  1266. {
  1267. if (src[k] == RC_MESH_NULL_IDX) break;
  1268. tgt[k] = vremap[src[k]];
  1269. }
  1270. if (isOnBorder)
  1271. {
  1272. for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)
  1273. {
  1274. if (src[k] & 0x8000 && src[k] != 0xffff)
  1275. {
  1276. unsigned short dir = src[k] & 0xf;
  1277. switch (dir)
  1278. {
  1279. case 0: // Portal x-
  1280. if (isMinX)
  1281. tgt[k] = src[k];
  1282. break;
  1283. case 1: // Portal z+
  1284. if (isMaxZ)
  1285. tgt[k] = src[k];
  1286. break;
  1287. case 2: // Portal x+
  1288. if (isMaxX)
  1289. tgt[k] = src[k];
  1290. break;
  1291. case 3: // Portal z-
  1292. if (isMinZ)
  1293. tgt[k] = src[k];
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. }
  1300. }
  1301. // Calculate adjacency.
  1302. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp))
  1303. {
  1304. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed.");
  1305. return false;
  1306. }
  1307. if (mesh.nverts > 0xffff)
  1308. {
  1309. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
  1310. }
  1311. if (mesh.npolys > 0xffff)
  1312. {
  1313. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
  1314. }
  1315. return true;
  1316. }
  1317. bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)
  1318. {
  1319. rcAssert(ctx);
  1320. // Destination must be empty.
  1321. rcAssert(dst.verts == 0);
  1322. rcAssert(dst.polys == 0);
  1323. rcAssert(dst.regs == 0);
  1324. rcAssert(dst.areas == 0);
  1325. rcAssert(dst.flags == 0);
  1326. dst.nverts = src.nverts;
  1327. dst.npolys = src.npolys;
  1328. dst.maxpolys = src.npolys;
  1329. dst.nvp = src.nvp;
  1330. rcVcopy(dst.bmin, src.bmin);
  1331. rcVcopy(dst.bmax, src.bmax);
  1332. dst.cs = src.cs;
  1333. dst.ch = src.ch;
  1334. dst.borderSize = src.borderSize;
  1335. dst.maxEdgeError = src.maxEdgeError;
  1336. dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);
  1337. if (!dst.verts)
  1338. {
  1339. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);
  1340. return false;
  1341. }
  1342. memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);
  1343. dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);
  1344. if (!dst.polys)
  1345. {
  1346. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);
  1347. return false;
  1348. }
  1349. memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);
  1350. dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
  1351. if (!dst.regs)
  1352. {
  1353. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);
  1354. return false;
  1355. }
  1356. memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);
  1357. dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);
  1358. if (!dst.areas)
  1359. {
  1360. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);
  1361. return false;
  1362. }
  1363. memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);
  1364. dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
  1365. if (!dst.flags)
  1366. {
  1367. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);
  1368. return false;
  1369. }
  1370. memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);
  1371. return true;
  1372. }