Path: blob/master/thirdparty/recastnavigation/Recast/Source/RecastMeshDetail.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 <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"262728static const unsigned RC_UNSET_HEIGHT = 0xffff;2930struct rcHeightPatch31{32inline rcHeightPatch() : data(0), xmin(0), ymin(0), width(0), height(0) {}33inline ~rcHeightPatch() { rcFree(data); }34unsigned short* data;35int xmin, ymin, width, height;36};373839inline float vdot2(const float* a, const float* b)40{41return a[0]*b[0] + a[2]*b[2];42}4344inline float vdistSq2(const float* p, const float* q)45{46const float dx = q[0] - p[0];47const float dy = q[2] - p[2];48return dx*dx + dy*dy;49}5051inline float vdist2(const float* p, const float* q)52{53return sqrtf(vdistSq2(p,q));54}5556inline float vcross2(const float* p1, const float* p2, const float* p3)57{58const float u1 = p2[0] - p1[0];59const float v1 = p2[2] - p1[2];60const float u2 = p3[0] - p1[0];61const float v2 = p3[2] - p1[2];62return u1 * v2 - v1 * u2;63}6465static bool circumCircle(const float* p1, const float* p2, const float* p3,66float* c, float& r)67{68static const float EPS = 1e-6f;69// Calculate the circle relative to p1, to avoid some precision issues.70const float v1[3] = {0,0,0};71float v2[3], v3[3];72rcVsub(v2, p2,p1);73rcVsub(v3, p3,p1);7475const float cp = vcross2(v1, v2, v3);76if (fabsf(cp) > EPS)77{78const float v1Sq = vdot2(v1,v1);79const float v2Sq = vdot2(v2,v2);80const float v3Sq = vdot2(v3,v3);81c[0] = (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp);82c[1] = 0;83c[2] = (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp);84r = vdist2(c, v1);85rcVadd(c, c, p1);86return true;87}8889rcVcopy(c, p1);90r = 0;91return false;92}9394static float distPtTri(const float* p, const float* a, const float* b, const float* c)95{96float v0[3], v1[3], v2[3];97rcVsub(v0, c,a);98rcVsub(v1, b,a);99rcVsub(v2, p,a);100101const float dot00 = vdot2(v0, v0);102const float dot01 = vdot2(v0, v1);103const float dot02 = vdot2(v0, v2);104const float dot11 = vdot2(v1, v1);105const float dot12 = vdot2(v1, v2);106107// Compute barycentric coordinates108const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);109const float u = (dot11 * dot02 - dot01 * dot12) * invDenom;110float v = (dot00 * dot12 - dot01 * dot02) * invDenom;111112// If point lies inside the triangle, return interpolated y-coord.113static const float EPS = 1e-4f;114if (u >= -EPS && v >= -EPS && (u+v) <= 1+EPS)115{116const float y = a[1] + v0[1]*u + v1[1]*v;117return fabsf(y-p[1]);118}119return FLT_MAX;120}121122static float distancePtSeg(const float* pt, const float* p, const float* q)123{124float pqx = q[0] - p[0];125float pqy = q[1] - p[1];126float pqz = q[2] - p[2];127float dx = pt[0] - p[0];128float dy = pt[1] - p[1];129float dz = pt[2] - p[2];130float d = pqx*pqx + pqy*pqy + pqz*pqz;131float t = pqx*dx + pqy*dy + pqz*dz;132if (d > 0)133t /= d;134if (t < 0)135t = 0;136else if (t > 1)137t = 1;138139dx = p[0] + t*pqx - pt[0];140dy = p[1] + t*pqy - pt[1];141dz = p[2] + t*pqz - pt[2];142143return dx*dx + dy*dy + dz*dz;144}145146static float distancePtSeg2d(const float* pt, const float* p, const float* q)147{148float pqx = q[0] - p[0];149float pqz = q[2] - p[2];150float dx = pt[0] - p[0];151float dz = pt[2] - p[2];152float d = pqx*pqx + pqz*pqz;153float t = pqx*dx + pqz*dz;154if (d > 0)155t /= d;156if (t < 0)157t = 0;158else if (t > 1)159t = 1;160161dx = p[0] + t*pqx - pt[0];162dz = p[2] + t*pqz - pt[2];163164return dx*dx + dz*dz;165}166167static float distToTriMesh(const float* p, const float* verts, const int /*nverts*/, const int* tris, const int ntris)168{169float dmin = FLT_MAX;170for (int i = 0; i < ntris; ++i)171{172const float* va = &verts[tris[i*4+0]*3];173const float* vb = &verts[tris[i*4+1]*3];174const float* vc = &verts[tris[i*4+2]*3];175float d = distPtTri(p, va,vb,vc);176if (d < dmin)177dmin = d;178}179if (dmin == FLT_MAX) return -1;180return dmin;181}182183static float distToPoly(int nvert, const float* verts, const float* p)184{185186float dmin = FLT_MAX;187int i, j, c = 0;188for (i = 0, j = nvert-1; i < nvert; j = i++)189{190const float* vi = &verts[i*3];191const float* vj = &verts[j*3];192if (((vi[2] > p[2]) != (vj[2] > p[2])) &&193(p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )194c = !c;195dmin = rcMin(dmin, distancePtSeg2d(p, vj, vi));196}197return c ? -dmin : dmin;198}199200201static unsigned short getHeight(const float fx, const float fy, const float fz,202const float /*cs*/, const float ics, const float ch,203const int radius, const rcHeightPatch& hp)204{205int ix = (int)floorf(fx*ics + 0.01f);206int iz = (int)floorf(fz*ics + 0.01f);207ix = rcClamp(ix-hp.xmin, 0, hp.width - 1);208iz = rcClamp(iz-hp.ymin, 0, hp.height - 1);209unsigned short h = hp.data[ix+iz*hp.width];210if (h == RC_UNSET_HEIGHT)211{212// Special case when data might be bad.213// Walk adjacent cells in a spiral up to 'radius', and look214// for a pixel which has a valid height.215int x = 1, z = 0, dx = 1, dz = 0;216int maxSize = radius * 2 + 1;217int maxIter = maxSize * maxSize - 1;218219int nextRingIterStart = 8;220int nextRingIters = 16;221222float dmin = FLT_MAX;223for (int i = 0; i < maxIter; i++)224{225const int nx = ix + x;226const int nz = iz + z;227228if (nx >= 0 && nz >= 0 && nx < hp.width && nz < hp.height)229{230const unsigned short nh = hp.data[nx + nz*hp.width];231if (nh != RC_UNSET_HEIGHT)232{233const float d = fabsf(nh*ch - fy);234if (d < dmin)235{236h = nh;237dmin = d;238}239}240}241242// We are searching in a grid which looks approximately like this:243// __________244// |2 ______ 2|245// | |1 __ 1| |246// | | |__| | |247// | |______| |248// |__________|249// We want to find the best height as close to the center cell as possible. This means that250// if we find a height in one of the neighbor cells to the center, we don't want to251// expand further out than the 8 neighbors - we want to limit our search to the closest252// of these "rings", but the best height in the ring.253// For example, the center is just 1 cell. We checked that at the entrance to the function.254// The next "ring" contains 8 cells (marked 1 above). Those are all the neighbors to the center cell.255// The next one again contains 16 cells (marked 2). In general each ring has 8 additional cells, which256// can be thought of as adding 2 cells around the "center" of each side when we expand the ring.257// Here we detect if we are about to enter the next ring, and if we are and we have found258// a height, we abort the search.259if (i + 1 == nextRingIterStart)260{261if (h != RC_UNSET_HEIGHT)262break;263264nextRingIterStart += nextRingIters;265nextRingIters += 8;266}267268if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z)))269{270int tmp = dx;271dx = -dz;272dz = tmp;273}274x += dx;275z += dz;276}277}278return h;279}280281282enum EdgeValues283{284EV_UNDEF = -1,285EV_HULL = -2286};287288static int findEdge(const int* edges, int nedges, int s, int t)289{290for (int i = 0; i < nedges; i++)291{292const int* e = &edges[i*4];293if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s))294return i;295}296return EV_UNDEF;297}298299static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r)300{301if (nedges >= maxEdges)302{303ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges);304return EV_UNDEF;305}306307// Add edge if not already in the triangulation.308int e = findEdge(edges, nedges, s, t);309if (e == EV_UNDEF)310{311int* edge = &edges[nedges*4];312edge[0] = s;313edge[1] = t;314edge[2] = l;315edge[3] = r;316return nedges++;317}318else319{320return EV_UNDEF;321}322}323324static void updateLeftFace(int* e, int s, int t, int f)325{326if (e[0] == s && e[1] == t && e[2] == EV_UNDEF)327e[2] = f;328else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF)329e[3] = f;330}331332static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d)333{334const float a1 = vcross2(a, b, d);335const float a2 = vcross2(a, b, c);336if (a1*a2 < 0.0f)337{338float a3 = vcross2(c, d, a);339float a4 = a3 + a2 - a1;340if (a3 * a4 < 0.0f)341return 1;342}343return 0;344}345346static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1)347{348for (int i = 0; i < nedges; ++i)349{350const int s0 = edges[i*4+0];351const int t0 = edges[i*4+1];352// Same or connected edges do not overlap.353if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1)354continue;355if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3]))356return true;357}358return false;359}360361static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)362{363static const float EPS = 1e-5f;364365int* edge = &edges[e*4];366367// Cache s and t.368int s,t;369if (edge[2] == EV_UNDEF)370{371s = edge[0];372t = edge[1];373}374else if (edge[3] == EV_UNDEF)375{376s = edge[1];377t = edge[0];378}379else380{381// Edge already completed.382return;383}384385// Find best point on left of edge.386int pt = npts;387float c[3] = {0,0,0};388float r = -1;389for (int u = 0; u < npts; ++u)390{391if (u == s || u == t) continue;392if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)393{394if (r < 0)395{396// The circle is not updated yet, do it now.397pt = u;398circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);399continue;400}401const float d = vdist2(c, &pts[u*3]);402const float tol = 0.001f;403if (d > r*(1+tol))404{405// Outside current circumcircle, skip.406continue;407}408else if (d < r*(1-tol))409{410// Inside safe circumcircle, update circle.411pt = u;412circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);413}414else415{416// Inside epsilon circum circle, do extra tests to make sure the edge is valid.417// s-u and t-u cannot overlap with s-pt nor t-pt if they exists.418if (overlapEdges(pts, edges, nedges, s,u))419continue;420if (overlapEdges(pts, edges, nedges, t,u))421continue;422// Edge is valid.423pt = u;424circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);425}426}427}428429// Add new triangle or update edge info if s-t is on hull.430if (pt < npts)431{432// Update face information of edge being completed.433updateLeftFace(&edges[e*4], s, t, nfaces);434435// Add new edge or update face info of old edge.436e = findEdge(edges, nedges, pt, s);437if (e == EV_UNDEF)438addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF);439else440updateLeftFace(&edges[e*4], pt, s, nfaces);441442// Add new edge or update face info of old edge.443e = findEdge(edges, nedges, t, pt);444if (e == EV_UNDEF)445addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF);446else447updateLeftFace(&edges[e*4], t, pt, nfaces);448449nfaces++;450}451else452{453updateLeftFace(&edges[e*4], s, t, EV_HULL);454}455}456457static void delaunayHull(rcContext* ctx, const int npts, const float* pts,458const int nhull, const int* hull,459rcIntArray& tris, rcIntArray& edges)460{461int nfaces = 0;462int nedges = 0;463const int maxEdges = npts*10;464edges.resize(maxEdges*4);465466for (int i = 0, j = nhull-1; i < nhull; j=i++)467addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF);468469int currentEdge = 0;470while (currentEdge < nedges)471{472if (edges[currentEdge*4+2] == EV_UNDEF)473completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);474if (edges[currentEdge*4+3] == EV_UNDEF)475completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);476currentEdge++;477}478479// Create tris480tris.resize(nfaces*4);481for (int i = 0; i < nfaces*4; ++i)482tris[i] = -1;483484for (int i = 0; i < nedges; ++i)485{486const int* e = &edges[i*4];487if (e[3] >= 0)488{489// Left face490int* t = &tris[e[3]*4];491if (t[0] == -1)492{493t[0] = e[0];494t[1] = e[1];495}496else if (t[0] == e[1])497t[2] = e[0];498else if (t[1] == e[0])499t[2] = e[1];500}501if (e[2] >= 0)502{503// Right504int* t = &tris[e[2]*4];505if (t[0] == -1)506{507t[0] = e[1];508t[1] = e[0];509}510else if (t[0] == e[0])511t[2] = e[1];512else if (t[1] == e[1])513t[2] = e[0];514}515}516517for (int i = 0; i < tris.size()/4; ++i)518{519int* t = &tris[i*4];520if (t[0] == -1 || t[1] == -1 || t[2] == -1)521{522ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);523t[0] = tris[tris.size()-4];524t[1] = tris[tris.size()-3];525t[2] = tris[tris.size()-2];526t[3] = tris[tris.size()-1];527tris.resize(tris.size()-4);528--i;529}530}531}532533// Calculate minimum extend of the polygon.534static float polyMinExtent(const float* verts, const int nverts)535{536float minDist = FLT_MAX;537for (int i = 0; i < nverts; i++)538{539const int ni = (i+1) % nverts;540const float* p1 = &verts[i*3];541const float* p2 = &verts[ni*3];542float maxEdgeDist = 0;543for (int j = 0; j < nverts; j++)544{545if (j == i || j == ni) continue;546float d = distancePtSeg2d(&verts[j*3], p1,p2);547maxEdgeDist = rcMax(maxEdgeDist, d);548}549minDist = rcMin(minDist, maxEdgeDist);550}551return rcSqrt(minDist);552}553554// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).555inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }556inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }557558static void triangulateHull(const int /*nverts*/, const float* verts, const int nhull, const int* hull, const int nin, rcIntArray& tris)559{560int start = 0, left = 1, right = nhull-1;561562// Start from an ear with shortest perimeter.563// This tends to favor well formed triangles as starting point.564float dmin = FLT_MAX;565for (int i = 0; i < nhull; i++)566{567if (hull[i] >= nin) continue; // Ears are triangles with original vertices as middle vertex while others are actually line segments on edges568int pi = prev(i, nhull);569int ni = next(i, nhull);570const float* pv = &verts[hull[pi]*3];571const float* cv = &verts[hull[i]*3];572const float* nv = &verts[hull[ni]*3];573const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);574if (d < dmin)575{576start = i;577left = ni;578right = pi;579dmin = d;580}581}582583// Add first triangle584tris.push(hull[start]);585tris.push(hull[left]);586tris.push(hull[right]);587tris.push(0);588589// Triangulate the polygon by moving left or right,590// depending on which triangle has shorter perimeter.591// This heuristic was chose emprically, since it seems592// handle tesselated straight edges well.593while (next(left, nhull) != right)594{595// Check to see if se should advance left or right.596int nleft = next(left, nhull);597int nright = prev(right, nhull);598599const float* cvleft = &verts[hull[left]*3];600const float* nvleft = &verts[hull[nleft]*3];601const float* cvright = &verts[hull[right]*3];602const float* nvright = &verts[hull[nright]*3];603const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);604const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright);605606if (dleft < dright)607{608tris.push(hull[left]);609tris.push(hull[nleft]);610tris.push(hull[right]);611tris.push(0);612left = nleft;613}614else615{616tris.push(hull[left]);617tris.push(hull[nright]);618tris.push(hull[right]);619tris.push(0);620right = nright;621}622}623}624625626inline float getJitterX(const int i)627{628return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f;629}630631inline float getJitterY(const int i)632{633return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f;634}635636static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin,637const float sampleDist, const float sampleMaxError,638const int heightSearchRadius, const rcCompactHeightfield& chf,639const rcHeightPatch& hp, float* verts, int& nverts,640rcIntArray& tris, rcIntArray& edges, rcIntArray& samples)641{642static const int MAX_VERTS = 127;643static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).644static const int MAX_VERTS_PER_EDGE = 32;645float edge[(MAX_VERTS_PER_EDGE+1)*3];646int hull[MAX_VERTS];647int nhull = 0;648649nverts = nin;650651for (int i = 0; i < nin; ++i)652rcVcopy(&verts[i*3], &in[i*3]);653654edges.clear();655tris.clear();656657const float cs = chf.cs;658const float ics = 1.0f/cs;659660// Calculate minimum extents of the polygon based on input data.661float minExtent = polyMinExtent(verts, nverts);662663// Tessellate outlines.664// This is done in separate pass in order to ensure665// seamless height values across the ply boundaries.666if (sampleDist > 0)667{668for (int i = 0, j = nin-1; i < nin; j=i++)669{670const float* vj = &in[j*3];671const float* vi = &in[i*3];672bool swapped = false;673// Make sure the segments are always handled in same order674// using lexological sort or else there will be seams.675if (fabsf(vj[0]-vi[0]) < 1e-6f)676{677if (vj[2] > vi[2])678{679rcSwap(vj,vi);680swapped = true;681}682}683else684{685if (vj[0] > vi[0])686{687rcSwap(vj,vi);688swapped = true;689}690}691// Create samples along the edge.692float dx = vi[0] - vj[0];693float dy = vi[1] - vj[1];694float dz = vi[2] - vj[2];695float d = sqrtf(dx*dx + dz*dz);696int nn = 1 + (int)floorf(d/sampleDist);697if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1;698if (nverts+nn >= MAX_VERTS)699nn = MAX_VERTS-1-nverts;700701for (int k = 0; k <= nn; ++k)702{703float u = (float)k/(float)nn;704float* pos = &edge[k*3];705pos[0] = vj[0] + dx*u;706pos[1] = vj[1] + dy*u;707pos[2] = vj[2] + dz*u;708pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, heightSearchRadius, hp)*chf.ch;709}710// Simplify samples.711int idx[MAX_VERTS_PER_EDGE] = {0,nn};712int nidx = 2;713for (int k = 0; k < nidx-1; )714{715const int a = idx[k];716const int b = idx[k+1];717const float* va = &edge[a*3];718const float* vb = &edge[b*3];719// Find maximum deviation along the segment.720float maxd = 0;721int maxi = -1;722for (int m = a+1; m < b; ++m)723{724float dev = distancePtSeg(&edge[m*3],va,vb);725if (dev > maxd)726{727maxd = dev;728maxi = m;729}730}731// If the max deviation is larger than accepted error,732// add new point, else continue to next segment.733if (maxi != -1 && maxd > rcSqr(sampleMaxError))734{735for (int m = nidx; m > k; --m)736idx[m] = idx[m-1];737idx[k+1] = maxi;738nidx++;739}740else741{742++k;743}744}745746hull[nhull++] = j;747// Add new vertices.748if (swapped)749{750for (int k = nidx-2; k > 0; --k)751{752rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);753hull[nhull++] = nverts;754nverts++;755}756}757else758{759for (int k = 1; k < nidx-1; ++k)760{761rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);762hull[nhull++] = nverts;763nverts++;764}765}766}767}768769// If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.770if (minExtent < sampleDist*2)771{772triangulateHull(nverts, verts, nhull, hull, nin, tris);773return true;774}775776// Tessellate the base mesh.777// We're using the triangulateHull instead of delaunayHull as it tends to778// create a bit better triangulation for long thin triangles when there779// are no internal points.780triangulateHull(nverts, verts, nhull, hull, nin, tris);781782if (tris.size() == 0)783{784// Could not triangulate the poly, make sure there is some valid data there.785ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts);786return true;787}788789if (sampleDist > 0)790{791// Create sample locations in a grid.792float bmin[3], bmax[3];793rcVcopy(bmin, in);794rcVcopy(bmax, in);795for (int i = 1; i < nin; ++i)796{797rcVmin(bmin, &in[i*3]);798rcVmax(bmax, &in[i*3]);799}800int x0 = (int)floorf(bmin[0]/sampleDist);801int x1 = (int)ceilf(bmax[0]/sampleDist);802int z0 = (int)floorf(bmin[2]/sampleDist);803int z1 = (int)ceilf(bmax[2]/sampleDist);804samples.clear();805for (int z = z0; z < z1; ++z)806{807for (int x = x0; x < x1; ++x)808{809float pt[3];810pt[0] = x*sampleDist;811pt[1] = (bmax[1]+bmin[1])*0.5f;812pt[2] = z*sampleDist;813// Make sure the samples are not too close to the edges.814if (distToPoly(nin,in,pt) > -sampleDist/2) continue;815samples.push(x);816samples.push(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, heightSearchRadius, hp));817samples.push(z);818samples.push(0); // Not added819}820}821822// Add the samples starting from the one that has the most823// error. The procedure stops when all samples are added824// or when the max error is within treshold.825const int nsamples = samples.size()/4;826for (int iter = 0; iter < nsamples; ++iter)827{828if (nverts >= MAX_VERTS)829break;830831// Find sample with most error.832float bestpt[3] = {0,0,0};833float bestd = 0;834int besti = -1;835for (int i = 0; i < nsamples; ++i)836{837const int* s = &samples[i*4];838if (s[3]) continue; // skip added.839float pt[3];840// The sample location is jittered to get rid of some bad triangulations841// which are cause by symmetrical data from the grid structure.842pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f;843pt[1] = s[1]*chf.ch;844pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f;845float d = distToTriMesh(pt, verts, nverts, &tris[0], tris.size()/4);846if (d < 0) continue; // did not hit the mesh.847if (d > bestd)848{849bestd = d;850besti = i;851rcVcopy(bestpt,pt);852}853}854// If the max error is within accepted threshold, stop tesselating.855if (bestd <= sampleMaxError || besti == -1)856break;857// Mark sample as added.858samples[besti*4+3] = 1;859// Add the new sample point.860rcVcopy(&verts[nverts*3],bestpt);861nverts++;862863// Create new triangulation.864// TODO: Incremental add instead of full rebuild.865edges.clear();866tris.clear();867delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges);868}869}870871const int ntris = tris.size()/4;872if (ntris > MAX_TRIS)873{874tris.resize(MAX_TRIS*4);875ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS);876}877878return true;879}880881static void seedArrayWithPolyCenter(rcContext* ctx, const rcCompactHeightfield& chf,882const unsigned short* poly, const int npoly,883const unsigned short* verts, const int bs,884rcHeightPatch& hp, rcIntArray& array)885{886// Note: Reads to the compact heightfield are offset by border size (bs)887// since border size offset is already removed from the polymesh vertices.888889static const int offset[9*2] =890{8910,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0,892};893894// Find cell closest to a poly vertex895int startCellX = 0, startCellY = 0, startSpanIndex = -1;896int dmin = RC_UNSET_HEIGHT;897for (int j = 0; j < npoly && dmin > 0; ++j)898{899for (int k = 0; k < 9 && dmin > 0; ++k)900{901const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0];902const int ay = (int)verts[poly[j]*3+1];903const int az = (int)verts[poly[j]*3+2] + offset[k*2+1];904if (ax < hp.xmin || ax >= hp.xmin+hp.width ||905az < hp.ymin || az >= hp.ymin+hp.height)906continue;907908const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width];909for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni && dmin > 0; ++i)910{911const rcCompactSpan& s = chf.spans[i];912int d = rcAbs(ay - (int)s.y);913if (d < dmin)914{915startCellX = ax;916startCellY = az;917startSpanIndex = i;918dmin = d;919}920}921}922}923924rcAssert(startSpanIndex != -1);925// Find center of the polygon926int pcx = 0, pcy = 0;927for (int j = 0; j < npoly; ++j)928{929pcx += (int)verts[poly[j]*3+0];930pcy += (int)verts[poly[j]*3+2];931}932pcx /= npoly;933pcy /= npoly;934935// Use seeds array as a stack for DFS936array.clear();937array.push(startCellX);938array.push(startCellY);939array.push(startSpanIndex);940941int dirs[] = { 0, 1, 2, 3 };942memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height);943// DFS to move to the center. Note that we need a DFS here and can not just move944// directly towards the center without recording intermediate nodes, even though the polygons945// are convex. In very rare we can get stuck due to contour simplification if we do not946// record nodes.947int cx = -1, cy = -1, ci = -1;948while (true)949{950if (array.size() < 3)951{952ctx->log(RC_LOG_WARNING, "Walk towards polygon center failed to reach center");953break;954}955956ci = array.pop();957cy = array.pop();958cx = array.pop();959960if (cx == pcx && cy == pcy)961break;962963// If we are already at the correct X-position, prefer direction964// directly towards the center in the Y-axis; otherwise prefer965// direction in the X-axis966int directDir;967if (cx == pcx)968directDir = rcGetDirForOffset(0, pcy > cy ? 1 : -1);969else970directDir = rcGetDirForOffset(pcx > cx ? 1 : -1, 0);971972// Push the direct dir last so we start with this on next iteration973rcSwap(dirs[directDir], dirs[3]);974975const rcCompactSpan& cs = chf.spans[ci];976for (int i = 0; i < 4; i++)977{978int dir = dirs[i];979if (rcGetCon(cs, dir) == RC_NOT_CONNECTED)980continue;981982int newX = cx + rcGetDirOffsetX(dir);983int newY = cy + rcGetDirOffsetY(dir);984985int hpx = newX - hp.xmin;986int hpy = newY - hp.ymin;987if (hpx < 0 || hpx >= hp.width || hpy < 0 || hpy >= hp.height)988continue;989990if (hp.data[hpx+hpy*hp.width] != 0)991continue;992993hp.data[hpx+hpy*hp.width] = 1;994array.push(newX);995array.push(newY);996array.push((int)chf.cells[(newX+bs)+(newY+bs)*chf.width].index + rcGetCon(cs, dir));997}998999rcSwap(dirs[directDir], dirs[3]);1000}10011002array.clear();1003// getHeightData seeds are given in coordinates with borders1004array.push(cx+bs);1005array.push(cy+bs);1006array.push(ci);10071008memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);1009const rcCompactSpan& cs = chf.spans[ci];1010hp.data[cx-hp.xmin+(cy-hp.ymin)*hp.width] = cs.y;1011}101210131014static void push3(rcIntArray& queue, int v1, int v2, int v3)1015{1016queue.resize(queue.size() + 3);1017queue[queue.size() - 3] = v1;1018queue[queue.size() - 2] = v2;1019queue[queue.size() - 1] = v3;1020}10211022static void getHeightData(rcContext* ctx, const rcCompactHeightfield& chf,1023const unsigned short* poly, const int npoly,1024const unsigned short* verts, const int bs,1025rcHeightPatch& hp, rcIntArray& queue,1026int region)1027{1028// Note: Reads to the compact heightfield are offset by border size (bs)1029// since border size offset is already removed from the polymesh vertices.10301031queue.clear();1032// Set all heights to RC_UNSET_HEIGHT.1033memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);10341035bool empty = true;10361037// We cannot sample from this poly if it was created from polys1038// of different regions. If it was then it could potentially be overlapping1039// with polys of that region and the heights sampled here could be wrong.1040if (region != RC_MULTIPLE_REGS)1041{1042// Copy the height from the same region, and mark region borders1043// as seed points to fill the rest.1044for (int hy = 0; hy < hp.height; hy++)1045{1046int y = hp.ymin + hy + bs;1047for (int hx = 0; hx < hp.width; hx++)1048{1049int x = hp.xmin + hx + bs;1050const rcCompactCell& c = chf.cells[x + y*chf.width];1051for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)1052{1053const rcCompactSpan& s = chf.spans[i];1054if (s.reg == region)1055{1056// Store height1057hp.data[hx + hy*hp.width] = s.y;1058empty = false;10591060// If any of the neighbours is not in same region,1061// add the current location as flood fill start1062bool border = false;1063for (int dir = 0; dir < 4; ++dir)1064{1065if (rcGetCon(s, dir) != RC_NOT_CONNECTED)1066{1067const int ax = x + rcGetDirOffsetX(dir);1068const int ay = y + rcGetDirOffsetY(dir);1069const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(s, dir);1070const rcCompactSpan& as = chf.spans[ai];1071if (as.reg != region)1072{1073border = true;1074break;1075}1076}1077}1078if (border)1079push3(queue, x, y, i);1080break;1081}1082}1083}1084}1085}10861087// if the polygon does not contain any points from the current region (rare, but happens)1088// or if it could potentially be overlapping polygons of the same region,1089// then use the center as the seed point.1090if (empty)1091seedArrayWithPolyCenter(ctx, chf, poly, npoly, verts, bs, hp, queue);10921093static const int RETRACT_SIZE = 256;1094int head = 0;10951096// We assume the seed is centered in the polygon, so a BFS to collect1097// height data will ensure we do not move onto overlapping polygons and1098// sample wrong heights.1099while (head*3 < queue.size())1100{1101int cx = queue[head*3+0];1102int cy = queue[head*3+1];1103int ci = queue[head*3+2];1104head++;1105if (head >= RETRACT_SIZE)1106{1107head = 0;1108if (queue.size() > RETRACT_SIZE*3)1109memmove(&queue[0], &queue[RETRACT_SIZE*3], sizeof(int)*(queue.size()-RETRACT_SIZE*3));1110queue.resize(queue.size()-RETRACT_SIZE*3);1111}11121113const rcCompactSpan& cs = chf.spans[ci];1114for (int dir = 0; dir < 4; ++dir)1115{1116if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;11171118const int ax = cx + rcGetDirOffsetX(dir);1119const int ay = cy + rcGetDirOffsetY(dir);1120const int hx = ax - hp.xmin - bs;1121const int hy = ay - hp.ymin - bs;11221123if ((unsigned int)hx >= (unsigned int)hp.width || (unsigned int)hy >= (unsigned int)hp.height)1124continue;11251126if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT)1127continue;11281129const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);1130const rcCompactSpan& as = chf.spans[ai];11311132hp.data[hx + hy*hp.width] = as.y;11331134push3(queue, ax, ay, ai);1135}1136}1137}11381139static unsigned char getEdgeFlags(const float* va, const float* vb,1140const float* vpoly, const int npoly)1141{1142// The flag returned by this function matches dtDetailTriEdgeFlags in Detour.1143// Figure out if edge (va,vb) is part of the polygon boundary.1144static const float thrSqr = rcSqr(0.001f);1145for (int i = 0, j = npoly-1; i < npoly; j=i++)1146{1147if (distancePtSeg2d(va, &vpoly[j*3], &vpoly[i*3]) < thrSqr &&1148distancePtSeg2d(vb, &vpoly[j*3], &vpoly[i*3]) < thrSqr)1149return 1;1150}1151return 0;1152}11531154static unsigned char getTriFlags(const float* va, const float* vb, const float* vc,1155const float* vpoly, const int npoly)1156{1157unsigned char flags = 0;1158flags |= getEdgeFlags(va,vb,vpoly,npoly) << 0;1159flags |= getEdgeFlags(vb,vc,vpoly,npoly) << 2;1160flags |= getEdgeFlags(vc,va,vpoly,npoly) << 4;1161return flags;1162}11631164/// @par1165///1166/// See the #rcConfig documentation for more information on the configuration parameters.1167///1168/// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig1169bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,1170const float sampleDist, const float sampleMaxError,1171rcPolyMeshDetail& dmesh)1172{1173rcAssert(ctx);11741175rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESHDETAIL);11761177if (mesh.nverts == 0 || mesh.npolys == 0)1178return true;11791180const int nvp = mesh.nvp;1181const float cs = mesh.cs;1182const float ch = mesh.ch;1183const float* orig = mesh.bmin;1184const int borderSize = mesh.borderSize;1185const int heightSearchRadius = rcMax(1, (int)ceilf(mesh.maxEdgeError));11861187rcIntArray edges(64);1188rcIntArray tris(512);1189rcIntArray arr(512);1190rcIntArray samples(512);1191float verts[256*3];1192rcHeightPatch hp;1193int nPolyVerts = 0;1194int maxhw = 0, maxhh = 0;11951196rcScopedDelete<int> bounds((int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP));1197if (!bounds)1198{1199ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4);1200return false;1201}1202rcScopedDelete<float> poly((float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP));1203if (!poly)1204{1205ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3);1206return false;1207}12081209// Find max size for a polygon area.1210for (int i = 0; i < mesh.npolys; ++i)1211{1212const unsigned short* p = &mesh.polys[i*nvp*2];1213int& xmin = bounds[i*4+0];1214int& xmax = bounds[i*4+1];1215int& ymin = bounds[i*4+2];1216int& ymax = bounds[i*4+3];1217xmin = chf.width;1218xmax = 0;1219ymin = chf.height;1220ymax = 0;1221for (int j = 0; j < nvp; ++j)1222{1223if(p[j] == RC_MESH_NULL_IDX) break;1224const unsigned short* v = &mesh.verts[p[j]*3];1225xmin = rcMin(xmin, (int)v[0]);1226xmax = rcMax(xmax, (int)v[0]);1227ymin = rcMin(ymin, (int)v[2]);1228ymax = rcMax(ymax, (int)v[2]);1229nPolyVerts++;1230}1231xmin = rcMax(0,xmin-1);1232xmax = rcMin(chf.width,xmax+1);1233ymin = rcMax(0,ymin-1);1234ymax = rcMin(chf.height,ymax+1);1235if (xmin >= xmax || ymin >= ymax) continue;1236maxhw = rcMax(maxhw, xmax-xmin);1237maxhh = rcMax(maxhh, ymax-ymin);1238}12391240hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);1241if (!hp.data)1242{1243ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);1244return false;1245}12461247dmesh.nmeshes = mesh.npolys;1248dmesh.nverts = 0;1249dmesh.ntris = 0;1250dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM);1251if (!dmesh.meshes)1252{1253ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4);1254return false;1255}12561257int vcap = nPolyVerts+nPolyVerts/2;1258int tcap = vcap*2;12591260dmesh.nverts = 0;1261dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);1262if (!dmesh.verts)1263{1264ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3);1265return false;1266}1267dmesh.ntris = 0;1268dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);1269if (!dmesh.tris)1270{1271ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4);1272return false;1273}12741275for (int i = 0; i < mesh.npolys; ++i)1276{1277const unsigned short* p = &mesh.polys[i*nvp*2];12781279// Store polygon vertices for processing.1280int npoly = 0;1281for (int j = 0; j < nvp; ++j)1282{1283if(p[j] == RC_MESH_NULL_IDX) break;1284const unsigned short* v = &mesh.verts[p[j]*3];1285poly[j*3+0] = v[0]*cs;1286poly[j*3+1] = v[1]*ch;1287poly[j*3+2] = v[2]*cs;1288npoly++;1289}12901291// Get the height data from the area of the polygon.1292hp.xmin = bounds[i*4+0];1293hp.ymin = bounds[i*4+2];1294hp.width = bounds[i*4+1]-bounds[i*4+0];1295hp.height = bounds[i*4+3]-bounds[i*4+2];1296getHeightData(ctx, chf, p, npoly, mesh.verts, borderSize, hp, arr, mesh.regs[i]);12971298// Build detail mesh.1299int nverts = 0;1300if (!buildPolyDetail(ctx, poly, npoly,1301sampleDist, sampleMaxError,1302heightSearchRadius, chf, hp,1303verts, nverts, tris,1304edges, samples))1305{1306return false;1307}13081309// Move detail verts to world space.1310for (int j = 0; j < nverts; ++j)1311{1312verts[j*3+0] += orig[0];1313verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary?1314verts[j*3+2] += orig[2];1315}1316// Offset poly too, will be used to flag checking.1317for (int j = 0; j < npoly; ++j)1318{1319poly[j*3+0] += orig[0];1320poly[j*3+1] += orig[1];1321poly[j*3+2] += orig[2];1322}13231324// Store detail submesh.1325const int ntris = tris.size()/4;13261327dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts;1328dmesh.meshes[i*4+1] = (unsigned int)nverts;1329dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris;1330dmesh.meshes[i*4+3] = (unsigned int)ntris;13311332// Store vertices, allocate more memory if necessary.1333if (dmesh.nverts+nverts > vcap)1334{1335while (dmesh.nverts+nverts > vcap)1336vcap += 256;13371338float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);1339if (!newv)1340{1341ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3);1342return false;1343}1344if (dmesh.nverts)1345memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts);1346rcFree(dmesh.verts);1347dmesh.verts = newv;1348}1349for (int j = 0; j < nverts; ++j)1350{1351dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0];1352dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1];1353dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2];1354dmesh.nverts++;1355}13561357// Store triangles, allocate more memory if necessary.1358if (dmesh.ntris+ntris > tcap)1359{1360while (dmesh.ntris+ntris > tcap)1361tcap += 256;1362unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);1363if (!newt)1364{1365ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4);1366return false;1367}1368if (dmesh.ntris)1369memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris);1370rcFree(dmesh.tris);1371dmesh.tris = newt;1372}1373for (int j = 0; j < ntris; ++j)1374{1375const int* t = &tris[j*4];1376dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0];1377dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1];1378dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2];1379dmesh.tris[dmesh.ntris*4+3] = getTriFlags(&verts[t[0]*3], &verts[t[1]*3], &verts[t[2]*3], poly, npoly);1380dmesh.ntris++;1381}1382}13831384return true;1385}13861387/// @see rcAllocPolyMeshDetail, rcPolyMeshDetail1388bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)1389{1390rcAssert(ctx);13911392rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESHDETAIL);13931394int maxVerts = 0;1395int maxTris = 0;1396int maxMeshes = 0;13971398for (int i = 0; i < nmeshes; ++i)1399{1400if (!meshes[i]) continue;1401maxVerts += meshes[i]->nverts;1402maxTris += meshes[i]->ntris;1403maxMeshes += meshes[i]->nmeshes;1404}14051406mesh.nmeshes = 0;1407mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);1408if (!mesh.meshes)1409{1410ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4);1411return false;1412}14131414mesh.ntris = 0;1415mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);1416if (!mesh.tris)1417{1418ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4);1419return false;1420}14211422mesh.nverts = 0;1423mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);1424if (!mesh.verts)1425{1426ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3);1427return false;1428}14291430// Merge datas.1431for (int i = 0; i < nmeshes; ++i)1432{1433rcPolyMeshDetail* dm = meshes[i];1434if (!dm) continue;1435for (int j = 0; j < dm->nmeshes; ++j)1436{1437unsigned int* dst = &mesh.meshes[mesh.nmeshes*4];1438unsigned int* src = &dm->meshes[j*4];1439dst[0] = (unsigned int)mesh.nverts+src[0];1440dst[1] = src[1];1441dst[2] = (unsigned int)mesh.ntris+src[2];1442dst[3] = src[3];1443mesh.nmeshes++;1444}14451446for (int k = 0; k < dm->nverts; ++k)1447{1448rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]);1449mesh.nverts++;1450}1451for (int k = 0; k < dm->ntris; ++k)1452{1453mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0];1454mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1];1455mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2];1456mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3];1457mesh.ntris++;1458}1459}14601461return true;1462}146314641465