RecastMeshDetail.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. #include <math.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <stdio.h>
  23. #include "Recast.h"
  24. #include "RecastAlloc.h"
  25. #include "RecastAssert.h"
  26. static const unsigned RC_UNSET_HEIGHT = 0xffff;
  27. struct rcHeightPatch
  28. {
  29. inline rcHeightPatch() : data(0), xmin(0), ymin(0), width(0), height(0) {}
  30. inline ~rcHeightPatch() { rcFree(data); }
  31. unsigned short* data;
  32. int xmin, ymin, width, height;
  33. };
  34. inline float vdot2(const float* a, const float* b)
  35. {
  36. return a[0]*b[0] + a[2]*b[2];
  37. }
  38. inline float vdistSq2(const float* p, const float* q)
  39. {
  40. const float dx = q[0] - p[0];
  41. const float dy = q[2] - p[2];
  42. return dx*dx + dy*dy;
  43. }
  44. inline float vdist2(const float* p, const float* q)
  45. {
  46. return sqrtf(vdistSq2(p,q));
  47. }
  48. inline float vcross2(const float* p1, const float* p2, const float* p3)
  49. {
  50. const float u1 = p2[0] - p1[0];
  51. const float v1 = p2[2] - p1[2];
  52. const float u2 = p3[0] - p1[0];
  53. const float v2 = p3[2] - p1[2];
  54. return u1 * v2 - v1 * u2;
  55. }
  56. static bool circumCircle(const float* p1, const float* p2, const float* p3,
  57. float* c, float& r)
  58. {
  59. static const float EPS = 1e-6f;
  60. // Calculate the circle relative to p1, to avoid some precision issues.
  61. const float v1[3] = {0,0,0};
  62. float v2[3], v3[3];
  63. rcVsub(v2, p2,p1);
  64. rcVsub(v3, p3,p1);
  65. const float cp = vcross2(v1, v2, v3);
  66. if (fabsf(cp) > EPS)
  67. {
  68. const float v1Sq = vdot2(v1,v1);
  69. const float v2Sq = vdot2(v2,v2);
  70. const float v3Sq = vdot2(v3,v3);
  71. c[0] = (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp);
  72. c[1] = 0;
  73. c[2] = (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp);
  74. r = vdist2(c, v1);
  75. rcVadd(c, c, p1);
  76. return true;
  77. }
  78. rcVcopy(c, p1);
  79. r = 0;
  80. return false;
  81. }
  82. static float distPtTri(const float* p, const float* a, const float* b, const float* c)
  83. {
  84. float v0[3], v1[3], v2[3];
  85. rcVsub(v0, c,a);
  86. rcVsub(v1, b,a);
  87. rcVsub(v2, p,a);
  88. const float dot00 = vdot2(v0, v0);
  89. const float dot01 = vdot2(v0, v1);
  90. const float dot02 = vdot2(v0, v2);
  91. const float dot11 = vdot2(v1, v1);
  92. const float dot12 = vdot2(v1, v2);
  93. // Compute barycentric coordinates
  94. const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
  95. const float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  96. float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  97. // If point lies inside the triangle, return interpolated y-coord.
  98. static const float EPS = 1e-4f;
  99. if (u >= -EPS && v >= -EPS && (u+v) <= 1+EPS)
  100. {
  101. const float y = a[1] + v0[1]*u + v1[1]*v;
  102. return fabsf(y-p[1]);
  103. }
  104. return FLT_MAX;
  105. }
  106. static float distancePtSeg(const float* pt, const float* p, const float* q)
  107. {
  108. float pqx = q[0] - p[0];
  109. float pqy = q[1] - p[1];
  110. float pqz = q[2] - p[2];
  111. float dx = pt[0] - p[0];
  112. float dy = pt[1] - p[1];
  113. float dz = pt[2] - p[2];
  114. float d = pqx*pqx + pqy*pqy + pqz*pqz;
  115. float t = pqx*dx + pqy*dy + pqz*dz;
  116. if (d > 0)
  117. t /= d;
  118. if (t < 0)
  119. t = 0;
  120. else if (t > 1)
  121. t = 1;
  122. dx = p[0] + t*pqx - pt[0];
  123. dy = p[1] + t*pqy - pt[1];
  124. dz = p[2] + t*pqz - pt[2];
  125. return dx*dx + dy*dy + dz*dz;
  126. }
  127. static float distancePtSeg2d(const float* pt, const float* p, const float* q)
  128. {
  129. float pqx = q[0] - p[0];
  130. float pqz = q[2] - p[2];
  131. float dx = pt[0] - p[0];
  132. float dz = pt[2] - p[2];
  133. float d = pqx*pqx + pqz*pqz;
  134. float t = pqx*dx + pqz*dz;
  135. if (d > 0)
  136. t /= d;
  137. if (t < 0)
  138. t = 0;
  139. else if (t > 1)
  140. t = 1;
  141. dx = p[0] + t*pqx - pt[0];
  142. dz = p[2] + t*pqz - pt[2];
  143. return dx*dx + dz*dz;
  144. }
  145. static float distToTriMesh(const float* p, const float* verts, const int /*nverts*/, const int* tris, const int ntris)
  146. {
  147. float dmin = FLT_MAX;
  148. for (int i = 0; i < ntris; ++i)
  149. {
  150. const float* va = &verts[tris[i*4+0]*3];
  151. const float* vb = &verts[tris[i*4+1]*3];
  152. const float* vc = &verts[tris[i*4+2]*3];
  153. float d = distPtTri(p, va,vb,vc);
  154. if (d < dmin)
  155. dmin = d;
  156. }
  157. if (dmin == FLT_MAX) return -1;
  158. return dmin;
  159. }
  160. static float distToPoly(int nvert, const float* verts, const float* p)
  161. {
  162. float dmin = FLT_MAX;
  163. int i, j, c = 0;
  164. for (i = 0, j = nvert-1; i < nvert; j = i++)
  165. {
  166. const float* vi = &verts[i*3];
  167. const float* vj = &verts[j*3];
  168. if (((vi[2] > p[2]) != (vj[2] > p[2])) &&
  169. (p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
  170. c = !c;
  171. dmin = rcMin(dmin, distancePtSeg2d(p, vj, vi));
  172. }
  173. return c ? -dmin : dmin;
  174. }
  175. static unsigned short getHeight(const float fx, const float fy, const float fz,
  176. const float /*cs*/, const float ics, const float ch,
  177. const int radius, const rcHeightPatch& hp)
  178. {
  179. int ix = (int)floorf(fx*ics + 0.01f);
  180. int iz = (int)floorf(fz*ics + 0.01f);
  181. ix = rcClamp(ix-hp.xmin, 0, hp.width - 1);
  182. iz = rcClamp(iz-hp.ymin, 0, hp.height - 1);
  183. unsigned short h = hp.data[ix+iz*hp.width];
  184. if (h == RC_UNSET_HEIGHT)
  185. {
  186. // Special case when data might be bad.
  187. // Walk adjacent cells in a spiral up to 'radius', and look
  188. // for a pixel which has a valid height.
  189. int x = 1, z = 0, dx = 1, dz = 0;
  190. int maxSize = radius * 2 + 1;
  191. int maxIter = maxSize * maxSize - 1;
  192. int nextRingIterStart = 8;
  193. int nextRingIters = 16;
  194. float dmin = FLT_MAX;
  195. for (int i = 0; i < maxIter; i++)
  196. {
  197. const int nx = ix + x;
  198. const int nz = iz + z;
  199. if (nx >= 0 && nz >= 0 && nx < hp.width && nz < hp.height)
  200. {
  201. const unsigned short nh = hp.data[nx + nz*hp.width];
  202. if (nh != RC_UNSET_HEIGHT)
  203. {
  204. const float d = fabsf(nh*ch - fy);
  205. if (d < dmin)
  206. {
  207. h = nh;
  208. dmin = d;
  209. }
  210. }
  211. }
  212. // We are searching in a grid which looks approximately like this:
  213. // __________
  214. // |2 ______ 2|
  215. // | |1 __ 1| |
  216. // | | |__| | |
  217. // | |______| |
  218. // |__________|
  219. // We want to find the best height as close to the center cell as possible. This means that
  220. // if we find a height in one of the neighbor cells to the center, we don't want to
  221. // expand further out than the 8 neighbors - we want to limit our search to the closest
  222. // of these "rings", but the best height in the ring.
  223. // For example, the center is just 1 cell. We checked that at the entrance to the function.
  224. // The next "ring" contains 8 cells (marked 1 above). Those are all the neighbors to the center cell.
  225. // The next one again contains 16 cells (marked 2). In general each ring has 8 additional cells, which
  226. // can be thought of as adding 2 cells around the "center" of each side when we expand the ring.
  227. // Here we detect if we are about to enter the next ring, and if we are and we have found
  228. // a height, we abort the search.
  229. if (i + 1 == nextRingIterStart)
  230. {
  231. if (h != RC_UNSET_HEIGHT)
  232. break;
  233. nextRingIterStart += nextRingIters;
  234. nextRingIters += 8;
  235. }
  236. if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z)))
  237. {
  238. int tmp = dx;
  239. dx = -dz;
  240. dz = tmp;
  241. }
  242. x += dx;
  243. z += dz;
  244. }
  245. }
  246. return h;
  247. }
  248. enum EdgeValues
  249. {
  250. EV_UNDEF = -1,
  251. EV_HULL = -2
  252. };
  253. static int findEdge(const int* edges, int nedges, int s, int t)
  254. {
  255. for (int i = 0; i < nedges; i++)
  256. {
  257. const int* e = &edges[i*4];
  258. if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s))
  259. return i;
  260. }
  261. return EV_UNDEF;
  262. }
  263. static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r)
  264. {
  265. if (nedges >= maxEdges)
  266. {
  267. ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges);
  268. return EV_UNDEF;
  269. }
  270. // Add edge if not already in the triangulation.
  271. int e = findEdge(edges, nedges, s, t);
  272. if (e == EV_UNDEF)
  273. {
  274. int* edge = &edges[nedges*4];
  275. edge[0] = s;
  276. edge[1] = t;
  277. edge[2] = l;
  278. edge[3] = r;
  279. return nedges++;
  280. }
  281. else
  282. {
  283. return EV_UNDEF;
  284. }
  285. }
  286. static void updateLeftFace(int* e, int s, int t, int f)
  287. {
  288. if (e[0] == s && e[1] == t && e[2] == EV_UNDEF)
  289. e[2] = f;
  290. else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF)
  291. e[3] = f;
  292. }
  293. static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d)
  294. {
  295. const float a1 = vcross2(a, b, d);
  296. const float a2 = vcross2(a, b, c);
  297. if (a1*a2 < 0.0f)
  298. {
  299. float a3 = vcross2(c, d, a);
  300. float a4 = a3 + a2 - a1;
  301. if (a3 * a4 < 0.0f)
  302. return 1;
  303. }
  304. return 0;
  305. }
  306. static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1)
  307. {
  308. for (int i = 0; i < nedges; ++i)
  309. {
  310. const int s0 = edges[i*4+0];
  311. const int t0 = edges[i*4+1];
  312. // Same or connected edges do not overlap.
  313. if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1)
  314. continue;
  315. if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3]))
  316. return true;
  317. }
  318. return false;
  319. }
  320. static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)
  321. {
  322. static const float EPS = 1e-5f;
  323. int* edge = &edges[e*4];
  324. // Cache s and t.
  325. int s,t;
  326. if (edge[2] == EV_UNDEF)
  327. {
  328. s = edge[0];
  329. t = edge[1];
  330. }
  331. else if (edge[3] == EV_UNDEF)
  332. {
  333. s = edge[1];
  334. t = edge[0];
  335. }
  336. else
  337. {
  338. // Edge already completed.
  339. return;
  340. }
  341. // Find best point on left of edge.
  342. int pt = npts;
  343. float c[3] = {0,0,0};
  344. float r = -1;
  345. for (int u = 0; u < npts; ++u)
  346. {
  347. if (u == s || u == t) continue;
  348. if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)
  349. {
  350. if (r < 0)
  351. {
  352. // The circle is not updated yet, do it now.
  353. pt = u;
  354. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  355. continue;
  356. }
  357. const float d = vdist2(c, &pts[u*3]);
  358. const float tol = 0.001f;
  359. if (d > r*(1+tol))
  360. {
  361. // Outside current circumcircle, skip.
  362. continue;
  363. }
  364. else if (d < r*(1-tol))
  365. {
  366. // Inside safe circumcircle, update circle.
  367. pt = u;
  368. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  369. }
  370. else
  371. {
  372. // Inside epsilon circum circle, do extra tests to make sure the edge is valid.
  373. // s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
  374. if (overlapEdges(pts, edges, nedges, s,u))
  375. continue;
  376. if (overlapEdges(pts, edges, nedges, t,u))
  377. continue;
  378. // Edge is valid.
  379. pt = u;
  380. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  381. }
  382. }
  383. }
  384. // Add new triangle or update edge info if s-t is on hull.
  385. if (pt < npts)
  386. {
  387. // Update face information of edge being completed.
  388. updateLeftFace(&edges[e*4], s, t, nfaces);
  389. // Add new edge or update face info of old edge.
  390. e = findEdge(edges, nedges, pt, s);
  391. if (e == EV_UNDEF)
  392. addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF);
  393. else
  394. updateLeftFace(&edges[e*4], pt, s, nfaces);
  395. // Add new edge or update face info of old edge.
  396. e = findEdge(edges, nedges, t, pt);
  397. if (e == EV_UNDEF)
  398. addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF);
  399. else
  400. updateLeftFace(&edges[e*4], t, pt, nfaces);
  401. nfaces++;
  402. }
  403. else
  404. {
  405. updateLeftFace(&edges[e*4], s, t, EV_HULL);
  406. }
  407. }
  408. static void delaunayHull(rcContext* ctx, const int npts, const float* pts,
  409. const int nhull, const int* hull,
  410. rcIntArray& tris, rcIntArray& edges)
  411. {
  412. int nfaces = 0;
  413. int nedges = 0;
  414. const int maxEdges = npts*10;
  415. edges.resize(maxEdges*4);
  416. for (int i = 0, j = nhull-1; i < nhull; j=i++)
  417. addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF);
  418. int currentEdge = 0;
  419. while (currentEdge < nedges)
  420. {
  421. if (edges[currentEdge*4+2] == EV_UNDEF)
  422. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  423. if (edges[currentEdge*4+3] == EV_UNDEF)
  424. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  425. currentEdge++;
  426. }
  427. // Create tris
  428. tris.resize(nfaces*4);
  429. for (int i = 0; i < nfaces*4; ++i)
  430. tris[i] = -1;
  431. for (int i = 0; i < nedges; ++i)
  432. {
  433. const int* e = &edges[i*4];
  434. if (e[3] >= 0)
  435. {
  436. // Left face
  437. int* t = &tris[e[3]*4];
  438. if (t[0] == -1)
  439. {
  440. t[0] = e[0];
  441. t[1] = e[1];
  442. }
  443. else if (t[0] == e[1])
  444. t[2] = e[0];
  445. else if (t[1] == e[0])
  446. t[2] = e[1];
  447. }
  448. if (e[2] >= 0)
  449. {
  450. // Right
  451. int* t = &tris[e[2]*4];
  452. if (t[0] == -1)
  453. {
  454. t[0] = e[1];
  455. t[1] = e[0];
  456. }
  457. else if (t[0] == e[0])
  458. t[2] = e[1];
  459. else if (t[1] == e[1])
  460. t[2] = e[0];
  461. }
  462. }
  463. for (int i = 0; i < tris.size()/4; ++i)
  464. {
  465. int* t = &tris[i*4];
  466. if (t[0] == -1 || t[1] == -1 || t[2] == -1)
  467. {
  468. ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);
  469. t[0] = tris[tris.size()-4];
  470. t[1] = tris[tris.size()-3];
  471. t[2] = tris[tris.size()-2];
  472. t[3] = tris[tris.size()-1];
  473. tris.resize(tris.size()-4);
  474. --i;
  475. }
  476. }
  477. }
  478. // Calculate minimum extend of the polygon.
  479. static float polyMinExtent(const float* verts, const int nverts)
  480. {
  481. float minDist = FLT_MAX;
  482. for (int i = 0; i < nverts; i++)
  483. {
  484. const int ni = (i+1) % nverts;
  485. const float* p1 = &verts[i*3];
  486. const float* p2 = &verts[ni*3];
  487. float maxEdgeDist = 0;
  488. for (int j = 0; j < nverts; j++)
  489. {
  490. if (j == i || j == ni) continue;
  491. float d = distancePtSeg2d(&verts[j*3], p1,p2);
  492. maxEdgeDist = rcMax(maxEdgeDist, d);
  493. }
  494. minDist = rcMin(minDist, maxEdgeDist);
  495. }
  496. return rcSqrt(minDist);
  497. }
  498. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  499. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  500. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  501. static void triangulateHull(const int /*nverts*/, const float* verts, const int nhull, const int* hull, const int nin, rcIntArray& tris)
  502. {
  503. int start = 0, left = 1, right = nhull-1;
  504. // Start from an ear with shortest perimeter.
  505. // This tends to favor well formed triangles as starting point.
  506. float dmin = FLT_MAX;
  507. for (int i = 0; i < nhull; i++)
  508. {
  509. if (hull[i] >= nin) continue; // Ears are triangles with original vertices as middle vertex while others are actually line segments on edges
  510. int pi = prev(i, nhull);
  511. int ni = next(i, nhull);
  512. const float* pv = &verts[hull[pi]*3];
  513. const float* cv = &verts[hull[i]*3];
  514. const float* nv = &verts[hull[ni]*3];
  515. const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);
  516. if (d < dmin)
  517. {
  518. start = i;
  519. left = ni;
  520. right = pi;
  521. dmin = d;
  522. }
  523. }
  524. // Add first triangle
  525. tris.push(hull[start]);
  526. tris.push(hull[left]);
  527. tris.push(hull[right]);
  528. tris.push(0);
  529. // Triangulate the polygon by moving left or right,
  530. // depending on which triangle has shorter perimeter.
  531. // This heuristic was chose emprically, since it seems
  532. // handle tesselated straight edges well.
  533. while (next(left, nhull) != right)
  534. {
  535. // Check to see if se should advance left or right.
  536. int nleft = next(left, nhull);
  537. int nright = prev(right, nhull);
  538. const float* cvleft = &verts[hull[left]*3];
  539. const float* nvleft = &verts[hull[nleft]*3];
  540. const float* cvright = &verts[hull[right]*3];
  541. const float* nvright = &verts[hull[nright]*3];
  542. const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);
  543. const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright);
  544. if (dleft < dright)
  545. {
  546. tris.push(hull[left]);
  547. tris.push(hull[nleft]);
  548. tris.push(hull[right]);
  549. tris.push(0);
  550. left = nleft;
  551. }
  552. else
  553. {
  554. tris.push(hull[left]);
  555. tris.push(hull[nright]);
  556. tris.push(hull[right]);
  557. tris.push(0);
  558. right = nright;
  559. }
  560. }
  561. }
  562. inline float getJitterX(const int i)
  563. {
  564. return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  565. }
  566. inline float getJitterY(const int i)
  567. {
  568. return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  569. }
  570. static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin,
  571. const float sampleDist, const float sampleMaxError,
  572. const int heightSearchRadius, const rcCompactHeightfield& chf,
  573. const rcHeightPatch& hp, float* verts, int& nverts,
  574. rcIntArray& tris, rcIntArray& edges, rcIntArray& samples)
  575. {
  576. static const int MAX_VERTS = 127;
  577. static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).
  578. static const int MAX_VERTS_PER_EDGE = 32;
  579. float edge[(MAX_VERTS_PER_EDGE+1)*3];
  580. int hull[MAX_VERTS];
  581. int nhull = 0;
  582. nverts = nin;
  583. for (int i = 0; i < nin; ++i)
  584. rcVcopy(&verts[i*3], &in[i*3]);
  585. edges.clear();
  586. tris.clear();
  587. const float cs = chf.cs;
  588. const float ics = 1.0f/cs;
  589. // Calculate minimum extents of the polygon based on input data.
  590. float minExtent = polyMinExtent(verts, nverts);
  591. // Tessellate outlines.
  592. // This is done in separate pass in order to ensure
  593. // seamless height values across the ply boundaries.
  594. if (sampleDist > 0)
  595. {
  596. for (int i = 0, j = nin-1; i < nin; j=i++)
  597. {
  598. const float* vj = &in[j*3];
  599. const float* vi = &in[i*3];
  600. bool swapped = false;
  601. // Make sure the segments are always handled in same order
  602. // using lexological sort or else there will be seams.
  603. if (fabsf(vj[0]-vi[0]) < 1e-6f)
  604. {
  605. if (vj[2] > vi[2])
  606. {
  607. rcSwap(vj,vi);
  608. swapped = true;
  609. }
  610. }
  611. else
  612. {
  613. if (vj[0] > vi[0])
  614. {
  615. rcSwap(vj,vi);
  616. swapped = true;
  617. }
  618. }
  619. // Create samples along the edge.
  620. float dx = vi[0] - vj[0];
  621. float dy = vi[1] - vj[1];
  622. float dz = vi[2] - vj[2];
  623. float d = sqrtf(dx*dx + dz*dz);
  624. int nn = 1 + (int)floorf(d/sampleDist);
  625. if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1;
  626. if (nverts+nn >= MAX_VERTS)
  627. nn = MAX_VERTS-1-nverts;
  628. for (int k = 0; k <= nn; ++k)
  629. {
  630. float u = (float)k/(float)nn;
  631. float* pos = &edge[k*3];
  632. pos[0] = vj[0] + dx*u;
  633. pos[1] = vj[1] + dy*u;
  634. pos[2] = vj[2] + dz*u;
  635. pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, heightSearchRadius, hp)*chf.ch;
  636. }
  637. // Simplify samples.
  638. int idx[MAX_VERTS_PER_EDGE] = {0,nn};
  639. int nidx = 2;
  640. for (int k = 0; k < nidx-1; )
  641. {
  642. const int a = idx[k];
  643. const int b = idx[k+1];
  644. const float* va = &edge[a*3];
  645. const float* vb = &edge[b*3];
  646. // Find maximum deviation along the segment.
  647. float maxd = 0;
  648. int maxi = -1;
  649. for (int m = a+1; m < b; ++m)
  650. {
  651. float dev = distancePtSeg(&edge[m*3],va,vb);
  652. if (dev > maxd)
  653. {
  654. maxd = dev;
  655. maxi = m;
  656. }
  657. }
  658. // If the max deviation is larger than accepted error,
  659. // add new point, else continue to next segment.
  660. if (maxi != -1 && maxd > rcSqr(sampleMaxError))
  661. {
  662. for (int m = nidx; m > k; --m)
  663. idx[m] = idx[m-1];
  664. idx[k+1] = maxi;
  665. nidx++;
  666. }
  667. else
  668. {
  669. ++k;
  670. }
  671. }
  672. hull[nhull++] = j;
  673. // Add new vertices.
  674. if (swapped)
  675. {
  676. for (int k = nidx-2; k > 0; --k)
  677. {
  678. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  679. hull[nhull++] = nverts;
  680. nverts++;
  681. }
  682. }
  683. else
  684. {
  685. for (int k = 1; k < nidx-1; ++k)
  686. {
  687. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  688. hull[nhull++] = nverts;
  689. nverts++;
  690. }
  691. }
  692. }
  693. }
  694. // If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.
  695. if (minExtent < sampleDist*2)
  696. {
  697. triangulateHull(nverts, verts, nhull, hull, nin, tris);
  698. return true;
  699. }
  700. // Tessellate the base mesh.
  701. // We're using the triangulateHull instead of delaunayHull as it tends to
  702. // create a bit better triangulation for long thin triangles when there
  703. // are no internal points.
  704. triangulateHull(nverts, verts, nhull, hull, nin, tris);
  705. if (tris.size() == 0)
  706. {
  707. // Could not triangulate the poly, make sure there is some valid data there.
  708. ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts);
  709. return true;
  710. }
  711. if (sampleDist > 0)
  712. {
  713. // Create sample locations in a grid.
  714. float bmin[3], bmax[3];
  715. rcVcopy(bmin, in);
  716. rcVcopy(bmax, in);
  717. for (int i = 1; i < nin; ++i)
  718. {
  719. rcVmin(bmin, &in[i*3]);
  720. rcVmax(bmax, &in[i*3]);
  721. }
  722. int x0 = (int)floorf(bmin[0]/sampleDist);
  723. int x1 = (int)ceilf(bmax[0]/sampleDist);
  724. int z0 = (int)floorf(bmin[2]/sampleDist);
  725. int z1 = (int)ceilf(bmax[2]/sampleDist);
  726. samples.clear();
  727. for (int z = z0; z < z1; ++z)
  728. {
  729. for (int x = x0; x < x1; ++x)
  730. {
  731. float pt[3];
  732. pt[0] = x*sampleDist;
  733. pt[1] = (bmax[1]+bmin[1])*0.5f;
  734. pt[2] = z*sampleDist;
  735. // Make sure the samples are not too close to the edges.
  736. if (distToPoly(nin,in,pt) > -sampleDist/2) continue;
  737. samples.push(x);
  738. samples.push(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, heightSearchRadius, hp));
  739. samples.push(z);
  740. samples.push(0); // Not added
  741. }
  742. }
  743. // Add the samples starting from the one that has the most
  744. // error. The procedure stops when all samples are added
  745. // or when the max error is within treshold.
  746. const int nsamples = samples.size()/4;
  747. for (int iter = 0; iter < nsamples; ++iter)
  748. {
  749. if (nverts >= MAX_VERTS)
  750. break;
  751. // Find sample with most error.
  752. float bestpt[3] = {0,0,0};
  753. float bestd = 0;
  754. int besti = -1;
  755. for (int i = 0; i < nsamples; ++i)
  756. {
  757. const int* s = &samples[i*4];
  758. if (s[3]) continue; // skip added.
  759. float pt[3];
  760. // The sample location is jittered to get rid of some bad triangulations
  761. // which are cause by symmetrical data from the grid structure.
  762. pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f;
  763. pt[1] = s[1]*chf.ch;
  764. pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f;
  765. float d = distToTriMesh(pt, verts, nverts, &tris[0], tris.size()/4);
  766. if (d < 0) continue; // did not hit the mesh.
  767. if (d > bestd)
  768. {
  769. bestd = d;
  770. besti = i;
  771. rcVcopy(bestpt,pt);
  772. }
  773. }
  774. // If the max error is within accepted threshold, stop tesselating.
  775. if (bestd <= sampleMaxError || besti == -1)
  776. break;
  777. // Mark sample as added.
  778. samples[besti*4+3] = 1;
  779. // Add the new sample point.
  780. rcVcopy(&verts[nverts*3],bestpt);
  781. nverts++;
  782. // Create new triangulation.
  783. // TODO: Incremental add instead of full rebuild.
  784. edges.clear();
  785. tris.clear();
  786. delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges);
  787. }
  788. }
  789. const int ntris = tris.size()/4;
  790. if (ntris > MAX_TRIS)
  791. {
  792. tris.resize(MAX_TRIS*4);
  793. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS);
  794. }
  795. return true;
  796. }
  797. static void seedArrayWithPolyCenter(rcContext* ctx, const rcCompactHeightfield& chf,
  798. const unsigned short* poly, const int npoly,
  799. const unsigned short* verts, const int bs,
  800. rcHeightPatch& hp, rcIntArray& array)
  801. {
  802. // Note: Reads to the compact heightfield are offset by border size (bs)
  803. // since border size offset is already removed from the polymesh vertices.
  804. static const int offset[9*2] =
  805. {
  806. 0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0,
  807. };
  808. // Find cell closest to a poly vertex
  809. int startCellX = 0, startCellY = 0, startSpanIndex = -1;
  810. int dmin = RC_UNSET_HEIGHT;
  811. for (int j = 0; j < npoly && dmin > 0; ++j)
  812. {
  813. for (int k = 0; k < 9 && dmin > 0; ++k)
  814. {
  815. const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0];
  816. const int ay = (int)verts[poly[j]*3+1];
  817. const int az = (int)verts[poly[j]*3+2] + offset[k*2+1];
  818. if (ax < hp.xmin || ax >= hp.xmin+hp.width ||
  819. az < hp.ymin || az >= hp.ymin+hp.height)
  820. continue;
  821. const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width];
  822. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni && dmin > 0; ++i)
  823. {
  824. const rcCompactSpan& s = chf.spans[i];
  825. int d = rcAbs(ay - (int)s.y);
  826. if (d < dmin)
  827. {
  828. startCellX = ax;
  829. startCellY = az;
  830. startSpanIndex = i;
  831. dmin = d;
  832. }
  833. }
  834. }
  835. }
  836. rcAssert(startSpanIndex != -1);
  837. // Find center of the polygon
  838. int pcx = 0, pcy = 0;
  839. for (int j = 0; j < npoly; ++j)
  840. {
  841. pcx += (int)verts[poly[j]*3+0];
  842. pcy += (int)verts[poly[j]*3+2];
  843. }
  844. pcx /= npoly;
  845. pcy /= npoly;
  846. // Use seeds array as a stack for DFS
  847. array.clear();
  848. array.push(startCellX);
  849. array.push(startCellY);
  850. array.push(startSpanIndex);
  851. int dirs[] = { 0, 1, 2, 3 };
  852. memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height);
  853. // DFS to move to the center. Note that we need a DFS here and can not just move
  854. // directly towards the center without recording intermediate nodes, even though the polygons
  855. // are convex. In very rare we can get stuck due to contour simplification if we do not
  856. // record nodes.
  857. int cx = -1, cy = -1, ci = -1;
  858. while (true)
  859. {
  860. if (array.size() < 3)
  861. {
  862. ctx->log(RC_LOG_WARNING, "Walk towards polygon center failed to reach center");
  863. break;
  864. }
  865. ci = array.pop();
  866. cy = array.pop();
  867. cx = array.pop();
  868. if (cx == pcx && cy == pcy)
  869. break;
  870. // If we are already at the correct X-position, prefer direction
  871. // directly towards the center in the Y-axis; otherwise prefer
  872. // direction in the X-axis
  873. int directDir;
  874. if (cx == pcx)
  875. directDir = rcGetDirForOffset(0, pcy > cy ? 1 : -1);
  876. else
  877. directDir = rcGetDirForOffset(pcx > cx ? 1 : -1, 0);
  878. // Push the direct dir last so we start with this on next iteration
  879. rcSwap(dirs[directDir], dirs[3]);
  880. const rcCompactSpan& cs = chf.spans[ci];
  881. for (int i = 0; i < 4; i++)
  882. {
  883. int dir = dirs[i];
  884. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED)
  885. continue;
  886. int newX = cx + rcGetDirOffsetX(dir);
  887. int newY = cy + rcGetDirOffsetY(dir);
  888. int hpx = newX - hp.xmin;
  889. int hpy = newY - hp.ymin;
  890. if (hpx < 0 || hpx >= hp.width || hpy < 0 || hpy >= hp.height)
  891. continue;
  892. if (hp.data[hpx+hpy*hp.width] != 0)
  893. continue;
  894. hp.data[hpx+hpy*hp.width] = 1;
  895. array.push(newX);
  896. array.push(newY);
  897. array.push((int)chf.cells[(newX+bs)+(newY+bs)*chf.width].index + rcGetCon(cs, dir));
  898. }
  899. rcSwap(dirs[directDir], dirs[3]);
  900. }
  901. array.clear();
  902. // getHeightData seeds are given in coordinates with borders
  903. array.push(cx+bs);
  904. array.push(cy+bs);
  905. array.push(ci);
  906. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  907. const rcCompactSpan& cs = chf.spans[ci];
  908. hp.data[cx-hp.xmin+(cy-hp.ymin)*hp.width] = cs.y;
  909. }
  910. static void push3(rcIntArray& queue, int v1, int v2, int v3)
  911. {
  912. queue.resize(queue.size() + 3);
  913. queue[queue.size() - 3] = v1;
  914. queue[queue.size() - 2] = v2;
  915. queue[queue.size() - 1] = v3;
  916. }
  917. static void getHeightData(rcContext* ctx, const rcCompactHeightfield& chf,
  918. const unsigned short* poly, const int npoly,
  919. const unsigned short* verts, const int bs,
  920. rcHeightPatch& hp, rcIntArray& queue,
  921. int region)
  922. {
  923. // Note: Reads to the compact heightfield are offset by border size (bs)
  924. // since border size offset is already removed from the polymesh vertices.
  925. queue.clear();
  926. // Set all heights to RC_UNSET_HEIGHT.
  927. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  928. bool empty = true;
  929. // We cannot sample from this poly if it was created from polys
  930. // of different regions. If it was then it could potentially be overlapping
  931. // with polys of that region and the heights sampled here could be wrong.
  932. if (region != RC_MULTIPLE_REGS)
  933. {
  934. // Copy the height from the same region, and mark region borders
  935. // as seed points to fill the rest.
  936. for (int hy = 0; hy < hp.height; hy++)
  937. {
  938. int y = hp.ymin + hy + bs;
  939. for (int hx = 0; hx < hp.width; hx++)
  940. {
  941. int x = hp.xmin + hx + bs;
  942. const rcCompactCell& c = chf.cells[x + y*chf.width];
  943. for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
  944. {
  945. const rcCompactSpan& s = chf.spans[i];
  946. if (s.reg == region)
  947. {
  948. // Store height
  949. hp.data[hx + hy*hp.width] = s.y;
  950. empty = false;
  951. // If any of the neighbours is not in same region,
  952. // add the current location as flood fill start
  953. bool border = false;
  954. for (int dir = 0; dir < 4; ++dir)
  955. {
  956. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  957. {
  958. const int ax = x + rcGetDirOffsetX(dir);
  959. const int ay = y + rcGetDirOffsetY(dir);
  960. const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(s, dir);
  961. const rcCompactSpan& as = chf.spans[ai];
  962. if (as.reg != region)
  963. {
  964. border = true;
  965. break;
  966. }
  967. }
  968. }
  969. if (border)
  970. push3(queue, x, y, i);
  971. break;
  972. }
  973. }
  974. }
  975. }
  976. }
  977. // if the polygon does not contain any points from the current region (rare, but happens)
  978. // or if it could potentially be overlapping polygons of the same region,
  979. // then use the center as the seed point.
  980. if (empty)
  981. seedArrayWithPolyCenter(ctx, chf, poly, npoly, verts, bs, hp, queue);
  982. static const int RETRACT_SIZE = 256;
  983. int head = 0;
  984. // We assume the seed is centered in the polygon, so a BFS to collect
  985. // height data will ensure we do not move onto overlapping polygons and
  986. // sample wrong heights.
  987. while (head*3 < queue.size())
  988. {
  989. int cx = queue[head*3+0];
  990. int cy = queue[head*3+1];
  991. int ci = queue[head*3+2];
  992. head++;
  993. if (head >= RETRACT_SIZE)
  994. {
  995. head = 0;
  996. if (queue.size() > RETRACT_SIZE*3)
  997. memmove(&queue[0], &queue[RETRACT_SIZE*3], sizeof(int)*(queue.size()-RETRACT_SIZE*3));
  998. queue.resize(queue.size()-RETRACT_SIZE*3);
  999. }
  1000. const rcCompactSpan& cs = chf.spans[ci];
  1001. for (int dir = 0; dir < 4; ++dir)
  1002. {
  1003. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;
  1004. const int ax = cx + rcGetDirOffsetX(dir);
  1005. const int ay = cy + rcGetDirOffsetY(dir);
  1006. const int hx = ax - hp.xmin - bs;
  1007. const int hy = ay - hp.ymin - bs;
  1008. if ((unsigned int)hx >= (unsigned int)hp.width || (unsigned int)hy >= (unsigned int)hp.height)
  1009. continue;
  1010. if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT)
  1011. continue;
  1012. const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);
  1013. const rcCompactSpan& as = chf.spans[ai];
  1014. hp.data[hx + hy*hp.width] = as.y;
  1015. push3(queue, ax, ay, ai);
  1016. }
  1017. }
  1018. }
  1019. static unsigned char getEdgeFlags(const float* va, const float* vb,
  1020. const float* vpoly, const int npoly)
  1021. {
  1022. // The flag returned by this function matches dtDetailTriEdgeFlags in Detour.
  1023. // Figure out if edge (va,vb) is part of the polygon boundary.
  1024. static const float thrSqr = rcSqr(0.001f);
  1025. for (int i = 0, j = npoly-1; i < npoly; j=i++)
  1026. {
  1027. if (distancePtSeg2d(va, &vpoly[j*3], &vpoly[i*3]) < thrSqr &&
  1028. distancePtSeg2d(vb, &vpoly[j*3], &vpoly[i*3]) < thrSqr)
  1029. return 1;
  1030. }
  1031. return 0;
  1032. }
  1033. static unsigned char getTriFlags(const float* va, const float* vb, const float* vc,
  1034. const float* vpoly, const int npoly)
  1035. {
  1036. unsigned char flags = 0;
  1037. flags |= getEdgeFlags(va,vb,vpoly,npoly) << 0;
  1038. flags |= getEdgeFlags(vb,vc,vpoly,npoly) << 2;
  1039. flags |= getEdgeFlags(vc,va,vpoly,npoly) << 4;
  1040. return flags;
  1041. }
  1042. /// @par
  1043. ///
  1044. /// See the #rcConfig documentation for more information on the configuration parameters.
  1045. ///
  1046. /// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig
  1047. bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,
  1048. const float sampleDist, const float sampleMaxError,
  1049. rcPolyMeshDetail& dmesh)
  1050. {
  1051. rcAssert(ctx);
  1052. rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESHDETAIL);
  1053. if (mesh.nverts == 0 || mesh.npolys == 0)
  1054. return true;
  1055. const int nvp = mesh.nvp;
  1056. const float cs = mesh.cs;
  1057. const float ch = mesh.ch;
  1058. const float* orig = mesh.bmin;
  1059. const int borderSize = mesh.borderSize;
  1060. const int heightSearchRadius = rcMax(1, (int)ceilf(mesh.maxEdgeError));
  1061. rcIntArray edges(64);
  1062. rcIntArray tris(512);
  1063. rcIntArray arr(512);
  1064. rcIntArray samples(512);
  1065. float verts[256*3];
  1066. rcHeightPatch hp;
  1067. int nPolyVerts = 0;
  1068. int maxhw = 0, maxhh = 0;
  1069. rcScopedDelete<int> bounds((int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP));
  1070. if (!bounds)
  1071. {
  1072. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4);
  1073. return false;
  1074. }
  1075. rcScopedDelete<float> poly((float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP));
  1076. if (!poly)
  1077. {
  1078. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3);
  1079. return false;
  1080. }
  1081. // Find max size for a polygon area.
  1082. for (int i = 0; i < mesh.npolys; ++i)
  1083. {
  1084. const unsigned short* p = &mesh.polys[i*nvp*2];
  1085. int& xmin = bounds[i*4+0];
  1086. int& xmax = bounds[i*4+1];
  1087. int& ymin = bounds[i*4+2];
  1088. int& ymax = bounds[i*4+3];
  1089. xmin = chf.width;
  1090. xmax = 0;
  1091. ymin = chf.height;
  1092. ymax = 0;
  1093. for (int j = 0; j < nvp; ++j)
  1094. {
  1095. if(p[j] == RC_MESH_NULL_IDX) break;
  1096. const unsigned short* v = &mesh.verts[p[j]*3];
  1097. xmin = rcMin(xmin, (int)v[0]);
  1098. xmax = rcMax(xmax, (int)v[0]);
  1099. ymin = rcMin(ymin, (int)v[2]);
  1100. ymax = rcMax(ymax, (int)v[2]);
  1101. nPolyVerts++;
  1102. }
  1103. xmin = rcMax(0,xmin-1);
  1104. xmax = rcMin(chf.width,xmax+1);
  1105. ymin = rcMax(0,ymin-1);
  1106. ymax = rcMin(chf.height,ymax+1);
  1107. if (xmin >= xmax || ymin >= ymax) continue;
  1108. maxhw = rcMax(maxhw, xmax-xmin);
  1109. maxhh = rcMax(maxhh, ymax-ymin);
  1110. }
  1111. hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
  1112. if (!hp.data)
  1113. {
  1114. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);
  1115. return false;
  1116. }
  1117. dmesh.nmeshes = mesh.npolys;
  1118. dmesh.nverts = 0;
  1119. dmesh.ntris = 0;
  1120. dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM);
  1121. if (!dmesh.meshes)
  1122. {
  1123. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4);
  1124. return false;
  1125. }
  1126. int vcap = nPolyVerts+nPolyVerts/2;
  1127. int tcap = vcap*2;
  1128. dmesh.nverts = 0;
  1129. dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1130. if (!dmesh.verts)
  1131. {
  1132. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3);
  1133. return false;
  1134. }
  1135. dmesh.ntris = 0;
  1136. dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1137. if (!dmesh.tris)
  1138. {
  1139. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4);
  1140. return false;
  1141. }
  1142. for (int i = 0; i < mesh.npolys; ++i)
  1143. {
  1144. const unsigned short* p = &mesh.polys[i*nvp*2];
  1145. // Store polygon vertices for processing.
  1146. int npoly = 0;
  1147. for (int j = 0; j < nvp; ++j)
  1148. {
  1149. if(p[j] == RC_MESH_NULL_IDX) break;
  1150. const unsigned short* v = &mesh.verts[p[j]*3];
  1151. poly[j*3+0] = v[0]*cs;
  1152. poly[j*3+1] = v[1]*ch;
  1153. poly[j*3+2] = v[2]*cs;
  1154. npoly++;
  1155. }
  1156. // Get the height data from the area of the polygon.
  1157. hp.xmin = bounds[i*4+0];
  1158. hp.ymin = bounds[i*4+2];
  1159. hp.width = bounds[i*4+1]-bounds[i*4+0];
  1160. hp.height = bounds[i*4+3]-bounds[i*4+2];
  1161. getHeightData(ctx, chf, p, npoly, mesh.verts, borderSize, hp, arr, mesh.regs[i]);
  1162. // Build detail mesh.
  1163. int nverts = 0;
  1164. if (!buildPolyDetail(ctx, poly, npoly,
  1165. sampleDist, sampleMaxError,
  1166. heightSearchRadius, chf, hp,
  1167. verts, nverts, tris,
  1168. edges, samples))
  1169. {
  1170. return false;
  1171. }
  1172. // Move detail verts to world space.
  1173. for (int j = 0; j < nverts; ++j)
  1174. {
  1175. verts[j*3+0] += orig[0];
  1176. verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary?
  1177. verts[j*3+2] += orig[2];
  1178. }
  1179. // Offset poly too, will be used to flag checking.
  1180. for (int j = 0; j < npoly; ++j)
  1181. {
  1182. poly[j*3+0] += orig[0];
  1183. poly[j*3+1] += orig[1];
  1184. poly[j*3+2] += orig[2];
  1185. }
  1186. // Store detail submesh.
  1187. const int ntris = tris.size()/4;
  1188. dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts;
  1189. dmesh.meshes[i*4+1] = (unsigned int)nverts;
  1190. dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris;
  1191. dmesh.meshes[i*4+3] = (unsigned int)ntris;
  1192. // Store vertices, allocate more memory if necessary.
  1193. if (dmesh.nverts+nverts > vcap)
  1194. {
  1195. while (dmesh.nverts+nverts > vcap)
  1196. vcap += 256;
  1197. float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1198. if (!newv)
  1199. {
  1200. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3);
  1201. return false;
  1202. }
  1203. if (dmesh.nverts)
  1204. memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts);
  1205. rcFree(dmesh.verts);
  1206. dmesh.verts = newv;
  1207. }
  1208. for (int j = 0; j < nverts; ++j)
  1209. {
  1210. dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0];
  1211. dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1];
  1212. dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2];
  1213. dmesh.nverts++;
  1214. }
  1215. // Store triangles, allocate more memory if necessary.
  1216. if (dmesh.ntris+ntris > tcap)
  1217. {
  1218. while (dmesh.ntris+ntris > tcap)
  1219. tcap += 256;
  1220. unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1221. if (!newt)
  1222. {
  1223. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4);
  1224. return false;
  1225. }
  1226. if (dmesh.ntris)
  1227. memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris);
  1228. rcFree(dmesh.tris);
  1229. dmesh.tris = newt;
  1230. }
  1231. for (int j = 0; j < ntris; ++j)
  1232. {
  1233. const int* t = &tris[j*4];
  1234. dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0];
  1235. dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1];
  1236. dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2];
  1237. dmesh.tris[dmesh.ntris*4+3] = getTriFlags(&verts[t[0]*3], &verts[t[1]*3], &verts[t[2]*3], poly, npoly);
  1238. dmesh.ntris++;
  1239. }
  1240. }
  1241. return true;
  1242. }
  1243. /// @see rcAllocPolyMeshDetail, rcPolyMeshDetail
  1244. bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)
  1245. {
  1246. rcAssert(ctx);
  1247. rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESHDETAIL);
  1248. int maxVerts = 0;
  1249. int maxTris = 0;
  1250. int maxMeshes = 0;
  1251. for (int i = 0; i < nmeshes; ++i)
  1252. {
  1253. if (!meshes[i]) continue;
  1254. maxVerts += meshes[i]->nverts;
  1255. maxTris += meshes[i]->ntris;
  1256. maxMeshes += meshes[i]->nmeshes;
  1257. }
  1258. mesh.nmeshes = 0;
  1259. mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);
  1260. if (!mesh.meshes)
  1261. {
  1262. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4);
  1263. return false;
  1264. }
  1265. mesh.ntris = 0;
  1266. mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);
  1267. if (!mesh.tris)
  1268. {
  1269. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4);
  1270. return false;
  1271. }
  1272. mesh.nverts = 0;
  1273. mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);
  1274. if (!mesh.verts)
  1275. {
  1276. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3);
  1277. return false;
  1278. }
  1279. // Merge datas.
  1280. for (int i = 0; i < nmeshes; ++i)
  1281. {
  1282. rcPolyMeshDetail* dm = meshes[i];
  1283. if (!dm) continue;
  1284. for (int j = 0; j < dm->nmeshes; ++j)
  1285. {
  1286. unsigned int* dst = &mesh.meshes[mesh.nmeshes*4];
  1287. unsigned int* src = &dm->meshes[j*4];
  1288. dst[0] = (unsigned int)mesh.nverts+src[0];
  1289. dst[1] = src[1];
  1290. dst[2] = (unsigned int)mesh.ntris+src[2];
  1291. dst[3] = src[3];
  1292. mesh.nmeshes++;
  1293. }
  1294. for (int k = 0; k < dm->nverts; ++k)
  1295. {
  1296. rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]);
  1297. mesh.nverts++;
  1298. }
  1299. for (int k = 0; k < dm->ntris; ++k)
  1300. {
  1301. mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0];
  1302. mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1];
  1303. mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2];
  1304. mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3];
  1305. mesh.ntris++;
  1306. }
  1307. }
  1308. return true;
  1309. }