Path: blob/master/thirdparty/recastnavigation/Recast/Source/RecastMesh.cpp
9913 views
//1// Copyright (c) 2009-2010 Mikko Mononen [email protected]2//3// This software is provided 'as-is', without any express or implied4// warranty. In no event will the authors be held liable for any damages5// arising from the use of this software.6// Permission is granted to anyone to use this software for any purpose,7// including commercial applications, and to alter it and redistribute it8// freely, subject to the following restrictions:9// 1. The origin of this software must not be misrepresented; you must not10// claim that you wrote the original software. If you use this software11// in a product, an acknowledgment in the product documentation would be12// appreciated but is not required.13// 2. Altered source versions must be plainly marked as such, and must not be14// misrepresented as being the original software.15// 3. This notice may not be removed or altered from any source distribution.16//1718#include <math.h>19#include <string.h>20#include <stdio.h>21#include "Recast.h"22#include "RecastAlloc.h"23#include "RecastAssert.h"2425struct rcEdge26{27unsigned short vert[2];28unsigned short polyEdge[2];29unsigned short poly[2];30};3132static bool buildMeshAdjacency(unsigned short* polys, const int npolys,33const int nverts, const int vertsPerPoly)34{35// Based on code by Eric Lengyel from:36// https://web.archive.org/web/20080704083314/http://www.terathon.com/code/edges.php3738int maxEdgeCount = npolys*vertsPerPoly;39unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP);40if (!firstEdge)41return false;42unsigned short* nextEdge = firstEdge + nverts;43int edgeCount = 0;4445rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP);46if (!edges)47{48rcFree(firstEdge);49return false;50}5152for (int i = 0; i < nverts; i++)53firstEdge[i] = RC_MESH_NULL_IDX;5455for (int i = 0; i < npolys; ++i)56{57unsigned short* t = &polys[i*vertsPerPoly*2];58for (int j = 0; j < vertsPerPoly; ++j)59{60if (t[j] == RC_MESH_NULL_IDX) break;61unsigned short v0 = t[j];62unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];63if (v0 < v1)64{65rcEdge& edge = edges[edgeCount];66edge.vert[0] = v0;67edge.vert[1] = v1;68edge.poly[0] = (unsigned short)i;69edge.polyEdge[0] = (unsigned short)j;70edge.poly[1] = (unsigned short)i;71edge.polyEdge[1] = 0;72// Insert edge73nextEdge[edgeCount] = firstEdge[v0];74firstEdge[v0] = (unsigned short)edgeCount;75edgeCount++;76}77}78}7980for (int i = 0; i < npolys; ++i)81{82unsigned short* t = &polys[i*vertsPerPoly*2];83for (int j = 0; j < vertsPerPoly; ++j)84{85if (t[j] == RC_MESH_NULL_IDX) break;86unsigned short v0 = t[j];87unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];88if (v0 > v1)89{90for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e])91{92rcEdge& edge = edges[e];93if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])94{95edge.poly[1] = (unsigned short)i;96edge.polyEdge[1] = (unsigned short)j;97break;98}99}100}101}102}103104// Store adjacency105for (int i = 0; i < edgeCount; ++i)106{107const rcEdge& e = edges[i];108if (e.poly[0] != e.poly[1])109{110unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2];111unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2];112p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1];113p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0];114}115}116117rcFree(firstEdge);118rcFree(edges);119120return true;121}122123124static const int VERTEX_BUCKET_COUNT = (1<<12);125126inline int computeVertexHash(int x, int y, int z)127{128const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;129const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes130const unsigned int h3 = 0xcb1ab31f;131unsigned int n = h1 * x + h2 * y + h3 * z;132return (int)(n & (VERTEX_BUCKET_COUNT-1));133}134135static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,136unsigned short* verts, int* firstVert, int* nextVert, int& nv)137{138int bucket = computeVertexHash(x, 0, z);139int i = firstVert[bucket];140141while (i != -1)142{143const unsigned short* v = &verts[i*3];144if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z)145return (unsigned short)i;146i = nextVert[i]; // next147}148149// Could not find, create new.150i = nv; nv++;151unsigned short* v = &verts[i*3];152v[0] = x;153v[1] = y;154v[2] = z;155nextVert[i] = firstVert[bucket];156firstVert[bucket] = i;157158return (unsigned short)i;159}160161// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).162inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }163inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }164165inline int area2(const int* a, const int* b, const int* c)166{167return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);168}169170// Exclusive or: true iff exactly one argument is true.171// The arguments are negated to ensure that they are 0/1172// values. Then the bitwise Xor operator may apply.173// (This idea is due to Michael Baldwin.)174inline bool xorb(bool x, bool y)175{176return !x ^ !y;177}178179// Returns true iff c is strictly to the left of the directed180// line through a to b.181inline bool left(const int* a, const int* b, const int* c)182{183return area2(a, b, c) < 0;184}185186inline bool leftOn(const int* a, const int* b, const int* c)187{188return area2(a, b, c) <= 0;189}190191inline bool collinear(const int* a, const int* b, const int* c)192{193return area2(a, b, c) == 0;194}195196// Returns true iff ab properly intersects cd: they share197// a point interior to both segments. The properness of the198// intersection is ensured by using strict leftness.199static bool intersectProp(const int* a, const int* b, const int* c, const int* d)200{201// Eliminate improper cases.202if (collinear(a,b,c) || collinear(a,b,d) ||203collinear(c,d,a) || collinear(c,d,b))204return false;205206return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));207}208209// Returns T iff (a,b,c) are collinear and point c lies210// on the closed segement ab.211static bool between(const int* a, const int* b, const int* c)212{213if (!collinear(a, b, c))214return false;215// If ab not vertical, check betweenness on x; else on y.216if (a[0] != b[0])217return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));218else219return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));220}221222// Returns true iff segments ab and cd intersect, properly or improperly.223static bool intersect(const int* a, const int* b, const int* c, const int* d)224{225if (intersectProp(a, b, c, d))226return true;227else if (between(a, b, c) || between(a, b, d) ||228between(c, d, a) || between(c, d, b))229return true;230else231return false;232}233234static bool vequal(const int* a, const int* b)235{236return a[0] == b[0] && a[2] == b[2];237}238239// Returns T iff (v_i, v_j) is a proper internal *or* external240// diagonal of P, *ignoring edges incident to v_i and v_j*.241static bool diagonalie(int i, int j, int n, const int* verts, int* indices)242{243const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];244const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];245246// For each edge (k,k+1) of P247for (int k = 0; k < n; k++)248{249int k1 = next(k, n);250// Skip edges incident to i or j251if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))252{253const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];254const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];255256if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))257continue;258259if (intersect(d0, d1, p0, p1))260return false;261}262}263return true;264}265266// Returns true iff the diagonal (i,j) is strictly internal to the267// polygon P in the neighborhood of the i endpoint.268static bool inCone(int i, int j, int n, const int* verts, int* indices)269{270const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];271const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];272const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];273const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];274275// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].276if (leftOn(pin1, pi, pi1))277return left(pi, pj, pin1) && left(pj, pi, pi1);278// Assume (i-1,i,i+1) not collinear.279// else P[i] is reflex.280return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));281}282283// Returns T iff (v_i, v_j) is a proper internal284// diagonal of P.285static bool diagonal(int i, int j, int n, const int* verts, int* indices)286{287return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);288}289290291static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)292{293const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];294const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];295296// For each edge (k,k+1) of P297for (int k = 0; k < n; k++)298{299int k1 = next(k, n);300// Skip edges incident to i or j301if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))302{303const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];304const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];305306if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))307continue;308309if (intersectProp(d0, d1, p0, p1))310return false;311}312}313return true;314}315316static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)317{318const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];319const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];320const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];321const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];322323// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].324if (leftOn(pin1, pi, pi1))325return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);326// Assume (i-1,i,i+1) not collinear.327// else P[i] is reflex.328return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));329}330331static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)332{333return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);334}335336337static int triangulate(int n, const int* verts, int* indices, int* tris)338{339int ntris = 0;340int* dst = tris;341342// The last bit of the index is used to indicate if the vertex can be removed.343for (int i = 0; i < n; i++)344{345int i1 = next(i, n);346int i2 = next(i1, n);347if (diagonal(i, i2, n, verts, indices))348indices[i1] |= 0x80000000;349}350351while (n > 3)352{353int minLen = -1;354int mini = -1;355for (int i = 0; i < n; i++)356{357int i1 = next(i, n);358if (indices[i1] & 0x80000000)359{360const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];361const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4];362363int dx = p2[0] - p0[0];364int dy = p2[2] - p0[2];365int len = dx*dx + dy*dy;366367if (minLen < 0 || len < minLen)368{369minLen = len;370mini = i;371}372}373}374375if (mini == -1)376{377// We might get here because the contour has overlapping segments, like this:378//379// A o-o=====o---o B380// / |C D| \.381// o o o o382// : : : :383// We'll try to recover by loosing up the inCone test a bit so that a diagonal384// like A-B or C-D can be found and we can continue.385minLen = -1;386mini = -1;387for (int i = 0; i < n; i++)388{389int i1 = next(i, n);390int i2 = next(i1, n);391if (diagonalLoose(i, i2, n, verts, indices))392{393const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];394const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];395int dx = p2[0] - p0[0];396int dy = p2[2] - p0[2];397int len = dx*dx + dy*dy;398399if (minLen < 0 || len < minLen)400{401minLen = len;402mini = i;403}404}405}406if (mini == -1)407{408// The contour is messed up. This sometimes happens409// if the contour simplification is too aggressive.410return -ntris;411}412}413414int i = mini;415int i1 = next(i, n);416int i2 = next(i1, n);417418*dst++ = indices[i] & 0x0fffffff;419*dst++ = indices[i1] & 0x0fffffff;420*dst++ = indices[i2] & 0x0fffffff;421ntris++;422423// Removes P[i1] by copying P[i+1]...P[n-1] left one index.424n--;425for (int k = i1; k < n; k++)426indices[k] = indices[k+1];427428if (i1 >= n) i1 = 0;429i = prev(i1,n);430// Update diagonal flags.431if (diagonal(prev(i, n), i1, n, verts, indices))432indices[i] |= 0x80000000;433else434indices[i] &= 0x0fffffff;435436if (diagonal(i, next(i1, n), n, verts, indices))437indices[i1] |= 0x80000000;438else439indices[i1] &= 0x0fffffff;440}441442// Append the remaining triangle.443*dst++ = indices[0] & 0x0fffffff;444*dst++ = indices[1] & 0x0fffffff;445*dst++ = indices[2] & 0x0fffffff;446ntris++;447448return ntris;449}450451static int countPolyVerts(const unsigned short* p, const int nvp)452{453for (int i = 0; i < nvp; ++i)454if (p[i] == RC_MESH_NULL_IDX)455return i;456return nvp;457}458459inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)460{461return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -462((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;463}464465static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,466const unsigned short* verts, int& ea, int& eb,467const int nvp)468{469const int na = countPolyVerts(pa, nvp);470const int nb = countPolyVerts(pb, nvp);471472// If the merged polygon would be too big, do not merge.473if (na+nb-2 > nvp)474return -1;475476// Check if the polygons share an edge.477ea = -1;478eb = -1;479480for (int i = 0; i < na; ++i)481{482unsigned short va0 = pa[i];483unsigned short va1 = pa[(i+1) % na];484if (va0 > va1)485rcSwap(va0, va1);486for (int j = 0; j < nb; ++j)487{488unsigned short vb0 = pb[j];489unsigned short vb1 = pb[(j+1) % nb];490if (vb0 > vb1)491rcSwap(vb0, vb1);492if (va0 == vb0 && va1 == vb1)493{494ea = i;495eb = j;496break;497}498}499}500501// No common edge, cannot merge.502if (ea == -1 || eb == -1)503return -1;504505// Check to see if the merged polygon would be convex.506unsigned short va, vb, vc;507508va = pa[(ea+na-1) % na];509vb = pa[ea];510vc = pb[(eb+2) % nb];511if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))512return -1;513514va = pb[(eb+nb-1) % nb];515vb = pb[eb];516vc = pa[(ea+2) % na];517if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))518return -1;519520va = pa[ea];521vb = pa[(ea+1)%na];522523int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];524int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];525526return dx*dx + dy*dy;527}528529static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,530unsigned short* tmp, const int nvp)531{532const int na = countPolyVerts(pa, nvp);533const int nb = countPolyVerts(pb, nvp);534535// Merge polygons.536memset(tmp, 0xff, sizeof(unsigned short)*nvp);537int n = 0;538// Add pa539for (int i = 0; i < na-1; ++i)540tmp[n++] = pa[(ea+1+i) % na];541// Add pb542for (int i = 0; i < nb-1; ++i)543tmp[n++] = pb[(eb+1+i) % nb];544545memcpy(pa, tmp, sizeof(unsigned short)*nvp);546}547548549static void pushFront(int v, int* arr, int& an)550{551an++;552for (int i = an-1; i > 0; --i) arr[i] = arr[i-1];553arr[0] = v;554}555556static void pushBack(int v, int* arr, int& an)557{558arr[an] = v;559an++;560}561562static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem)563{564const int nvp = mesh.nvp;565566// Count number of polygons to remove.567int numTouchedVerts = 0;568int numRemainingEdges = 0;569for (int i = 0; i < mesh.npolys; ++i)570{571unsigned short* p = &mesh.polys[i*nvp*2];572const int nv = countPolyVerts(p, nvp);573int numRemoved = 0;574int numVerts = 0;575for (int j = 0; j < nv; ++j)576{577if (p[j] == rem)578{579numTouchedVerts++;580numRemoved++;581}582numVerts++;583}584if (numRemoved)585{586numRemainingEdges += numVerts-(numRemoved+1);587}588}589590// There would be too few edges remaining to create a polygon.591// This can happen for example when a tip of a triangle is marked592// as deletion, but there are no other polys that share the vertex.593// In this case, the vertex should not be removed.594if (numRemainingEdges <= 2)595return false;596597// Find edges which share the removed vertex.598const int maxEdges = numTouchedVerts*2;599int nedges = 0;600rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));601if (!edges)602{603ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);604return false;605}606607for (int i = 0; i < mesh.npolys; ++i)608{609unsigned short* p = &mesh.polys[i*nvp*2];610const int nv = countPolyVerts(p, nvp);611612// Collect edges which touches the removed vertex.613for (int j = 0, k = nv-1; j < nv; k = j++)614{615if (p[j] == rem || p[k] == rem)616{617// Arrange edge so that a=rem.618int a = p[j], b = p[k];619if (b == rem)620rcSwap(a,b);621622// Check if the edge exists623bool exists = false;624for (int m = 0; m < nedges; ++m)625{626int* e = &edges[m*3];627if (e[1] == b)628{629// Exists, increment vertex share count.630e[2]++;631exists = true;632}633}634// Add new edge.635if (!exists)636{637int* e = &edges[nedges*3];638e[0] = a;639e[1] = b;640e[2] = 1;641nedges++;642}643}644}645}646647// There should be no more than 2 open edges.648// This catches the case that two non-adjacent polygons649// share the removed vertex. In that case, do not remove the vertex.650int numOpenEdges = 0;651for (int i = 0; i < nedges; ++i)652{653if (edges[i*3+2] < 2)654numOpenEdges++;655}656if (numOpenEdges > 2)657return false;658659return true;660}661662static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris)663{664const int nvp = mesh.nvp;665666// Count number of polygons to remove.667int numRemovedVerts = 0;668for (int i = 0; i < mesh.npolys; ++i)669{670unsigned short* p = &mesh.polys[i*nvp*2];671const int nv = countPolyVerts(p, nvp);672for (int j = 0; j < nv; ++j)673{674if (p[j] == rem)675numRemovedVerts++;676}677}678679int nedges = 0;680rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));681if (!edges)682{683ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);684return false;685}686687int nhole = 0;688rcScopedDelete<int> hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));689if (!hole)690{691ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);692return false;693}694695int nhreg = 0;696rcScopedDelete<int> hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));697if (!hreg)698{699ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);700return false;701}702703int nharea = 0;704rcScopedDelete<int> harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));705if (!harea)706{707ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);708return false;709}710711for (int i = 0; i < mesh.npolys; ++i)712{713unsigned short* p = &mesh.polys[i*nvp*2];714const int nv = countPolyVerts(p, nvp);715bool hasRem = false;716for (int j = 0; j < nv; ++j)717if (p[j] == rem) hasRem = true;718if (hasRem)719{720// Collect edges which does not touch the removed vertex.721for (int j = 0, k = nv-1; j < nv; k = j++)722{723if (p[j] != rem && p[k] != rem)724{725int* e = &edges[nedges*4];726e[0] = p[k];727e[1] = p[j];728e[2] = mesh.regs[i];729e[3] = mesh.areas[i];730nedges++;731}732}733// Remove the polygon.734unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];735if (p != p2)736memcpy(p,p2,sizeof(unsigned short)*nvp);737memset(p+nvp,0xff,sizeof(unsigned short)*nvp);738mesh.regs[i] = mesh.regs[mesh.npolys-1];739mesh.areas[i] = mesh.areas[mesh.npolys-1];740mesh.npolys--;741--i;742}743}744745// Remove vertex.746for (int i = (int)rem; i < mesh.nverts - 1; ++i)747{748mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];749mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];750mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];751}752mesh.nverts--;753754// Adjust indices to match the removed vertex layout.755for (int i = 0; i < mesh.npolys; ++i)756{757unsigned short* p = &mesh.polys[i*nvp*2];758const int nv = countPolyVerts(p, nvp);759for (int j = 0; j < nv; ++j)760if (p[j] > rem) p[j]--;761}762for (int i = 0; i < nedges; ++i)763{764if (edges[i*4+0] > rem) edges[i*4+0]--;765if (edges[i*4+1] > rem) edges[i*4+1]--;766}767768if (nedges == 0)769return true;770771// Start with one vertex, keep appending connected772// segments to the start and end of the hole.773pushBack(edges[0], hole, nhole);774pushBack(edges[2], hreg, nhreg);775pushBack(edges[3], harea, nharea);776777while (nedges)778{779bool match = false;780781for (int i = 0; i < nedges; ++i)782{783const int ea = edges[i*4+0];784const int eb = edges[i*4+1];785const int r = edges[i*4+2];786const int a = edges[i*4+3];787bool add = false;788if (hole[0] == eb)789{790// The segment matches the beginning of the hole boundary.791pushFront(ea, hole, nhole);792pushFront(r, hreg, nhreg);793pushFront(a, harea, nharea);794add = true;795}796else if (hole[nhole-1] == ea)797{798// The segment matches the end of the hole boundary.799pushBack(eb, hole, nhole);800pushBack(r, hreg, nhreg);801pushBack(a, harea, nharea);802add = true;803}804if (add)805{806// The edge segment was added, remove it.807edges[i*4+0] = edges[(nedges-1)*4+0];808edges[i*4+1] = edges[(nedges-1)*4+1];809edges[i*4+2] = edges[(nedges-1)*4+2];810edges[i*4+3] = edges[(nedges-1)*4+3];811--nedges;812match = true;813--i;814}815}816817if (!match)818break;819}820821rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));822if (!tris)823{824ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);825return false;826}827828rcScopedDelete<int> tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));829if (!tverts)830{831ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);832return false;833}834835rcScopedDelete<int> thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));836if (!thole)837{838ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);839return false;840}841842// Generate temp vertex array for triangulation.843for (int i = 0; i < nhole; ++i)844{845const int pi = hole[i];846tverts[i*4+0] = mesh.verts[pi*3+0];847tverts[i*4+1] = mesh.verts[pi*3+1];848tverts[i*4+2] = mesh.verts[pi*3+2];849tverts[i*4+3] = 0;850thole[i] = i;851}852853// Triangulate the hole.854int ntris = triangulate(nhole, &tverts[0], &thole[0], tris);855if (ntris < 0)856{857ntris = -ntris;858ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results.");859}860861// Merge the hole triangles back to polygons.862rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));863if (!polys)864{865ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);866return false;867}868rcScopedDelete<unsigned short> pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));869if (!pregs)870{871ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);872return false;873}874rcScopedDelete<unsigned char> pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));875if (!pareas)876{877ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);878return false;879}880881unsigned short* tmpPoly = &polys[ntris*nvp];882883// Build initial polygons.884int npolys = 0;885memset(polys, 0xff, ntris*nvp*sizeof(unsigned short));886for (int j = 0; j < ntris; ++j)887{888int* t = &tris[j*3];889if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])890{891polys[npolys*nvp+0] = (unsigned short)hole[t[0]];892polys[npolys*nvp+1] = (unsigned short)hole[t[1]];893polys[npolys*nvp+2] = (unsigned short)hole[t[2]];894895// If this polygon covers multiple region types then896// mark it as such897if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])898pregs[npolys] = RC_MULTIPLE_REGS;899else900pregs[npolys] = (unsigned short)hreg[t[0]];901902pareas[npolys] = (unsigned char)harea[t[0]];903npolys++;904}905}906if (!npolys)907return true;908909// Merge polygons.910if (nvp > 3)911{912for (;;)913{914// Find best polygons to merge.915int bestMergeVal = 0;916int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;917918for (int j = 0; j < npolys-1; ++j)919{920unsigned short* pj = &polys[j*nvp];921for (int k = j+1; k < npolys; ++k)922{923unsigned short* pk = &polys[k*nvp];924int ea, eb;925int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);926if (v > bestMergeVal)927{928bestMergeVal = v;929bestPa = j;930bestPb = k;931bestEa = ea;932bestEb = eb;933}934}935}936937if (bestMergeVal > 0)938{939// Found best, merge.940unsigned short* pa = &polys[bestPa*nvp];941unsigned short* pb = &polys[bestPb*nvp];942mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);943if (pregs[bestPa] != pregs[bestPb])944pregs[bestPa] = RC_MULTIPLE_REGS;945946unsigned short* last = &polys[(npolys-1)*nvp];947if (pb != last)948memcpy(pb, last, sizeof(unsigned short)*nvp);949pregs[bestPb] = pregs[npolys-1];950pareas[bestPb] = pareas[npolys-1];951npolys--;952}953else954{955// Could not merge any polygons, stop.956break;957}958}959}960961// Store polygons.962for (int i = 0; i < npolys; ++i)963{964if (mesh.npolys >= maxTris) break;965unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];966memset(p,0xff,sizeof(unsigned short)*nvp*2);967for (int j = 0; j < nvp; ++j)968p[j] = polys[i*nvp+j];969mesh.regs[mesh.npolys] = pregs[i];970mesh.areas[mesh.npolys] = pareas[i];971mesh.npolys++;972if (mesh.npolys > maxTris)973{974ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris);975return false;976}977}978979return true;980}981982/// @par983///984/// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper985/// limit must be retricted to <= #DT_VERTS_PER_POLYGON.986///987/// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig988bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh)989{990rcAssert(ctx);991992rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);993994rcVcopy(mesh.bmin, cset.bmin);995rcVcopy(mesh.bmax, cset.bmax);996mesh.cs = cset.cs;997mesh.ch = cset.ch;998mesh.borderSize = cset.borderSize;999mesh.maxEdgeError = cset.maxError;10001001int maxVertices = 0;1002int maxTris = 0;1003int maxVertsPerCont = 0;1004for (int i = 0; i < cset.nconts; ++i)1005{1006// Skip null contours.1007if (cset.conts[i].nverts < 3) continue;1008maxVertices += cset.conts[i].nverts;1009maxTris += cset.conts[i].nverts - 2;1010maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts);1011}10121013if (maxVertices >= 0xfffe)1014{1015ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices);1016return false;1017}10181019rcScopedDelete<unsigned char> vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));1020if (!vflags)1021{1022ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);1023return false;1024}1025memset(vflags, 0, maxVertices);10261027mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM);1028if (!mesh.verts)1029{1030ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);1031return false;1032}1033mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM);1034if (!mesh.polys)1035{1036ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2);1037return false;1038}1039mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM);1040if (!mesh.regs)1041{1042ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris);1043return false;1044}1045mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM);1046if (!mesh.areas)1047{1048ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris);1049return false;1050}10511052mesh.nverts = 0;1053mesh.npolys = 0;1054mesh.nvp = nvp;1055mesh.maxpolys = maxTris;10561057memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);1058memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2);1059memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);1060memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);10611062rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));1063if (!nextVert)1064{1065ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);1066return false;1067}1068memset(nextVert, 0, sizeof(int)*maxVertices);10691070rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));1071if (!firstVert)1072{1073ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);1074return false;1075}1076for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)1077firstVert[i] = -1;10781079rcScopedDelete<int> indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));1080if (!indices)1081{1082ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);1083return false;1084}1085rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));1086if (!tris)1087{1088ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);1089return false;1090}1091rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));1092if (!polys)1093{1094ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);1095return false;1096}1097unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp];10981099for (int i = 0; i < cset.nconts; ++i)1100{1101rcContour& cont = cset.conts[i];11021103// Skip null contours.1104if (cont.nverts < 3)1105continue;11061107// Triangulate contour1108for (int j = 0; j < cont.nverts; ++j)1109indices[j] = j;11101111int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);1112if (ntris <= 0)1113{1114// Bad triangulation, should not happen.1115/* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]);1116printf("\tconst float cs = %ff;\n", cset.cs);1117printf("\tconst float ch = %ff;\n", cset.ch);1118printf("\tconst int verts[] = {\n");1119for (int k = 0; k < cont.nverts; ++k)1120{1121const int* v = &cont.verts[k*4];1122printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]);1123}1124printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/1125ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i);1126ntris = -ntris;1127}11281129// Add and merge vertices.1130for (int j = 0; j < cont.nverts; ++j)1131{1132const int* v = &cont.verts[j*4];1133indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],1134mesh.verts, firstVert, nextVert, mesh.nverts);1135if (v[3] & RC_BORDER_VERTEX)1136{1137// This vertex should be removed.1138vflags[indices[j]] = 1;1139}1140}11411142// Build initial polygons.1143int npolys = 0;1144memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));1145for (int j = 0; j < ntris; ++j)1146{1147int* t = &tris[j*3];1148if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])1149{1150polys[npolys*nvp+0] = (unsigned short)indices[t[0]];1151polys[npolys*nvp+1] = (unsigned short)indices[t[1]];1152polys[npolys*nvp+2] = (unsigned short)indices[t[2]];1153npolys++;1154}1155}1156if (!npolys)1157continue;11581159// Merge polygons.1160if (nvp > 3)1161{1162for(;;)1163{1164// Find best polygons to merge.1165int bestMergeVal = 0;1166int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;11671168for (int j = 0; j < npolys-1; ++j)1169{1170unsigned short* pj = &polys[j*nvp];1171for (int k = j+1; k < npolys; ++k)1172{1173unsigned short* pk = &polys[k*nvp];1174int ea, eb;1175int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);1176if (v > bestMergeVal)1177{1178bestMergeVal = v;1179bestPa = j;1180bestPb = k;1181bestEa = ea;1182bestEb = eb;1183}1184}1185}11861187if (bestMergeVal > 0)1188{1189// Found best, merge.1190unsigned short* pa = &polys[bestPa*nvp];1191unsigned short* pb = &polys[bestPb*nvp];1192mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);1193unsigned short* lastPoly = &polys[(npolys-1)*nvp];1194if (pb != lastPoly)1195memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);1196npolys--;1197}1198else1199{1200// Could not merge any polygons, stop.1201break;1202}1203}1204}12051206// Store polygons.1207for (int j = 0; j < npolys; ++j)1208{1209unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];1210unsigned short* q = &polys[j*nvp];1211for (int k = 0; k < nvp; ++k)1212p[k] = q[k];1213mesh.regs[mesh.npolys] = cont.reg;1214mesh.areas[mesh.npolys] = cont.area;1215mesh.npolys++;1216if (mesh.npolys > maxTris)1217{1218ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris);1219return false;1220}1221}1222}122312241225// Remove edge vertices.1226for (int i = 0; i < mesh.nverts; ++i)1227{1228if (vflags[i])1229{1230if (!canRemoveVertex(ctx, mesh, (unsigned short)i))1231continue;1232if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris))1233{1234// Failed to remove vertex1235ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i);1236return false;1237}1238// Remove vertex1239// Note: mesh.nverts is already decremented inside removeVertex()!1240// Fixup vertex flags1241for (int j = i; j < mesh.nverts; ++j)1242vflags[j] = vflags[j+1];1243--i;1244}1245}12461247// Calculate adjacency.1248if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp))1249{1250ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed.");1251return false;1252}12531254// Find portal edges1255if (mesh.borderSize > 0)1256{1257const int w = cset.width;1258const int h = cset.height;1259for (int i = 0; i < mesh.npolys; ++i)1260{1261unsigned short* p = &mesh.polys[i*2*nvp];1262for (int j = 0; j < nvp; ++j)1263{1264if (p[j] == RC_MESH_NULL_IDX) break;1265// Skip connected edges.1266if (p[nvp+j] != RC_MESH_NULL_IDX)1267continue;1268int nj = j+1;1269if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0;1270const unsigned short* va = &mesh.verts[p[j]*3];1271const unsigned short* vb = &mesh.verts[p[nj]*3];12721273if ((int)va[0] == 0 && (int)vb[0] == 0)1274p[nvp+j] = 0x8000 | 0;1275else if ((int)va[2] == h && (int)vb[2] == h)1276p[nvp+j] = 0x8000 | 1;1277else if ((int)va[0] == w && (int)vb[0] == w)1278p[nvp+j] = 0x8000 | 2;1279else if ((int)va[2] == 0 && (int)vb[2] == 0)1280p[nvp+j] = 0x8000 | 3;1281}1282}1283}12841285// Just allocate the mesh flags array. The user is resposible to fill it.1286mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM);1287if (!mesh.flags)1288{1289ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys);1290return false;1291}1292memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys);12931294if (mesh.nverts > 0xffff)1295{1296ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);1297}1298if (mesh.npolys > 0xffff)1299{1300ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);1301}13021303return true;1304}13051306/// @see rcAllocPolyMesh, rcPolyMesh1307bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh)1308{1309rcAssert(ctx);13101311if (!nmeshes || !meshes)1312return true;13131314rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);13151316mesh.nvp = meshes[0]->nvp;1317mesh.cs = meshes[0]->cs;1318mesh.ch = meshes[0]->ch;1319rcVcopy(mesh.bmin, meshes[0]->bmin);1320rcVcopy(mesh.bmax, meshes[0]->bmax);13211322int maxVerts = 0;1323int maxPolys = 0;1324int maxVertsPerMesh = 0;1325for (int i = 0; i < nmeshes; ++i)1326{1327rcVmin(mesh.bmin, meshes[i]->bmin);1328rcVmax(mesh.bmax, meshes[i]->bmax);1329maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts);1330maxVerts += meshes[i]->nverts;1331maxPolys += meshes[i]->npolys;1332}13331334mesh.nverts = 0;1335mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM);1336if (!mesh.verts)1337{1338ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3);1339return false;1340}13411342mesh.npolys = 0;1343mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM);1344if (!mesh.polys)1345{1346ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp);1347return false;1348}1349memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp);13501351mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);1352if (!mesh.regs)1353{1354ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys);1355return false;1356}1357memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys);13581359mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM);1360if (!mesh.areas)1361{1362ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys);1363return false;1364}1365memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys);13661367mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);1368if (!mesh.flags)1369{1370ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys);1371return false;1372}1373memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);13741375rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));1376if (!nextVert)1377{1378ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);1379return false;1380}1381memset(nextVert, 0, sizeof(int)*maxVerts);13821383rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));1384if (!firstVert)1385{1386ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);1387return false;1388}1389for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)1390firstVert[i] = -1;13911392rcScopedDelete<unsigned short> vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));1393if (!vremap)1394{1395ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);1396return false;1397}1398memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);13991400for (int i = 0; i < nmeshes; ++i)1401{1402const rcPolyMesh* pmesh = meshes[i];14031404const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);1405const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);14061407bool isMinX = (ox == 0);1408bool isMinZ = (oz == 0);1409bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;1410bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;1411bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);14121413for (int j = 0; j < pmesh->nverts; ++j)1414{1415unsigned short* v = &pmesh->verts[j*3];1416vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz,1417mesh.verts, firstVert, nextVert, mesh.nverts);1418}14191420for (int j = 0; j < pmesh->npolys; ++j)1421{1422unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp];1423unsigned short* src = &pmesh->polys[j*2*mesh.nvp];1424mesh.regs[mesh.npolys] = pmesh->regs[j];1425mesh.areas[mesh.npolys] = pmesh->areas[j];1426mesh.flags[mesh.npolys] = pmesh->flags[j];1427mesh.npolys++;1428for (int k = 0; k < mesh.nvp; ++k)1429{1430if (src[k] == RC_MESH_NULL_IDX) break;1431tgt[k] = vremap[src[k]];1432}14331434if (isOnBorder)1435{1436for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)1437{1438if (src[k] & 0x8000 && src[k] != 0xffff)1439{1440unsigned short dir = src[k] & 0xf;1441switch (dir)1442{1443case 0: // Portal x-1444if (isMinX)1445tgt[k] = src[k];1446break;1447case 1: // Portal z+1448if (isMaxZ)1449tgt[k] = src[k];1450break;1451case 2: // Portal x+1452if (isMaxX)1453tgt[k] = src[k];1454break;1455case 3: // Portal z-1456if (isMinZ)1457tgt[k] = src[k];1458break;1459}1460}1461}1462}1463}1464}14651466// Calculate adjacency.1467if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp))1468{1469ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed.");1470return false;1471}14721473if (mesh.nverts > 0xffff)1474{1475ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);1476}1477if (mesh.npolys > 0xffff)1478{1479ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);1480}14811482return true;1483}14841485bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)1486{1487rcAssert(ctx);14881489// Destination must be empty.1490rcAssert(dst.verts == 0);1491rcAssert(dst.polys == 0);1492rcAssert(dst.regs == 0);1493rcAssert(dst.areas == 0);1494rcAssert(dst.flags == 0);14951496dst.nverts = src.nverts;1497dst.npolys = src.npolys;1498dst.maxpolys = src.npolys;1499dst.nvp = src.nvp;1500rcVcopy(dst.bmin, src.bmin);1501rcVcopy(dst.bmax, src.bmax);1502dst.cs = src.cs;1503dst.ch = src.ch;1504dst.borderSize = src.borderSize;1505dst.maxEdgeError = src.maxEdgeError;15061507dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);1508if (!dst.verts)1509{1510ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);1511return false;1512}1513memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);15141515dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);1516if (!dst.polys)1517{1518ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);1519return false;1520}1521memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);15221523dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);1524if (!dst.regs)1525{1526ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);1527return false;1528}1529memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);15301531dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);1532if (!dst.areas)1533{1534ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);1535return false;1536}1537memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);15381539dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);1540if (!dst.flags)1541{1542ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);1543return false;1544}1545memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);15461547return true;1548}154915501551