Debian Codegraph @

RecastDemo/Source/InputGeom.cpp

raw symbols SCIP
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 <stdio.h>
21 #include <ctype.h>
22 #include <string.h>
23 #include <algorithm>
24 #include "Recast.h"
25 #include "InputGeom.h"
26 #include "ChunkyTriMesh.h"
27 #include "MeshLoaderObj.h"
28 #include "DebugDraw.h"
29 #include "RecastDebugDraw.h"
30 #include "DetourNavMesh.h"
31 #include "Sample.h"
32
33 static bool intersectSegmentTriangle(const float* sp, const float* sq,
34 const float* a, const float* b, const float* c,
35 float &t)
36 {
37 float v, w;
38 float ab[3], ac[3], qp[3], ap[3], norm[3], e[3];
39 rcVsub(ab, b, a);
40 rcVsub(ac, c, a);
41 rcVsub(qp, sp, sq);
42
43 // Compute triangle normal. Can be precalculated or cached if
44 // intersecting multiple segments against the same triangle
45 rcVcross(norm, ab, ac);
46
47 // Compute denominator d. If d <= 0, segment is parallel to or points
48 // away from triangle, so exit early
49 float d = rcVdot(qp, norm);
50 if (d <= 0.0f) return false;
51
52 // Compute intersection t value of pq with plane of triangle. A ray
53 // intersects iff 0 <= t. Segment intersects iff 0 <= t <= 1. Delay
54 // dividing by d until intersection has been found to pierce triangle
55 rcVsub(ap, sp, a);
56 t = rcVdot(ap, norm);
57 if (t < 0.0f) return false;
58 if (t > d) return false; // For segment; exclude this code line for a ray test
59
60 // Compute barycentric coordinate components and test if within bounds
61 rcVcross(e, qp, ap);
62 v = rcVdot(ac, e);
63 if (v < 0.0f || v > d) return false;
64 w = -rcVdot(ab, e);
65 if (w < 0.0f || v + w > d) return false;
66
67 // Segment/ray intersects triangle. Perform delayed division
68 t /= d;
69
70 return true;
71 }
72
73 static char* parseRow(char* buf, char* bufEnd, char* row, int len)
74 {
75 bool start = true;
76 bool done = false;
77 int n = 0;
78 while (!done && buf < bufEnd)
79 {
80 char c = *buf;
81 buf++;
82 // multirow
83 switch (c)
84 {
85 case '\n':
86 if (start) break;
87 done = true;
88 break;
89 case '\r':
90 break;
91 case '\t':
92 case ' ':
93 if (start) break;
94 // else falls through
95 default:
96 start = false;
97 row[n++] = c;
98 if (n >= len-1)
99 done = true;
100 break;
101 }
102 }
103 row[n] = '\0';
104 return buf;
105 }
106
107
108
109 InputGeom::InputGeom() :
110 m_chunkyMesh(0),
111 m_mesh(0),
112 m_hasBuildSettings(false),
113 m_offMeshConCount(0),
114 m_volumeCount(0)
115 {
116 }
117
118 InputGeom::~InputGeom()
119 {
120 delete m_chunkyMesh;
121 delete m_mesh;
122 }
123
124 bool InputGeom::loadMesh(rcContext* ctx, const std::string& filepath)
125 {
126 if (m_mesh)
127 {
128 delete m_chunkyMesh;
129 m_chunkyMesh = 0;
130 delete m_mesh;
131 m_mesh = 0;
132 }
133 m_offMeshConCount = 0;
134 m_volumeCount = 0;
135
136 m_mesh = new rcMeshLoaderObj;
137 if (!m_mesh)
138 {
139 ctx->log(RC_LOG_ERROR, "loadMesh: Out of memory 'm_mesh'.");
140 return false;
141 }
142 if (!m_mesh->load(filepath))
143 {
144 ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath.c_str());
145 return false;
146 }
147
148 rcCalcBounds(m_mesh->getVerts(), m_mesh->getVertCount(), m_meshBMin, m_meshBMax);
149
150 m_chunkyMesh = new rcChunkyTriMesh;
151 if (!m_chunkyMesh)
152 {
153 ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Out of memory 'm_chunkyMesh'.");
154 return false;
155 }
156 if (!rcCreateChunkyTriMesh(m_mesh->getVerts(), m_mesh->getTris(), m_mesh->getTriCount(), 256, m_chunkyMesh))
157 {
158 ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Failed to build chunky mesh.");
159 return false;
160 }
161
162 return true;
163 }
164
165 bool InputGeom::loadGeomSet(rcContext* ctx, const std::string& filepath)
166 {
167 char* buf = 0;
168 FILE* fp = fopen(filepath.c_str(), "rb");
169 if (!fp)
170 {
171 return false;
172 }
173 if (fseek(fp, 0, SEEK_END) != 0)
174 {
175 fclose(fp);
176 return false;
177 }
178
179 long bufSize = ftell(fp);
180 if (bufSize < 0)
181 {
182 fclose(fp);
183 return false;
184 }
185 if (fseek(fp, 0, SEEK_SET) != 0)
186 {
187 fclose(fp);
188 return false;
189 }
190 buf = new char[bufSize];
191 if (!buf)
192 {
193 fclose(fp);
194 return false;
195 }
196 size_t readLen = fread(buf, bufSize, 1, fp);
197 fclose(fp);
198 if (readLen != 1)
199 {
200 delete[] buf;
201 return false;
202 }
203
204 m_offMeshConCount = 0;
205 m_volumeCount = 0;
206 delete m_mesh;
207 m_mesh = 0;
208
209 char* src = buf;
210 char* srcEnd = buf + bufSize;
211 char row[512];
212 while (src < srcEnd)
213 {
214 // Parse one row
215 row[0] = '\0';
216 src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
217 if (row[0] == 'f')
218 {
219 // File name.
220 const char* name = row+1;
221 // Skip white spaces
222 while (*name && isspace(*name))
223 name++;
224 if (*name)
225 {
226 if (!loadMesh(ctx, name))
227 {
228 delete [] buf;
229 return false;
230 }
231 }
232 }
233 else if (row[0] == 'c')
234 {
235 // Off-mesh connection
236 if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS)
237 {
238 float* v = &m_offMeshConVerts[m_offMeshConCount*3*2];
239 int bidir, area = 0, flags = 0;
240 float rad;
241 sscanf(row+1, "%f %f %f %f %f %f %f %d %d %d",
242 &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
243 m_offMeshConRads[m_offMeshConCount] = rad;
244 m_offMeshConDirs[m_offMeshConCount] = (unsigned char)bidir;
245 m_offMeshConAreas[m_offMeshConCount] = (unsigned char)area;
246 m_offMeshConFlags[m_offMeshConCount] = (unsigned short)flags;
247 m_offMeshConCount++;
248 }
249 }
250 else if (row[0] == 'v')
251 {
252 // Convex volumes
253 if (m_volumeCount < MAX_VOLUMES)
254 {
255 ConvexVolume* vol = &m_volumes[m_volumeCount++];
256 sscanf(row+1, "%d %d %f %f", &vol->nverts, &vol->area, &vol->hmin, &vol->hmax);
257 for (int i = 0; i < vol->nverts; ++i)
258 {
259 row[0] = '\0';
260 src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
261 sscanf(row, "%f %f %f", &vol->verts[i*3+0], &vol->verts[i*3+1], &vol->verts[i*3+2]);
262 }
263 }
264 }
265 else if (row[0] == 's')
266 {
267 // Settings
268 m_hasBuildSettings = true;
269 sscanf(row + 1, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d %f %f %f %f %f %f %f",
270 &m_buildSettings.cellSize,
271 &m_buildSettings.cellHeight,
272 &m_buildSettings.agentHeight,
273 &m_buildSettings.agentRadius,
274 &m_buildSettings.agentMaxClimb,
275 &m_buildSettings.agentMaxSlope,
276 &m_buildSettings.regionMinSize,
277 &m_buildSettings.regionMergeSize,
278 &m_buildSettings.edgeMaxLen,
279 &m_buildSettings.edgeMaxError,
280 &m_buildSettings.vertsPerPoly,
281 &m_buildSettings.detailSampleDist,
282 &m_buildSettings.detailSampleMaxError,
283 &m_buildSettings.partitionType,
284 &m_buildSettings.navMeshBMin[0],
285 &m_buildSettings.navMeshBMin[1],
286 &m_buildSettings.navMeshBMin[2],
287 &m_buildSettings.navMeshBMax[0],
288 &m_buildSettings.navMeshBMax[1],
289 &m_buildSettings.navMeshBMax[2],
290 &m_buildSettings.tileSize);
291 }
292 }
293
294 delete [] buf;
295
296 return true;
297 }
298
299 bool InputGeom::load(rcContext* ctx, const std::string& filepath)
300 {
301 size_t extensionPos = filepath.find_last_of('.');
302 if (extensionPos == std::string::npos)
303 return false;
304
305 std::string extension = filepath.substr(extensionPos);
306 std::transform(extension.begin(), extension.end(), extension.begin(), tolower);
307
308 if (extension == ".gset")
309 return loadGeomSet(ctx, filepath);
310 if (extension == ".obj")
311 return loadMesh(ctx, filepath);
312
313 return false;
314 }
315
316 bool InputGeom::saveGeomSet(const BuildSettings* settings)
317 {
318 if (!m_mesh) return false;
319
320 // Change extension
321 std::string filepath = m_mesh->getFileName();
322 size_t extPos = filepath.find_last_of('.');
323 if (extPos != std::string::npos)
324 filepath = filepath.substr(0, extPos);
325
326 filepath += ".gset";
327
328 FILE* fp = fopen(filepath.c_str(), "w");
329 if (!fp) return false;
330
331 // Store mesh filename.
332 fprintf(fp, "f %s\n", m_mesh->getFileName().c_str());
333
334 // Store settings if any
335 if (settings)
336 {
337 fprintf(fp,
338 "s %f %f %f %f %f %f %f %f %f %f %f %f %f %d %f %f %f %f %f %f %f\n",
339 settings->cellSize,
340 settings->cellHeight,
341 settings->agentHeight,
342 settings->agentRadius,
343 settings->agentMaxClimb,
344 settings->agentMaxSlope,
345 settings->regionMinSize,
346 settings->regionMergeSize,
347 settings->edgeMaxLen,
348 settings->edgeMaxError,
349 settings->vertsPerPoly,
350 settings->detailSampleDist,
351 settings->detailSampleMaxError,
352 settings->partitionType,
353 settings->navMeshBMin[0],
354 settings->navMeshBMin[1],
355 settings->navMeshBMin[2],
356 settings->navMeshBMax[0],
357 settings->navMeshBMax[1],
358 settings->navMeshBMax[2],
359 settings->tileSize);
360 }
361
362 // Store off-mesh links.
363 for (int i = 0; i < m_offMeshConCount; ++i)
364 {
365 const float* v = &m_offMeshConVerts[i*3*2];
366 const float rad = m_offMeshConRads[i];
367 const int bidir = m_offMeshConDirs[i];
368 const int area = m_offMeshConAreas[i];
369 const int flags = m_offMeshConFlags[i];
370 fprintf(fp, "c %f %f %f %f %f %f %f %d %d %d\n",
371 v[0], v[1], v[2], v[3], v[4], v[5], rad, bidir, area, flags);
372 }
373
374 // Convex volumes
375 for (int i = 0; i < m_volumeCount; ++i)
376 {
377 ConvexVolume* vol = &m_volumes[i];
378 fprintf(fp, "v %d %d %f %f\n", vol->nverts, vol->area, vol->hmin, vol->hmax);
379 for (int j = 0; j < vol->nverts; ++j)
380 fprintf(fp, "%f %f %f\n", vol->verts[j*3+0], vol->verts[j*3+1], vol->verts[j*3+2]);
381 }
382
383 fclose(fp);
384
385 return true;
386 }
387
388 static bool isectSegAABB(const float* sp, const float* sq,
389 const float* amin, const float* amax,
390 float& tmin, float& tmax)
391 {
392 static const float EPS = 1e-6f;
393
394 float d[3];
395 d[0] = sq[0] - sp[0];
396 d[1] = sq[1] - sp[1];
397 d[2] = sq[2] - sp[2];
398 tmin = 0.0;
399 tmax = 1.0f;
400
401 for (int i = 0; i < 3; i++)
402 {
403 if (fabsf(d[i]) < EPS)
404 {
405 if (sp[i] < amin[i] || sp[i] > amax[i])
406 return false;
407 }
408 else
409 {
410 const float ood = 1.0f / d[i];
411 float t1 = (amin[i] - sp[i]) * ood;
412 float t2 = (amax[i] - sp[i]) * ood;
413 if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; }
414 if (t1 > tmin) tmin = t1;
415 if (t2 < tmax) tmax = t2;
416 if (tmin > tmax) return false;
417 }
418 }
419
420 return true;
421 }
422
423
424 bool InputGeom::raycastMesh(float* src, float* dst, float& tmin)
425 {
426 // Prune hit ray.
427 float btmin, btmax;
428 if (!isectSegAABB(src, dst, m_meshBMin, m_meshBMax, btmin, btmax))
429 return false;
430 float p[2], q[2];
431 p[0] = src[0] + (dst[0]-src[0])*btmin;
432 p[1] = src[2] + (dst[2]-src[2])*btmin;
433 q[0] = src[0] + (dst[0]-src[0])*btmax;
434 q[1] = src[2] + (dst[2]-src[2])*btmax;
435
436 int cid[512];
437 const int ncid = rcGetChunksOverlappingSegment(m_chunkyMesh, p, q, cid, 512);
438 if (!ncid)
439 return false;
440
441 tmin = 1.0f;
442 bool hit = false;
443 const float* verts = m_mesh->getVerts();
444
445 for (int i = 0; i < ncid; ++i)
446 {
447 const rcChunkyTriMeshNode& node = m_chunkyMesh->nodes[cid[i]];
448 const int* tris = &m_chunkyMesh->tris[node.i*3];
449 const int ntris = node.n;
450
451 for (int j = 0; j < ntris*3; j += 3)
452 {
453 float t = 1;
454 if (intersectSegmentTriangle(src, dst,
455 &verts[tris[j]*3],
456 &verts[tris[j+1]*3],
457 &verts[tris[j+2]*3], t))
458 {
459 if (t < tmin)
460 tmin = t;
461 hit = true;
462 }
463 }
464 }
465
466 return hit;
467 }
468
469 void InputGeom::addOffMeshConnection(const float* spos, const float* epos, const float rad,
470 unsigned char bidir, unsigned char area, unsigned short flags)
471 {
472 if (m_offMeshConCount >= MAX_OFFMESH_CONNECTIONS) return;
473 float* v = &m_offMeshConVerts[m_offMeshConCount*3*2];
474 m_offMeshConRads[m_offMeshConCount] = rad;
475 m_offMeshConDirs[m_offMeshConCount] = bidir;
476 m_offMeshConAreas[m_offMeshConCount] = area;
477 m_offMeshConFlags[m_offMeshConCount] = flags;
478 m_offMeshConId[m_offMeshConCount] = 1000 + m_offMeshConCount;
479 rcVcopy(&v[0], spos);
480 rcVcopy(&v[3], epos);
481 m_offMeshConCount++;
482 }
483
484 void InputGeom::deleteOffMeshConnection(int i)
485 {
486 m_offMeshConCount--;
487 float* src = &m_offMeshConVerts[m_offMeshConCount*3*2];
488 float* dst = &m_offMeshConVerts[i*3*2];
489 rcVcopy(&dst[0], &src[0]);
490 rcVcopy(&dst[3], &src[3]);
491 m_offMeshConRads[i] = m_offMeshConRads[m_offMeshConCount];
492 m_offMeshConDirs[i] = m_offMeshConDirs[m_offMeshConCount];
493 m_offMeshConAreas[i] = m_offMeshConAreas[m_offMeshConCount];
494 m_offMeshConFlags[i] = m_offMeshConFlags[m_offMeshConCount];
495 }
496
497 void InputGeom::drawOffMeshConnections(duDebugDraw* dd, bool hilight)
498 {
499 unsigned int conColor = duRGBA(192,0,128,192);
500 unsigned int baseColor = duRGBA(0,0,0,64);
501 dd->depthMask(false);
502
503 dd->begin(DU_DRAW_LINES, 2.0f);
504 for (int i = 0; i < m_offMeshConCount; ++i)
505 {
506 float* v = &m_offMeshConVerts[i*3*2];
507
508 dd->vertex(v[0],v[1],v[2], baseColor);
509 dd->vertex(v[0],v[1]+0.2f,v[2], baseColor);
510
511 dd->vertex(v[3],v[4],v[5], baseColor);
512 dd->vertex(v[3],v[4]+0.2f,v[5], baseColor);
513
514 duAppendCircle(dd, v[0],v[1]+0.1f,v[2], m_offMeshConRads[i], baseColor);
515 duAppendCircle(dd, v[3],v[4]+0.1f,v[5], m_offMeshConRads[i], baseColor);
516
517 if (hilight)
518 {
519 duAppendArc(dd, v[0],v[1],v[2], v[3],v[4],v[5], 0.25f,
520 (m_offMeshConDirs[i]&1) ? 0.6f : 0.0f, 0.6f, conColor);
521 }
522 }
523 dd->end();
524
525 dd->depthMask(true);
526 }
527
528 void InputGeom::addConvexVolume(const float* verts, const int nverts,
529 const float minh, const float maxh, unsigned char area)
530 {
531 if (m_volumeCount >= MAX_VOLUMES) return;
532 ConvexVolume* vol = &m_volumes[m_volumeCount++];
533 memset(vol, 0, sizeof(ConvexVolume));
534 memcpy(vol->verts, verts, sizeof(float)*3*nverts);
535 vol->hmin = minh;
536 vol->hmax = maxh;
537 vol->nverts = nverts;
538 vol->area = area;
539 }
540
541 void InputGeom::deleteConvexVolume(int i)
542 {
543 m_volumeCount--;
544 m_volumes[i] = m_volumes[m_volumeCount];
545 }
546
547 void InputGeom::drawConvexVolumes(struct duDebugDraw* dd, bool /*hilight*/)
548 {
549 dd->depthMask(false);
550
551 dd->begin(DU_DRAW_TRIS);
552
553 for (int i = 0; i < m_volumeCount; ++i)
554 {
555 const ConvexVolume* vol = &m_volumes[i];
556 unsigned int col = duTransCol(dd->areaToCol(vol->area), 32);
557 for (int j = 0, k = vol->nverts-1; j < vol->nverts; k = j++)
558 {
559 const float* va = &vol->verts[k*3];
560 const float* vb = &vol->verts[j*3];
561
562 dd->vertex(vol->verts[0],vol->hmax,vol->verts[2], col);
563 dd->vertex(vb[0],vol->hmax,vb[2], col);
564 dd->vertex(va[0],vol->hmax,va[2], col);
565
566 dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col));
567 dd->vertex(va[0],vol->hmax,va[2], col);
568 dd->vertex(vb[0],vol->hmax,vb[2], col);
569
570 dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col));
571 dd->vertex(vb[0],vol->hmax,vb[2], col);
572 dd->vertex(vb[0],vol->hmin,vb[2], duDarkenCol(col));
573 }
574 }
575
576 dd->end();
577
578 dd->begin(DU_DRAW_LINES, 2.0f);
579 for (int i = 0; i < m_volumeCount; ++i)
580 {
581 const ConvexVolume* vol = &m_volumes[i];
582 unsigned int col = duTransCol(dd->areaToCol(vol->area), 220);
583 for (int j = 0, k = vol->nverts-1; j < vol->nverts; k = j++)
584 {
585 const float* va = &vol->verts[k*3];
586 const float* vb = &vol->verts[j*3];
587 dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col));
588 dd->vertex(vb[0],vol->hmin,vb[2], duDarkenCol(col));
589 dd->vertex(va[0],vol->hmax,va[2], col);
590 dd->vertex(vb[0],vol->hmax,vb[2], col);
591 dd->vertex(va[0],vol->hmin,va[2], duDarkenCol(col));
592 dd->vertex(va[0],vol->hmax,va[2], col);
593 }
594 }
595 dd->end();
596
597 dd->begin(DU_DRAW_POINTS, 3.0f);
598 for (int i = 0; i < m_volumeCount; ++i)
599 {
600 const ConvexVolume* vol = &m_volumes[i];
601 unsigned int col = duDarkenCol(duTransCol(dd->areaToCol(vol->area), 220));
602 for (int j = 0; j < vol->nverts; ++j)
603 {
604 dd->vertex(vol->verts[j*3+0],vol->verts[j*3+1]+0.1f,vol->verts[j*3+2], col);
605 dd->vertex(vol->verts[j*3+0],vol->hmin,vol->verts[j*3+2], col);
606 dd->vertex(vol->verts[j*3+0],vol->hmax,vol->verts[j*3+2], col);
607 }
608 }
609 dd->end();
610
611
612 dd->depthMask(true);
613 }