Debian Codegraph @

DetourCrowd/Source/DetourObstacleAvoidance.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //
2 // Copyright (c) 2009-2010 Mikko Mononen [email protected]
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty. In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 // claim that you wrote the original software. If you use this software
12 // in a product, an acknowledgment in the product documentation would be
13 // appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 // misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18
19 #include "DetourObstacleAvoidance.h"
20 #include "DetourCommon.h"
21 #include "DetourMath.h"
22 #include "DetourAlloc.h"
23 #include "DetourAssert.h"
24 #include <string.h>
25 #include <float.h>
26 #include <new>
27
28 static const float DT_PI = 3.14159265f;
29
30 static int sweepCircleCircle(const float* c0, const float r0, const float* v,
31 const float* c1, const float r1,
32 float& tmin, float& tmax)
33 {
34 static const float EPS = 0.0001f;
35 float s[3];
36 dtVsub(s,c1,c0);
37 float r = r0+r1;
38 float c = dtVdot2D(s,s) - r*r;
39 float a = dtVdot2D(v,v);
40 if (a < EPS) return 0; // not moving
41
42 // Overlap, calc time to exit.
43 float b = dtVdot2D(v,s);
44 float d = b*b - a*c;
45 if (d < 0.0f) return 0; // no intersection.
46 a = 1.0f / a;
47 const float rd = dtMathSqrtf(d);
48 tmin = (b - rd) * a;
49 tmax = (b + rd) * a;
50 return 1;
51 }
52
53 static int isectRaySeg(const float* ap, const float* u,
54 const float* bp, const float* bq,
55 float& t)
56 {
57 float v[3], w[3];
58 dtVsub(v,bq,bp);
59 dtVsub(w,ap,bp);
60 float d = dtVperp2D(u,v);
61 if (dtMathFabsf(d) < 1e-6f) return 0;
62 d = 1.0f/d;
63 t = dtVperp2D(v,w) * d;
64 if (t < 0 || t > 1) return 0;
65 float s = dtVperp2D(u,w) * d;
66 if (s < 0 || s > 1) return 0;
67 return 1;
68 }
69
70
71
72 dtObstacleAvoidanceDebugData* dtAllocObstacleAvoidanceDebugData()
73 {
74 void* mem = dtAlloc(sizeof(dtObstacleAvoidanceDebugData), DT_ALLOC_PERM);
75 if (!mem) return 0;
76 return new(mem) dtObstacleAvoidanceDebugData;
77 }
78
79 void dtFreeObstacleAvoidanceDebugData(dtObstacleAvoidanceDebugData* ptr)
80 {
81 if (!ptr) return;
82 ptr->~dtObstacleAvoidanceDebugData();
83 dtFree(ptr);
84 }
85
86
87 dtObstacleAvoidanceDebugData::dtObstacleAvoidanceDebugData() :
88 m_nsamples(0),
89 m_maxSamples(0),
90 m_vel(0),
91 m_ssize(0),
92 m_pen(0),
93 m_vpen(0),
94 m_vcpen(0),
95 m_spen(0),
96 m_tpen(0)
97 {
98 }
99
100 dtObstacleAvoidanceDebugData::~dtObstacleAvoidanceDebugData()
101 {
102 dtFree(m_vel);
103 dtFree(m_ssize);
104 dtFree(m_pen);
105 dtFree(m_vpen);
106 dtFree(m_vcpen);
107 dtFree(m_spen);
108 dtFree(m_tpen);
109 }
110
111 bool dtObstacleAvoidanceDebugData::init(const int maxSamples)
112 {
113 dtAssert(maxSamples);
114 m_maxSamples = maxSamples;
115
116 m_vel = (float*)dtAlloc(sizeof(float)*3*m_maxSamples, DT_ALLOC_PERM);
117 if (!m_vel)
118 return false;
119 m_pen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
120 if (!m_pen)
121 return false;
122 m_ssize = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
123 if (!m_ssize)
124 return false;
125 m_vpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
126 if (!m_vpen)
127 return false;
128 m_vcpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
129 if (!m_vcpen)
130 return false;
131 m_spen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
132 if (!m_spen)
133 return false;
134 m_tpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM);
135 if (!m_tpen)
136 return false;
137
138 return true;
139 }
140
141 void dtObstacleAvoidanceDebugData::reset()
142 {
143 m_nsamples = 0;
144 }
145
146 void dtObstacleAvoidanceDebugData::addSample(const float* vel, const float ssize, const float pen,
147 const float vpen, const float vcpen, const float spen, const float tpen)
148 {
149 if (m_nsamples >= m_maxSamples)
150 return;
151 dtAssert(m_vel);
152 dtAssert(m_ssize);
153 dtAssert(m_pen);
154 dtAssert(m_vpen);
155 dtAssert(m_vcpen);
156 dtAssert(m_spen);
157 dtAssert(m_tpen);
158 dtVcopy(&m_vel[m_nsamples*3], vel);
159 m_ssize[m_nsamples] = ssize;
160 m_pen[m_nsamples] = pen;
161 m_vpen[m_nsamples] = vpen;
162 m_vcpen[m_nsamples] = vcpen;
163 m_spen[m_nsamples] = spen;
164 m_tpen[m_nsamples] = tpen;
165 m_nsamples++;
166 }
167
168 static void normalizeArray(float* arr, const int n)
169 {
170 // Normalize penaly range.
171 float minPen = FLT_MAX;
172 float maxPen = -FLT_MAX;
173 for (int i = 0; i < n; ++i)
174 {
175 minPen = dtMin(minPen, arr[i]);
176 maxPen = dtMax(maxPen, arr[i]);
177 }
178 const float penRange = maxPen-minPen;
179 const float s = penRange > 0.001f ? (1.0f / penRange) : 1;
180 for (int i = 0; i < n; ++i)
181 arr[i] = dtClamp((arr[i]-minPen)*s, 0.0f, 1.0f);
182 }
183
184 void dtObstacleAvoidanceDebugData::normalizeSamples()
185 {
186 normalizeArray(m_pen, m_nsamples);
187 normalizeArray(m_vpen, m_nsamples);
188 normalizeArray(m_vcpen, m_nsamples);
189 normalizeArray(m_spen, m_nsamples);
190 normalizeArray(m_tpen, m_nsamples);
191 }
192
193
194 dtObstacleAvoidanceQuery* dtAllocObstacleAvoidanceQuery()
195 {
196 void* mem = dtAlloc(sizeof(dtObstacleAvoidanceQuery), DT_ALLOC_PERM);
197 if (!mem) return 0;
198 return new(mem) dtObstacleAvoidanceQuery;
199 }
200
201 void dtFreeObstacleAvoidanceQuery(dtObstacleAvoidanceQuery* ptr)
202 {
203 if (!ptr) return;
204 ptr->~dtObstacleAvoidanceQuery();
205 dtFree(ptr);
206 }
207
208
209 dtObstacleAvoidanceQuery::dtObstacleAvoidanceQuery() :
210 m_invHorizTime(0),
211 m_vmax(0),
212 m_invVmax(0),
213 m_maxCircles(0),
214 m_circles(0),
215 m_ncircles(0),
216 m_maxSegments(0),
217 m_segments(0),
218 m_nsegments(0)
219 {
220 }
221
222 dtObstacleAvoidanceQuery::~dtObstacleAvoidanceQuery()
223 {
224 dtFree(m_circles);
225 dtFree(m_segments);
226 }
227
228 bool dtObstacleAvoidanceQuery::init(const int maxCircles, const int maxSegments)
229 {
230 m_maxCircles = maxCircles;
231 m_ncircles = 0;
232 m_circles = (dtObstacleCircle*)dtAlloc(sizeof(dtObstacleCircle)*m_maxCircles, DT_ALLOC_PERM);
233 if (!m_circles)
234 return false;
235 memset(m_circles, 0, sizeof(dtObstacleCircle)*m_maxCircles);
236
237 m_maxSegments = maxSegments;
238 m_nsegments = 0;
239 m_segments = (dtObstacleSegment*)dtAlloc(sizeof(dtObstacleSegment)*m_maxSegments, DT_ALLOC_PERM);
240 if (!m_segments)
241 return false;
242 memset(m_segments, 0, sizeof(dtObstacleSegment)*m_maxSegments);
243
244 return true;
245 }
246
247 void dtObstacleAvoidanceQuery::reset()
248 {
249 m_ncircles = 0;
250 m_nsegments = 0;
251 }
252
253 void dtObstacleAvoidanceQuery::addCircle(const float* pos, const float rad,
254 const float* vel, const float* dvel)
255 {
256 if (m_ncircles >= m_maxCircles)
257 return;
258
259 dtObstacleCircle* cir = &m_circles[m_ncircles++];
260 dtVcopy(cir->p, pos);
261 cir->rad = rad;
262 dtVcopy(cir->vel, vel);
263 dtVcopy(cir->dvel, dvel);
264 }
265
266 void dtObstacleAvoidanceQuery::addSegment(const float* p, const float* q)
267 {
268 if (m_nsegments >= m_maxSegments)
269 return;
270
271 dtObstacleSegment* seg = &m_segments[m_nsegments++];
272 dtVcopy(seg->p, p);
273 dtVcopy(seg->q, q);
274 }
275
276 void dtObstacleAvoidanceQuery::prepare(const float* pos, const float* dvel)
277 {
278 // Prepare obstacles
279 for (int i = 0; i < m_ncircles; ++i)
280 {
281 dtObstacleCircle* cir = &m_circles[i];
282
283 // Side
284 const float* pa = pos;
285 const float* pb = cir->p;
286
287 const float orig[3] = {0,0,0};
288 float dv[3];
289 dtVsub(cir->dp,pb,pa);
290 dtVnormalize(cir->dp);
291 dtVsub(dv, cir->dvel, dvel);
292
293 const float a = dtTriArea2D(orig, cir->dp,dv);
294 if (a < 0.01f)
295 {
296 cir->np[0] = -cir->dp[2];
297 cir->np[2] = cir->dp[0];
298 }
299 else
300 {
301 cir->np[0] = cir->dp[2];
302 cir->np[2] = -cir->dp[0];
303 }
304 }
305
306 for (int i = 0; i < m_nsegments; ++i)
307 {
308 dtObstacleSegment* seg = &m_segments[i];
309
310 // Precalc if the agent is really close to the segment.
311 const float r = 0.01f;
312 float t;
313 seg->touch = dtDistancePtSegSqr2D(pos, seg->p, seg->q, t) < dtSqr(r);
314 }
315 }
316
317
318 /* Calculate the collision penalty for a given velocity vector
319 *
320 * @param vcand sampled velocity
321 * @param dvel desired velocity
322 * @param minPenalty threshold penalty for early out
323 */
324 float dtObstacleAvoidanceQuery::processSample(const float* vcand, const float cs,
325 const float* pos, const float rad,
326 const float* vel, const float* dvel,
327 const float minPenalty,
328 dtObstacleAvoidanceDebugData* debug)
329 {
330 // penalty for straying away from the desired and current velocities
331 const float vpen = m_params.weightDesVel * (dtVdist2D(vcand, dvel) * m_invVmax);
332 const float vcpen = m_params.weightCurVel * (dtVdist2D(vcand, vel) * m_invVmax);
333
334 // find the threshold hit time to bail out based on the early out penalty
335 // (see how the penalty is calculated below to understnad)
336 float minPen = minPenalty - vpen - vcpen;
337 float tThresold = (m_params.weightToi / minPen - 0.1f) * m_params.horizTime;
338 if (tThresold - m_params.horizTime > -FLT_EPSILON)
339 return minPenalty; // already too much
340
341 // Find min time of impact and exit amongst all obstacles.
342 float tmin = m_params.horizTime;
343 float side = 0;
344 int nside = 0;
345
346 for (int i = 0; i < m_ncircles; ++i)
347 {
348 const dtObstacleCircle* cir = &m_circles[i];
349
350 // RVO
351 float vab[3];
352 dtVscale(vab, vcand, 2);
353 dtVsub(vab, vab, vel);
354 dtVsub(vab, vab, cir->vel);
355
356 // Side
357 side += dtClamp(dtMin(dtVdot2D(cir->dp,vab)*0.5f+0.5f, dtVdot2D(cir->np,vab)*2), 0.0f, 1.0f);
358 nside++;
359
360 float htmin = 0, htmax = 0;
361 if (!sweepCircleCircle(pos,rad, vab, cir->p,cir->rad, htmin, htmax))
362 continue;
363
364 // Handle overlapping obstacles.
365 if (htmin < 0.0f && htmax > 0.0f)
366 {
367 // Avoid more when overlapped.
368 htmin = -htmin * 0.5f;
369 }
370
371 if (htmin >= 0.0f)
372 {
373 // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
374 if (htmin < tmin)
375 {
376 tmin = htmin;
377 if (tmin < tThresold)
378 return minPenalty;
379 }
380 }
381 }
382
383 for (int i = 0; i < m_nsegments; ++i)
384 {
385 const dtObstacleSegment* seg = &m_segments[i];
386 float htmin = 0;
387
388 if (seg->touch)
389 {
390 // Special case when the agent is very close to the segment.
391 float sdir[3], snorm[3];
392 dtVsub(sdir, seg->q, seg->p);
393 snorm[0] = -sdir[2];
394 snorm[2] = sdir[0];
395 // If the velocity is pointing towards the segment, no collision.
396 if (dtVdot2D(snorm, vcand) < 0.0f)
397 continue;
398 // Else immediate collision.
399 htmin = 0.0f;
400 }
401 else
402 {
403 if (!isectRaySeg(pos, vcand, seg->p, seg->q, htmin))
404 continue;
405 }
406
407 // Avoid less when facing walls.
408 htmin *= 2.0f;
409
410 // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
411 if (htmin < tmin)
412 {
413 tmin = htmin;
414 if (tmin < tThresold)
415 return minPenalty;
416 }
417 }
418
419 // Normalize side bias, to prevent it dominating too much.
420 if (nside)
421 side /= nside;
422
423 const float spen = m_params.weightSide * side;
424 const float tpen = m_params.weightToi * (1.0f/(0.1f+tmin*m_invHorizTime));
425
426 const float penalty = vpen + vcpen + spen + tpen;
427
428 // Store different penalties for debug viewing
429 if (debug)
430 debug->addSample(vcand, cs, penalty, vpen, vcpen, spen, tpen);
431
432 return penalty;
433 }
434
435 int dtObstacleAvoidanceQuery::sampleVelocityGrid(const float* pos, const float rad, const float vmax,
436 const float* vel, const float* dvel, float* nvel,
437 const dtObstacleAvoidanceParams* params,
438 dtObstacleAvoidanceDebugData* debug)
439 {
440 prepare(pos, dvel);
441
442 memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
443 m_invHorizTime = 1.0f / m_params.horizTime;
444 m_vmax = vmax;
445 m_invVmax = vmax > 0 ? 1.0f / vmax : FLT_MAX;
446
447 dtVset(nvel, 0,0,0);
448
449 if (debug)
450 debug->reset();
451
452 const float cvx = dvel[0] * m_params.velBias;
453 const float cvz = dvel[2] * m_params.velBias;
454 const float cs = vmax * 2 * (1 - m_params.velBias) / (float)(m_params.gridSize-1);
455 const float half = (m_params.gridSize-1)*cs*0.5f;
456
457 float minPenalty = FLT_MAX;
458 int ns = 0;
459
460 for (int y = 0; y < m_params.gridSize; ++y)
461 {
462 for (int x = 0; x < m_params.gridSize; ++x)
463 {
464 float vcand[3];
465 vcand[0] = cvx + x*cs - half;
466 vcand[1] = 0;
467 vcand[2] = cvz + y*cs - half;
468
469 if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+cs/2)) continue;
470
471 const float penalty = processSample(vcand, cs, pos,rad,vel,dvel, minPenalty, debug);
472 ns++;
473 if (penalty < minPenalty)
474 {
475 minPenalty = penalty;
476 dtVcopy(nvel, vcand);
477 }
478 }
479 }
480
481 return ns;
482 }
483
484
485 // vector normalization that ignores the y-component.
486 inline void dtNormalize2D(float* v)
487 {
488 float d = dtMathSqrtf(v[0] * v[0] + v[2] * v[2]);
489 if (d==0)
490 return;
491 d = 1.0f / d;
492 v[0] *= d;
493 v[2] *= d;
494 }
495
496 // vector normalization that ignores the y-component.
497 inline void dtRorate2D(float* dest, const float* v, float ang)
498 {
499 float c = cosf(ang);
500 float s = sinf(ang);
501 dest[0] = v[0]*c - v[2]*s;
502 dest[2] = v[0]*s + v[2]*c;
503 dest[1] = v[1];
504 }
505
506
507 int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax,
508 const float* vel, const float* dvel, float* nvel,
509 const dtObstacleAvoidanceParams* params,
510 dtObstacleAvoidanceDebugData* debug)
511 {
512 prepare(pos, dvel);
513
514 memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
515 m_invHorizTime = 1.0f / m_params.horizTime;
516 m_vmax = vmax;
517 m_invVmax = vmax > 0 ? 1.0f / vmax : FLT_MAX;
518
519 dtVset(nvel, 0,0,0);
520
521 if (debug)
522 debug->reset();
523
524 // Build sampling pattern aligned to desired velocity.
525 float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2];
526 int npat = 0;
527
528 const int ndivs = (int)m_params.adaptiveDivs;
529 const int nrings= (int)m_params.adaptiveRings;
530 const int depth = (int)m_params.adaptiveDepth;
531
532 const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS);
533 const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS);
534 const float da = (1.0f/nd) * DT_PI*2;
535 const float ca = cosf(da);
536 const float sa = sinf(da);
537
538 // desired direction
539 float ddir[6];
540 dtVcopy(ddir, dvel);
541 dtNormalize2D(ddir);
542 dtRorate2D (ddir+3, ddir, da*0.5f); // rotated by da/2
543
544 // Always add sample at zero
545 pat[npat*2+0] = 0;
546 pat[npat*2+1] = 0;
547 npat++;
548
549 for (int j = 0; j < nr; ++j)
550 {
551 const float r = (float)(nr-j)/(float)nr;
552 pat[npat*2+0] = ddir[(j%2)*3] * r;
553 pat[npat*2+1] = ddir[(j%2)*3+2] * r;
554 float* last1 = pat + npat*2;
555 float* last2 = last1;
556 npat++;
557
558 for (int i = 1; i < nd-1; i+=2)
559 {
560 // get next point on the "right" (rotate CW)
561 pat[npat*2+0] = last1[0]*ca + last1[1]*sa;
562 pat[npat*2+1] = -last1[0]*sa + last1[1]*ca;
563 // get next point on the "left" (rotate CCW)
564 pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
565 pat[npat*2+3] = last2[0]*sa + last2[1]*ca;
566
567 last1 = pat + npat*2;
568 last2 = last1 + 2;
569 npat += 2;
570 }
571
572 if ((nd&1) == 0)
573 {
574 pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
575 pat[npat*2+3] = last2[0]*sa + last2[1]*ca;
576 npat++;
577 }
578 }
579
580
581 // Start sampling.
582 float cr = vmax * (1.0f - m_params.velBias);
583 float res[3];
584 dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias);
585 int ns = 0;
586
587 for (int k = 0; k < depth; ++k)
588 {
589 float minPenalty = FLT_MAX;
590 float bvel[3];
591 dtVset(bvel, 0,0,0);
592
593 for (int i = 0; i < npat; ++i)
594 {
595 float vcand[3];
596 vcand[0] = res[0] + pat[i*2+0]*cr;
597 vcand[1] = 0;
598 vcand[2] = res[2] + pat[i*2+1]*cr;
599
600 if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue;
601
602 const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, minPenalty, debug);
603 ns++;
604 if (penalty < minPenalty)
605 {
606 minPenalty = penalty;
607 dtVcopy(bvel, vcand);
608 }
609 }
610
611 dtVcopy(res, bvel);
612
613 cr *= 0.5f;
614 }
615
616 dtVcopy(nvel, res);
617
618 return ns;
619 }