Debian Codegraph @

Recast/Source/RecastMesh.cpp

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