Debian Codegraph @

DetourCrowd/Source/DetourCrowd.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 <string.h>
20 #include <float.h>
21 #include <stdlib.h>
22 #include <new>
23 #include "DetourCrowd.h"
24 #include "DetourNavMesh.h"
25 #include "DetourNavMeshQuery.h"
26 #include "DetourObstacleAvoidance.h"
27 #include "DetourCommon.h"
28 #include "DetourMath.h"
29 #include "DetourAssert.h"
30 #include "DetourAlloc.h"
31
32
33 dtCrowd* dtAllocCrowd()
34 {
35 void* mem = dtAlloc(sizeof(dtCrowd), DT_ALLOC_PERM);
36 if (!mem) return 0;
37 return new(mem) dtCrowd;
38 }
39
40 void dtFreeCrowd(dtCrowd* ptr)
41 {
42 if (!ptr) return;
43 ptr->~dtCrowd();
44 dtFree(ptr);
45 }
46
47
48 static const int MAX_ITERS_PER_UPDATE = 100;
49
50 static const int MAX_PATHQUEUE_NODES = 4096;
51 static const int MAX_COMMON_NODES = 512;
52
53 inline float tween(const float t, const float t0, const float t1)
54 {
55 return dtClamp((t-t0) / (t1-t0), 0.0f, 1.0f);
56 }
57
58 static void integrate(dtCrowdAgent* ag, const float dt)
59 {
60 // Fake dynamic constraint.
61 const float maxDelta = ag->params.maxAcceleration * dt;
62 float dv[3];
63 dtVsub(dv, ag->nvel, ag->vel);
64 float ds = dtVlen(dv);
65 if (ds > maxDelta)
66 dtVscale(dv, dv, maxDelta/ds);
67 dtVadd(ag->vel, ag->vel, dv);
68
69 // Integrate
70 if (dtVlen(ag->vel) > 0.0001f)
71 dtVmad(ag->npos, ag->npos, ag->vel, dt);
72 else
73 dtVset(ag->vel,0,0,0);
74 }
75
76 static bool overOffmeshConnection(const dtCrowdAgent* ag, const float radius)
77 {
78 if (!ag->ncorners)
79 return false;
80
81 const bool offMeshConnection = (ag->cornerFlags[ag->ncorners-1] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) ? true : false;
82 if (offMeshConnection)
83 {
84 const float distSq = dtVdist2DSqr(ag->npos, &ag->cornerVerts[(ag->ncorners-1)*3]);
85 if (distSq < radius*radius)
86 return true;
87 }
88
89 return false;
90 }
91
92 static float getDistanceToGoal(const dtCrowdAgent* ag, const float range)
93 {
94 if (!ag->ncorners)
95 return range;
96
97 const bool endOfPath = (ag->cornerFlags[ag->ncorners-1] & DT_STRAIGHTPATH_END) ? true : false;
98 if (endOfPath)
99 return dtMin(dtVdist2D(ag->npos, &ag->cornerVerts[(ag->ncorners-1)*3]), range);
100
101 return range;
102 }
103
104 static void calcSmoothSteerDirection(const dtCrowdAgent* ag, float* dir)
105 {
106 if (!ag->ncorners)
107 {
108 dtVset(dir, 0,0,0);
109 return;
110 }
111
112 const int ip0 = 0;
113 const int ip1 = dtMin(1, ag->ncorners-1);
114 const float* p0 = &ag->cornerVerts[ip0*3];
115 const float* p1 = &ag->cornerVerts[ip1*3];
116
117 float dir0[3], dir1[3];
118 dtVsub(dir0, p0, ag->npos);
119 dtVsub(dir1, p1, ag->npos);
120 dir0[1] = 0;
121 dir1[1] = 0;
122
123 float len0 = dtVlen(dir0);
124 float len1 = dtVlen(dir1);
125 if (len1 > 0.001f)
126 dtVscale(dir1,dir1,1.0f/len1);
127
128 dir[0] = dir0[0] - dir1[0]*len0*0.5f;
129 dir[1] = 0;
130 dir[2] = dir0[2] - dir1[2]*len0*0.5f;
131
132 dtVnormalize(dir);
133 }
134
135 static void calcStraightSteerDirection(const dtCrowdAgent* ag, float* dir)
136 {
137 if (!ag->ncorners)
138 {
139 dtVset(dir, 0,0,0);
140 return;
141 }
142 dtVsub(dir, &ag->cornerVerts[0], ag->npos);
143 dir[1] = 0;
144 dtVnormalize(dir);
145 }
146
147 static int addNeighbour(const int idx, const float dist,
148 dtCrowdNeighbour* neis, const int nneis, const int maxNeis)
149 {
150 // Insert neighbour based on the distance.
151 dtCrowdNeighbour* nei = 0;
152 if (!nneis)
153 {
154 nei = &neis[nneis];
155 }
156 else if (dist >= neis[nneis-1].dist)
157 {
158 if (nneis >= maxNeis)
159 return nneis;
160 nei = &neis[nneis];
161 }
162 else
163 {
164 int i;
165 for (i = 0; i < nneis; ++i)
166 if (dist <= neis[i].dist)
167 break;
168
169 const int tgt = i+1;
170 const int n = dtMin(nneis-i, maxNeis-tgt);
171
172 dtAssert(tgt+n <= maxNeis);
173
174 if (n > 0)
175 memmove(&neis[tgt], &neis[i], sizeof(dtCrowdNeighbour)*n);
176 nei = &neis[i];
177 }
178
179 memset(nei, 0, sizeof(dtCrowdNeighbour));
180
181 nei->idx = idx;
182 nei->dist = dist;
183
184 return dtMin(nneis+1, maxNeis);
185 }
186
187 static int getNeighbours(const float* pos, const float height, const float range,
188 const dtCrowdAgent* skip, dtCrowdNeighbour* result, const int maxResult,
189 dtCrowdAgent** agents, const int /*nagents*/, dtProximityGrid* grid)
190 {
191 int n = 0;
192
193 static const int MAX_NEIS = 32;
194 unsigned short ids[MAX_NEIS];
195 int nids = grid->queryItems(pos[0]-range, pos[2]-range,
196 pos[0]+range, pos[2]+range,
197 ids, MAX_NEIS);
198
199 for (int i = 0; i < nids; ++i)
200 {
201 const dtCrowdAgent* ag = agents[ids[i]];
202
203 if (ag == skip) continue;
204
205 // Check for overlap.
206 float diff[3];
207 dtVsub(diff, pos, ag->npos);
208 if (dtMathFabsf(diff[1]) >= (height+ag->params.height)/2.0f)
209 continue;
210 diff[1] = 0;
211 const float distSqr = dtVlenSqr(diff);
212 if (distSqr > dtSqr(range))
213 continue;
214
215 n = addNeighbour(ids[i], distSqr, result, n, maxResult);
216 }
217 return n;
218 }
219
220 static int addToOptQueue(dtCrowdAgent* newag, dtCrowdAgent** agents, const int nagents, const int maxAgents)
221 {
222 // Insert neighbour based on greatest time.
223 int slot = 0;
224 if (!nagents)
225 {
226 slot = nagents;
227 }
228 else if (newag->topologyOptTime <= agents[nagents-1]->topologyOptTime)
229 {
230 if (nagents >= maxAgents)
231 return nagents;
232 slot = nagents;
233 }
234 else
235 {
236 int i;
237 for (i = 0; i < nagents; ++i)
238 if (newag->topologyOptTime >= agents[i]->topologyOptTime)
239 break;
240
241 const int tgt = i+1;
242 const int n = dtMin(nagents-i, maxAgents-tgt);
243
244 dtAssert(tgt+n <= maxAgents);
245
246 if (n > 0)
247 memmove(&agents[tgt], &agents[i], sizeof(dtCrowdAgent*)*n);
248 slot = i;
249 }
250
251 agents[slot] = newag;
252
253 return dtMin(nagents+1, maxAgents);
254 }
255
256 static int addToPathQueue(dtCrowdAgent* newag, dtCrowdAgent** agents, const int nagents, const int maxAgents)
257 {
258 // Insert neighbour based on greatest time.
259 int slot = 0;
260 if (!nagents)
261 {
262 slot = nagents;
263 }
264 else if (newag->targetReplanTime <= agents[nagents-1]->targetReplanTime)
265 {
266 if (nagents >= maxAgents)
267 return nagents;
268 slot = nagents;
269 }
270 else
271 {
272 int i;
273 for (i = 0; i < nagents; ++i)
274 if (newag->targetReplanTime >= agents[i]->targetReplanTime)
275 break;
276
277 const int tgt = i+1;
278 const int n = dtMin(nagents-i, maxAgents-tgt);
279
280 dtAssert(tgt+n <= maxAgents);
281
282 if (n > 0)
283 memmove(&agents[tgt], &agents[i], sizeof(dtCrowdAgent*)*n);
284 slot = i;
285 }
286
287 agents[slot] = newag;
288
289 return dtMin(nagents+1, maxAgents);
290 }
291
292
293 /**
294 @class dtCrowd
295 @par
296
297 This is the core class of the @ref crowd module. See the @ref crowd documentation for a summary
298 of the crowd features.
299
300 A common method for setting up the crowd is as follows:
301
302 -# Allocate the crowd using #dtAllocCrowd.
303 -# Initialize the crowd using #init().
304 -# Set the avoidance configurations using #setObstacleAvoidanceParams().
305 -# Add agents using #addAgent() and make an initial movement request using #requestMoveTarget().
306
307 A common process for managing the crowd is as follows:
308
309 -# Call #update() to allow the crowd to manage its agents.
310 -# Retrieve agent information using #getActiveAgents().
311 -# Make movement requests using #requestMoveTarget() when movement goal changes.
312 -# Repeat every frame.
313
314 Some agent configuration settings can be updated using #updateAgentParameters(). But the crowd owns the
315 agent position. So it is not possible to update an active agent's position. If agent position
316 must be fed back into the crowd, the agent must be removed and re-added.
317
318 Notes:
319
320 - Path related information is available for newly added agents only after an #update() has been
321 performed.
322 - Agent objects are kept in a pool and re-used. So it is important when using agent objects to check the value of
323 #dtCrowdAgent::active to determine if the agent is actually in use or not.
324 - This class is meant to provide 'local' movement. There is a limit of 256 polygons in the path corridor.
325 So it is not meant to provide automatic pathfinding services over long distances.
326
327 @see dtAllocCrowd(), dtFreeCrowd(), init(), dtCrowdAgent
328
329 */
330
331 dtCrowd::dtCrowd() :
332 m_maxAgents(0),
333 m_agents(0),
334 m_activeAgents(0),
335 m_agentAnims(0),
336 m_obstacleQuery(0),
337 m_grid(0),
338 m_pathResult(0),
339 m_maxPathResult(0),
340 m_maxAgentRadius(0),
341 m_velocitySampleCount(0),
342 m_navquery(0)
343 {
344 }
345
346 dtCrowd::~dtCrowd()
347 {
348 purge();
349 }
350
351 void dtCrowd::purge()
352 {
353 for (int i = 0; i < m_maxAgents; ++i)
354 m_agents[i].~dtCrowdAgent();
355 dtFree(m_agents);
356 m_agents = 0;
357 m_maxAgents = 0;
358
359 dtFree(m_activeAgents);
360 m_activeAgents = 0;
361
362 dtFree(m_agentAnims);
363 m_agentAnims = 0;
364
365 dtFree(m_pathResult);
366 m_pathResult = 0;
367
368 dtFreeProximityGrid(m_grid);
369 m_grid = 0;
370
371 dtFreeObstacleAvoidanceQuery(m_obstacleQuery);
372 m_obstacleQuery = 0;
373
374 dtFreeNavMeshQuery(m_navquery);
375 m_navquery = 0;
376 }
377
378 /// @par
379 ///
380 /// May be called more than once to purge and re-initialize the crowd.
381 bool dtCrowd::init(const int maxAgents, const float maxAgentRadius, dtNavMesh* nav)
382 {
383 purge();
384
385 m_maxAgents = maxAgents;
386 m_maxAgentRadius = maxAgentRadius;
387
388 // Larger than agent radius because it is also used for agent recovery.
389 dtVset(m_agentPlacementHalfExtents, m_maxAgentRadius*2.0f, m_maxAgentRadius*1.5f, m_maxAgentRadius*2.0f);
390
391 m_grid = dtAllocProximityGrid();
392 if (!m_grid)
393 return false;
394 if (!m_grid->init(m_maxAgents*4, maxAgentRadius*3))
395 return false;
396
397 m_obstacleQuery = dtAllocObstacleAvoidanceQuery();
398 if (!m_obstacleQuery)
399 return false;
400 if (!m_obstacleQuery->init(6, 8))
401 return false;
402
403 // Init obstacle query params.
404 memset(m_obstacleQueryParams, 0, sizeof(m_obstacleQueryParams));
405 for (int i = 0; i < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS; ++i)
406 {
407 dtObstacleAvoidanceParams* params = &m_obstacleQueryParams[i];
408 params->velBias = 0.4f;
409 params->weightDesVel = 2.0f;
410 params->weightCurVel = 0.75f;
411 params->weightSide = 0.75f;
412 params->weightToi = 2.5f;
413 params->horizTime = 2.5f;
414 params->gridSize = 33;
415 params->adaptiveDivs = 7;
416 params->adaptiveRings = 2;
417 params->adaptiveDepth = 5;
418 }
419
420 // Allocate temp buffer for merging paths.
421 m_maxPathResult = 256;
422 m_pathResult = (dtPolyRef*)dtAlloc(sizeof(dtPolyRef)*m_maxPathResult, DT_ALLOC_PERM);
423 if (!m_pathResult)
424 return false;
425
426 if (!m_pathq.init(m_maxPathResult, MAX_PATHQUEUE_NODES, nav))
427 return false;
428
429 m_agents = (dtCrowdAgent*)dtAlloc(sizeof(dtCrowdAgent)*m_maxAgents, DT_ALLOC_PERM);
430 if (!m_agents)
431 return false;
432
433 m_activeAgents = (dtCrowdAgent**)dtAlloc(sizeof(dtCrowdAgent*)*m_maxAgents, DT_ALLOC_PERM);
434 if (!m_activeAgents)
435 return false;
436
437 m_agentAnims = (dtCrowdAgentAnimation*)dtAlloc(sizeof(dtCrowdAgentAnimation)*m_maxAgents, DT_ALLOC_PERM);
438 if (!m_agentAnims)
439 return false;
440
441 for (int i = 0; i < m_maxAgents; ++i)
442 {
443 new(&m_agents[i]) dtCrowdAgent();
444 m_agents[i].active = false;
445 if (!m_agents[i].corridor.init(m_maxPathResult))
446 return false;
447 }
448
449 for (int i = 0; i < m_maxAgents; ++i)
450 {
451 m_agentAnims[i].active = false;
452 }
453
454 // The navquery is mostly used for local searches, no need for large node pool.
455 m_navquery = dtAllocNavMeshQuery();
456 if (!m_navquery)
457 return false;
458 if (dtStatusFailed(m_navquery->init(nav, MAX_COMMON_NODES)))
459 return false;
460
461 return true;
462 }
463
464 void dtCrowd::setObstacleAvoidanceParams(const int idx, const dtObstacleAvoidanceParams* params)
465 {
466 if (idx >= 0 && idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)
467 memcpy(&m_obstacleQueryParams[idx], params, sizeof(dtObstacleAvoidanceParams));
468 }
469
470 const dtObstacleAvoidanceParams* dtCrowd::getObstacleAvoidanceParams(const int idx) const
471 {
472 if (idx >= 0 && idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)
473 return &m_obstacleQueryParams[idx];
474 return 0;
475 }
476
477 int dtCrowd::getAgentCount() const
478 {
479 return m_maxAgents;
480 }
481
482 /// @par
483 ///
484 /// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
485 const dtCrowdAgent* dtCrowd::getAgent(const int idx)
486 {
487 if (idx < 0 || idx >= m_maxAgents)
488 return 0;
489 return &m_agents[idx];
490 }
491
492 ///
493 /// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
494 dtCrowdAgent* dtCrowd::getEditableAgent(const int idx)
495 {
496 if (idx < 0 || idx >= m_maxAgents)
497 return 0;
498 return &m_agents[idx];
499 }
500
501 void dtCrowd::updateAgentParameters(const int idx, const dtCrowdAgentParams* params)
502 {
503 if (idx < 0 || idx >= m_maxAgents)
504 return;
505 memcpy(&m_agents[idx].params, params, sizeof(dtCrowdAgentParams));
506 }
507
508 /// @par
509 ///
510 /// The agent's position will be constrained to the surface of the navigation mesh.
511 int dtCrowd::addAgent(const float* pos, const dtCrowdAgentParams* params)
512 {
513 // Find empty slot.
514 int idx = -1;
515 for (int i = 0; i < m_maxAgents; ++i)
516 {
517 if (!m_agents[i].active)
518 {
519 idx = i;
520 break;
521 }
522 }
523 if (idx == -1)
524 return -1;
525
526 dtCrowdAgent* ag = &m_agents[idx];
527
528 updateAgentParameters(idx, params);
529
530 // Find nearest position on navmesh and place the agent there.
531 float nearest[3];
532 dtPolyRef ref = 0;
533 dtVcopy(nearest, pos);
534 dtStatus status = m_navquery->findNearestPoly(pos, m_agentPlacementHalfExtents, &m_filters[ag->params.queryFilterType], &ref, nearest);
535 if (dtStatusFailed(status))
536 {
537 dtVcopy(nearest, pos);
538 ref = 0;
539 }
540
541 ag->corridor.reset(ref, nearest);
542 ag->boundary.reset();
543 ag->partial = false;
544
545 ag->topologyOptTime = 0;
546 ag->targetReplanTime = 0;
547 ag->nneis = 0;
548
549 dtVset(ag->dvel, 0,0,0);
550 dtVset(ag->nvel, 0,0,0);
551 dtVset(ag->vel, 0,0,0);
552 dtVcopy(ag->npos, nearest);
553
554 ag->desiredSpeed = 0;
555
556 if (ref)
557 ag->state = DT_CROWDAGENT_STATE_WALKING;
558 else
559 ag->state = DT_CROWDAGENT_STATE_INVALID;
560
561 ag->targetState = DT_CROWDAGENT_TARGET_NONE;
562
563 ag->active = true;
564
565 return idx;
566 }
567
568 /// @par
569 ///
570 /// The agent is deactivated and will no longer be processed. Its #dtCrowdAgent object
571 /// is not removed from the pool. It is marked as inactive so that it is available for reuse.
572 void dtCrowd::removeAgent(const int idx)
573 {
574 if (idx >= 0 && idx < m_maxAgents)
575 {
576 m_agents[idx].active = false;
577 }
578 }
579
580 bool dtCrowd::requestMoveTargetReplan(const int idx, dtPolyRef ref, const float* pos)
581 {
582 if (idx < 0 || idx >= m_maxAgents)
583 return false;
584
585 dtCrowdAgent* ag = &m_agents[idx];
586
587 // Initialize request.
588 ag->targetRef = ref;
589 dtVcopy(ag->targetPos, pos);
590 ag->targetPathqRef = DT_PATHQ_INVALID;
591 ag->targetReplan = true;
592 if (ag->targetRef)
593 ag->targetState = DT_CROWDAGENT_TARGET_REQUESTING;
594 else
595 ag->targetState = DT_CROWDAGENT_TARGET_FAILED;
596
597 return true;
598 }
599
600 /// @par
601 ///
602 /// This method is used when a new target is set.
603 ///
604 /// The position will be constrained to the surface of the navigation mesh.
605 ///
606 /// The request will be processed during the next #update().
607 bool dtCrowd::requestMoveTarget(const int idx, dtPolyRef ref, const float* pos)
608 {
609 if (idx < 0 || idx >= m_maxAgents)
610 return false;
611 if (!ref)
612 return false;
613
614 dtCrowdAgent* ag = &m_agents[idx];
615
616 // Initialize request.
617 ag->targetRef = ref;
618 dtVcopy(ag->targetPos, pos);
619 ag->targetPathqRef = DT_PATHQ_INVALID;
620 ag->targetReplan = false;
621 if (ag->targetRef)
622 ag->targetState = DT_CROWDAGENT_TARGET_REQUESTING;
623 else
624 ag->targetState = DT_CROWDAGENT_TARGET_FAILED;
625
626 return true;
627 }
628
629 bool dtCrowd::requestMoveVelocity(const int idx, const float* vel)
630 {
631 if (idx < 0 || idx >= m_maxAgents)
632 return false;
633
634 dtCrowdAgent* ag = &m_agents[idx];
635
636 // Initialize request.
637 ag->targetRef = 0;
638 dtVcopy(ag->targetPos, vel);
639 ag->targetPathqRef = DT_PATHQ_INVALID;
640 ag->targetReplan = false;
641 ag->targetState = DT_CROWDAGENT_TARGET_VELOCITY;
642
643 return true;
644 }
645
646 bool dtCrowd::resetMoveTarget(const int idx)
647 {
648 if (idx < 0 || idx >= m_maxAgents)
649 return false;
650
651 dtCrowdAgent* ag = &m_agents[idx];
652
653 // Initialize request.
654 ag->targetRef = 0;
655 dtVset(ag->targetPos, 0,0,0);
656 dtVset(ag->dvel, 0,0,0);
657 ag->targetPathqRef = DT_PATHQ_INVALID;
658 ag->targetReplan = false;
659 ag->targetState = DT_CROWDAGENT_TARGET_NONE;
660
661 return true;
662 }
663
664 int dtCrowd::getActiveAgents(dtCrowdAgent** agents, const int maxAgents)
665 {
666 int n = 0;
667 for (int i = 0; i < m_maxAgents; ++i)
668 {
669 if (!m_agents[i].active) continue;
670 if (n < maxAgents)
671 agents[n++] = &m_agents[i];
672 }
673 return n;
674 }
675
676
677 void dtCrowd::updateMoveRequest(const float /*dt*/)
678 {
679 const int PATH_MAX_AGENTS = 8;
680 dtCrowdAgent* queue[PATH_MAX_AGENTS];
681 int nqueue = 0;
682
683 // Fire off new requests.
684 for (int i = 0; i < m_maxAgents; ++i)
685 {
686 dtCrowdAgent* ag = &m_agents[i];
687 if (!ag->active)
688 continue;
689 if (ag->state == DT_CROWDAGENT_STATE_INVALID)
690 continue;
691 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
692 continue;
693
694 if (ag->targetState == DT_CROWDAGENT_TARGET_REQUESTING)
695 {
696 const dtPolyRef* path = ag->corridor.getPath();
697 const int npath = ag->corridor.getPathCount();
698 dtAssert(npath);
699
700 static const int MAX_RES = 32;
701 float reqPos[3];
702 dtPolyRef reqPath[MAX_RES]; // The path to the request location
703 int reqPathCount = 0;
704
705 // Quick search towards the goal.
706 static const int MAX_ITER = 20;
707 m_navquery->initSlicedFindPath(path[0], ag->targetRef, ag->npos, ag->targetPos, &m_filters[ag->params.queryFilterType]);
708 m_navquery->updateSlicedFindPath(MAX_ITER, 0);
709 dtStatus status = 0;
710 if (ag->targetReplan) // && npath > 10)
711 {
712 // Try to use existing steady path during replan if possible.
713 status = m_navquery->finalizeSlicedFindPathPartial(path, npath, reqPath, &reqPathCount, MAX_RES);
714 }
715 else
716 {
717 // Try to move towards target when goal changes.
718 status = m_navquery->finalizeSlicedFindPath(reqPath, &reqPathCount, MAX_RES);
719 }
720
721 if (!dtStatusFailed(status) && reqPathCount > 0)
722 {
723 // In progress or succeed.
724 if (reqPath[reqPathCount-1] != ag->targetRef)
725 {
726 // Partial path, constrain target position inside the last polygon.
727 status = m_navquery->closestPointOnPoly(reqPath[reqPathCount-1], ag->targetPos, reqPos, 0);
728 if (dtStatusFailed(status))
729 reqPathCount = 0;
730 }
731 else
732 {
733 dtVcopy(reqPos, ag->targetPos);
734 }
735 }
736 else
737 {
738 reqPathCount = 0;
739 }
740
741 if (!reqPathCount)
742 {
743 // Could not find path, start the request from current location.
744 dtVcopy(reqPos, ag->npos);
745 reqPath[0] = path[0];
746 reqPathCount = 1;
747 }
748
749 ag->corridor.setCorridor(reqPos, reqPath, reqPathCount);
750 ag->boundary.reset();
751 ag->partial = false;
752
753 if (reqPath[reqPathCount-1] == ag->targetRef)
754 {
755 ag->targetState = DT_CROWDAGENT_TARGET_VALID;
756 ag->targetReplanTime = 0.0;
757 }
758 else
759 {
760 // The path is longer or potentially unreachable, full plan.
761 ag->targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE;
762 }
763 }
764
765 if (ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE)
766 {
767 nqueue = addToPathQueue(ag, queue, nqueue, PATH_MAX_AGENTS);
768 }
769 }
770
771 for (int i = 0; i < nqueue; ++i)
772 {
773 dtCrowdAgent* ag = queue[i];
774 ag->targetPathqRef = m_pathq.request(ag->corridor.getLastPoly(), ag->targetRef,
775 ag->corridor.getTarget(), ag->targetPos, &m_filters[ag->params.queryFilterType]);
776 if (ag->targetPathqRef != DT_PATHQ_INVALID)
777 ag->targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_PATH;
778 }
779
780
781 // Update requests.
782 m_pathq.update(MAX_ITERS_PER_UPDATE);
783
784 dtStatus status;
785
786 // Process path results.
787 for (int i = 0; i < m_maxAgents; ++i)
788 {
789 dtCrowdAgent* ag = &m_agents[i];
790 if (!ag->active)
791 continue;
792 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
793 continue;
794
795 if (ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_PATH)
796 {
797 // Poll path queue.
798 status = m_pathq.getRequestStatus(ag->targetPathqRef);
799 if (dtStatusFailed(status))
800 {
801 // Path find failed, retry if the target location is still valid.
802 ag->targetPathqRef = DT_PATHQ_INVALID;
803 if (ag->targetRef)
804 ag->targetState = DT_CROWDAGENT_TARGET_REQUESTING;
805 else
806 ag->targetState = DT_CROWDAGENT_TARGET_FAILED;
807 ag->targetReplanTime = 0.0;
808 }
809 else if (dtStatusSucceed(status))
810 {
811 const dtPolyRef* path = ag->corridor.getPath();
812 const int npath = ag->corridor.getPathCount();
813 dtAssert(npath);
814
815 // Apply results.
816 float targetPos[3];
817 dtVcopy(targetPos, ag->targetPos);
818
819 dtPolyRef* res = m_pathResult;
820 bool valid = true;
821 int nres = 0;
822 status = m_pathq.getPathResult(ag->targetPathqRef, res, &nres, m_maxPathResult);
823 if (dtStatusFailed(status) || !nres)
824 valid = false;
825
826 if (dtStatusDetail(status, DT_PARTIAL_RESULT))
827 ag->partial = true;
828 else
829 ag->partial = false;
830
831 // Merge result and existing path.
832 // The agent might have moved whilst the request is
833 // being processed, so the path may have changed.
834 // We assume that the end of the path is at the same location
835 // where the request was issued.
836
837 // The last ref in the old path should be the same as
838 // the location where the request was issued..
839 if (valid && path[npath-1] != res[0])
840 valid = false;
841
842 if (valid)
843 {
844 // Put the old path infront of the old path.
845 if (npath > 1)
846 {
847 // Make space for the old path.
848 if ((npath-1)+nres > m_maxPathResult)
849 nres = m_maxPathResult - (npath-1);
850
851 memmove(res+npath-1, res, sizeof(dtPolyRef)*nres);
852 // Copy old path in the beginning.
853 memcpy(res, path, sizeof(dtPolyRef)*(npath-1));
854 nres += npath-1;
855
856 // Remove trackbacks
857 for (int j = 0; j < nres; ++j)
858 {
859 if (j-1 >= 0 && j+1 < nres)
860 {
861 if (res[j-1] == res[j+1])
862 {
863 memmove(res+(j-1), res+(j+1), sizeof(dtPolyRef)*(nres-(j+1)));
864 nres -= 2;
865 j -= 2;
866 }
867 }
868 }
869
870 }
871
872 // Check for partial path.
873 if (res[nres-1] != ag->targetRef)
874 {
875 // Partial path, constrain target position inside the last polygon.
876 float nearest[3];
877 status = m_navquery->closestPointOnPoly(res[nres-1], targetPos, nearest, 0);
878 if (dtStatusSucceed(status))
879 dtVcopy(targetPos, nearest);
880 else
881 valid = false;
882 }
883 }
884
885 if (valid)
886 {
887 // Set current corridor.
888 ag->corridor.setCorridor(targetPos, res, nres);
889 // Force to update boundary.
890 ag->boundary.reset();
891 ag->targetState = DT_CROWDAGENT_TARGET_VALID;
892 }
893 else
894 {
895 // Something went wrong.
896 ag->targetState = DT_CROWDAGENT_TARGET_FAILED;
897 }
898
899 ag->targetReplanTime = 0.0;
900 }
901 }
902 }
903
904 }
905
906
907 void dtCrowd::updateTopologyOptimization(dtCrowdAgent** agents, const int nagents, const float dt)
908 {
909 if (!nagents)
910 return;
911
912 const float OPT_TIME_THR = 0.5f; // seconds
913 const int OPT_MAX_AGENTS = 1;
914 dtCrowdAgent* queue[OPT_MAX_AGENTS];
915 int nqueue = 0;
916
917 for (int i = 0; i < nagents; ++i)
918 {
919 dtCrowdAgent* ag = agents[i];
920 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
921 continue;
922 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
923 continue;
924 if ((ag->params.updateFlags & DT_CROWD_OPTIMIZE_TOPO) == 0)
925 continue;
926 ag->topologyOptTime += dt;
927 if (ag->topologyOptTime >= OPT_TIME_THR)
928 nqueue = addToOptQueue(ag, queue, nqueue, OPT_MAX_AGENTS);
929 }
930
931 for (int i = 0; i < nqueue; ++i)
932 {
933 dtCrowdAgent* ag = queue[i];
934 ag->corridor.optimizePathTopology(m_navquery, &m_filters[ag->params.queryFilterType]);
935 ag->topologyOptTime = 0;
936 }
937
938 }
939
940 void dtCrowd::checkPathValidity(dtCrowdAgent** agents, const int nagents, const float dt)
941 {
942 static const int CHECK_LOOKAHEAD = 10;
943 static const float TARGET_REPLAN_DELAY = 1.0; // seconds
944
945 for (int i = 0; i < nagents; ++i)
946 {
947 dtCrowdAgent* ag = agents[i];
948
949 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
950 continue;
951
952 ag->targetReplanTime += dt;
953
954 bool replan = false;
955
956 // First check that the current location is valid.
957 const int idx = getAgentIndex(ag);
958 float agentPos[3];
959 dtPolyRef agentRef = ag->corridor.getFirstPoly();
960 dtVcopy(agentPos, ag->npos);
961 if (!m_navquery->isValidPolyRef(agentRef, &m_filters[ag->params.queryFilterType]))
962 {
963 // Current location is not valid, try to reposition.
964 // TODO: this can snap agents, how to handle that?
965 float nearest[3];
966 dtVcopy(nearest, agentPos);
967 agentRef = 0;
968 m_navquery->findNearestPoly(ag->npos, m_agentPlacementHalfExtents, &m_filters[ag->params.queryFilterType], &agentRef, nearest);
969 dtVcopy(agentPos, nearest);
970
971 if (!agentRef)
972 {
973 // Could not find location in navmesh, set state to invalid.
974 ag->corridor.reset(0, agentPos);
975 ag->partial = false;
976 ag->boundary.reset();
977 ag->state = DT_CROWDAGENT_STATE_INVALID;
978 continue;
979 }
980
981 // Make sure the first polygon is valid, but leave other valid
982 // polygons in the path so that replanner can adjust the path better.
983 ag->corridor.fixPathStart(agentRef, agentPos);
984 // ag->corridor.trimInvalidPath(agentRef, agentPos, m_navquery, &m_filter);
985 ag->boundary.reset();
986 dtVcopy(ag->npos, agentPos);
987
988 replan = true;
989 }
990
991 // If the agent does not have move target or is controlled by velocity, no need to recover the target nor replan.
992 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
993 continue;
994
995 // Try to recover move request position.
996 if (ag->targetState != DT_CROWDAGENT_TARGET_NONE && ag->targetState != DT_CROWDAGENT_TARGET_FAILED)
997 {
998 if (!m_navquery->isValidPolyRef(ag->targetRef, &m_filters[ag->params.queryFilterType]))
999 {
1000 // Current target is not valid, try to reposition.
1001 float nearest[3];
1002 dtVcopy(nearest, ag->targetPos);
1003 ag->targetRef = 0;
1004 m_navquery->findNearestPoly(ag->targetPos, m_agentPlacementHalfExtents, &m_filters[ag->params.queryFilterType], &ag->targetRef, nearest);
1005 dtVcopy(ag->targetPos, nearest);
1006 replan = true;
1007 }
1008 if (!ag->targetRef)
1009 {
1010 // Failed to reposition target, fail moverequest.
1011 ag->corridor.reset(agentRef, agentPos);
1012 ag->partial = false;
1013 ag->targetState = DT_CROWDAGENT_TARGET_NONE;
1014 }
1015 }
1016
1017 // If nearby corridor is not valid, replan.
1018 if (!ag->corridor.isValid(CHECK_LOOKAHEAD, m_navquery, &m_filters[ag->params.queryFilterType]))
1019 {
1020 // Fix current path.
1021 // ag->corridor.trimInvalidPath(agentRef, agentPos, m_navquery, &m_filter);
1022 // ag->boundary.reset();
1023 replan = true;
1024 }
1025
1026 // If the end of the path is near and it is not the requested location, replan.
1027 if (ag->targetState == DT_CROWDAGENT_TARGET_VALID)
1028 {
1029 if (ag->targetReplanTime > TARGET_REPLAN_DELAY &&
1030 ag->corridor.getPathCount() < CHECK_LOOKAHEAD &&
1031 ag->corridor.getLastPoly() != ag->targetRef)
1032 replan = true;
1033 }
1034
1035 // Try to replan path to goal.
1036 if (replan)
1037 {
1038 if (ag->targetState != DT_CROWDAGENT_TARGET_NONE)
1039 {
1040 requestMoveTargetReplan(idx, ag->targetRef, ag->targetPos);
1041 }
1042 }
1043 }
1044 }
1045
1046 void dtCrowd::update(const float dt, dtCrowdAgentDebugInfo* debug)
1047 {
1048 m_velocitySampleCount = 0;
1049
1050 const int debugIdx = debug ? debug->idx : -1;
1051
1052 dtCrowdAgent** agents = m_activeAgents;
1053 int nagents = getActiveAgents(agents, m_maxAgents);
1054
1055 // Check that all agents still have valid paths.
1056 checkPathValidity(agents, nagents, dt);
1057
1058 // Update async move request and path finder.
1059 updateMoveRequest(dt);
1060
1061 // Optimize path topology.
1062 updateTopologyOptimization(agents, nagents, dt);
1063
1064 // Register agents to proximity grid.
1065 m_grid->clear();
1066 for (int i = 0; i < nagents; ++i)
1067 {
1068 dtCrowdAgent* ag = agents[i];
1069 const float* p = ag->npos;
1070 const float r = ag->params.radius;
1071 m_grid->addItem((unsigned short)i, p[0]-r, p[2]-r, p[0]+r, p[2]+r);
1072 }
1073
1074 // Get nearby navmesh segments and agents to collide with.
1075 for (int i = 0; i < nagents; ++i)
1076 {
1077 dtCrowdAgent* ag = agents[i];
1078 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1079 continue;
1080
1081 // Update the collision boundary after certain distance has been passed or
1082 // if it has become invalid.
1083 const float updateThr = ag->params.collisionQueryRange*0.25f;
1084 if (dtVdist2DSqr(ag->npos, ag->boundary.getCenter()) > dtSqr(updateThr) ||
1085 !ag->boundary.isValid(m_navquery, &m_filters[ag->params.queryFilterType]))
1086 {
1087 ag->boundary.update(ag->corridor.getFirstPoly(), ag->npos, ag->params.collisionQueryRange,
1088 m_navquery, &m_filters[ag->params.queryFilterType]);
1089 }
1090 // Query neighbour agents
1091 ag->nneis = getNeighbours(ag->npos, ag->params.height, ag->params.collisionQueryRange,
1092 ag, ag->neis, DT_CROWDAGENT_MAX_NEIGHBOURS,
1093 agents, nagents, m_grid);
1094 for (int j = 0; j < ag->nneis; j++)
1095 ag->neis[j].idx = getAgentIndex(agents[ag->neis[j].idx]);
1096 }
1097
1098 // Find next corner to steer to.
1099 for (int i = 0; i < nagents; ++i)
1100 {
1101 dtCrowdAgent* ag = agents[i];
1102
1103 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1104 continue;
1105 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
1106 continue;
1107
1108 // Find corners for steering
1109 ag->ncorners = ag->corridor.findCorners(ag->cornerVerts, ag->cornerFlags, ag->cornerPolys,
1110 DT_CROWDAGENT_MAX_CORNERS, m_navquery, &m_filters[ag->params.queryFilterType]);
1111
1112 // Check to see if the corner after the next corner is directly visible,
1113 // and short cut to there.
1114 if ((ag->params.updateFlags & DT_CROWD_OPTIMIZE_VIS) && ag->ncorners > 0)
1115 {
1116 const float* target = &ag->cornerVerts[dtMin(1,ag->ncorners-1)*3];
1117 ag->corridor.optimizePathVisibility(target, ag->params.pathOptimizationRange, m_navquery, &m_filters[ag->params.queryFilterType]);
1118
1119 // Copy data for debug purposes.
1120 if (debugIdx == i)
1121 {
1122 dtVcopy(debug->optStart, ag->corridor.getPos());
1123 dtVcopy(debug->optEnd, target);
1124 }
1125 }
1126 else
1127 {
1128 // Copy data for debug purposes.
1129 if (debugIdx == i)
1130 {
1131 dtVset(debug->optStart, 0,0,0);
1132 dtVset(debug->optEnd, 0,0,0);
1133 }
1134 }
1135 }
1136
1137 // Trigger off-mesh connections (depends on corners).
1138 for (int i = 0; i < nagents; ++i)
1139 {
1140 dtCrowdAgent* ag = agents[i];
1141
1142 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1143 continue;
1144 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
1145 continue;
1146
1147 // Check
1148 const float triggerRadius = ag->params.radius*2.25f;
1149 if (overOffmeshConnection(ag, triggerRadius))
1150 {
1151 // Prepare to off-mesh connection.
1152 const int idx = (int)(ag - m_agents);
1153 dtCrowdAgentAnimation* anim = &m_agentAnims[idx];
1154
1155 // Adjust the path over the off-mesh connection.
1156 dtPolyRef refs[2];
1157 if (ag->corridor.moveOverOffmeshConnection(ag->cornerPolys[ag->ncorners-1], refs,
1158 anim->startPos, anim->endPos, m_navquery))
1159 {
1160 dtVcopy(anim->initPos, ag->npos);
1161 anim->polyRef = refs[1];
1162 anim->active = true;
1163 anim->t = 0.0f;
1164 anim->tmax = (dtVdist2D(anim->startPos, anim->endPos) / ag->params.maxSpeed) * 0.5f;
1165
1166 ag->state = DT_CROWDAGENT_STATE_OFFMESH;
1167 ag->ncorners = 0;
1168 ag->nneis = 0;
1169 continue;
1170 }
1171 else
1172 {
1173 // Path validity check will ensure that bad/blocked connections will be replanned.
1174 }
1175 }
1176 }
1177
1178 // Calculate steering.
1179 for (int i = 0; i < nagents; ++i)
1180 {
1181 dtCrowdAgent* ag = agents[i];
1182
1183 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1184 continue;
1185 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE)
1186 continue;
1187
1188 float dvel[3] = {0,0,0};
1189
1190 if (ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
1191 {
1192 dtVcopy(dvel, ag->targetPos);
1193 ag->desiredSpeed = dtVlen(ag->targetPos);
1194 }
1195 else
1196 {
1197 // Calculate steering direction.
1198 if (ag->params.updateFlags & DT_CROWD_ANTICIPATE_TURNS)
1199 calcSmoothSteerDirection(ag, dvel);
1200 else
1201 calcStraightSteerDirection(ag, dvel);
1202
1203 // Calculate speed scale, which tells the agent to slowdown at the end of the path.
1204 const float slowDownRadius = ag->params.radius*2; // TODO: make less hacky.
1205 const float speedScale = getDistanceToGoal(ag, slowDownRadius) / slowDownRadius;
1206
1207 ag->desiredSpeed = ag->params.maxSpeed;
1208 dtVscale(dvel, dvel, ag->desiredSpeed * speedScale);
1209 }
1210
1211 // Separation
1212 if (ag->params.updateFlags & DT_CROWD_SEPARATION)
1213 {
1214 const float separationDist = ag->params.collisionQueryRange;
1215 const float invSeparationDist = 1.0f / separationDist;
1216 const float separationWeight = ag->params.separationWeight;
1217
1218 float w = 0;
1219 float disp[3] = {0,0,0};
1220
1221 for (int j = 0; j < ag->nneis; ++j)
1222 {
1223 const dtCrowdAgent* nei = &m_agents[ag->neis[j].idx];
1224
1225 float diff[3];
1226 dtVsub(diff, ag->npos, nei->npos);
1227 diff[1] = 0;
1228
1229 const float distSqr = dtVlenSqr(diff);
1230 if (distSqr < 0.00001f)
1231 continue;
1232 if (distSqr > dtSqr(separationDist))
1233 continue;
1234 const float dist = dtMathSqrtf(distSqr);
1235 const float weight = separationWeight * (1.0f - dtSqr(dist*invSeparationDist));
1236
1237 dtVmad(disp, disp, diff, weight/dist);
1238 w += 1.0f;
1239 }
1240
1241 if (w > 0.0001f)
1242 {
1243 // Adjust desired velocity.
1244 dtVmad(dvel, dvel, disp, 1.0f/w);
1245 // Clamp desired velocity to desired speed.
1246 const float speedSqr = dtVlenSqr(dvel);
1247 const float desiredSqr = dtSqr(ag->desiredSpeed);
1248 if (speedSqr > desiredSqr)
1249 dtVscale(dvel, dvel, desiredSqr/speedSqr);
1250 }
1251 }
1252
1253 // Set the desired velocity.
1254 dtVcopy(ag->dvel, dvel);
1255 }
1256
1257 // Velocity planning.
1258 for (int i = 0; i < nagents; ++i)
1259 {
1260 dtCrowdAgent* ag = agents[i];
1261
1262 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1263 continue;
1264
1265 if (ag->params.updateFlags & DT_CROWD_OBSTACLE_AVOIDANCE)
1266 {
1267 m_obstacleQuery->reset();
1268
1269 // Add neighbours as obstacles.
1270 for (int j = 0; j < ag->nneis; ++j)
1271 {
1272 const dtCrowdAgent* nei = &m_agents[ag->neis[j].idx];
1273 m_obstacleQuery->addCircle(nei->npos, nei->params.radius, nei->vel, nei->dvel);
1274 }
1275
1276 // Append neighbour segments as obstacles.
1277 for (int j = 0; j < ag->boundary.getSegmentCount(); ++j)
1278 {
1279 const float* s = ag->boundary.getSegment(j);
1280 if (dtTriArea2D(ag->npos, s, s+3) < 0.0f)
1281 continue;
1282 m_obstacleQuery->addSegment(s, s+3);
1283 }
1284
1285 dtObstacleAvoidanceDebugData* vod = 0;
1286 if (debugIdx == i)
1287 vod = debug->vod;
1288
1289 // Sample new safe velocity.
1290 bool adaptive = true;
1291 int ns = 0;
1292
1293 const dtObstacleAvoidanceParams* params = &m_obstacleQueryParams[ag->params.obstacleAvoidanceType];
1294
1295 if (adaptive)
1296 {
1297 ns = m_obstacleQuery->sampleVelocityAdaptive(ag->npos, ag->params.radius, ag->desiredSpeed,
1298 ag->vel, ag->dvel, ag->nvel, params, vod);
1299 }
1300 else
1301 {
1302 ns = m_obstacleQuery->sampleVelocityGrid(ag->npos, ag->params.radius, ag->desiredSpeed,
1303 ag->vel, ag->dvel, ag->nvel, params, vod);
1304 }
1305 m_velocitySampleCount += ns;
1306 }
1307 else
1308 {
1309 // If not using velocity planning, new velocity is directly the desired velocity.
1310 dtVcopy(ag->nvel, ag->dvel);
1311 }
1312 }
1313
1314 // Integrate.
1315 for (int i = 0; i < nagents; ++i)
1316 {
1317 dtCrowdAgent* ag = agents[i];
1318 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1319 continue;
1320 integrate(ag, dt);
1321 }
1322
1323 // Handle collisions.
1324 static const float COLLISION_RESOLVE_FACTOR = 0.7f;
1325
1326 for (int iter = 0; iter < 4; ++iter)
1327 {
1328 for (int i = 0; i < nagents; ++i)
1329 {
1330 dtCrowdAgent* ag = agents[i];
1331 const int idx0 = getAgentIndex(ag);
1332
1333 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1334 continue;
1335
1336 dtVset(ag->disp, 0,0,0);
1337
1338 float w = 0;
1339
1340 for (int j = 0; j < ag->nneis; ++j)
1341 {
1342 const dtCrowdAgent* nei = &m_agents[ag->neis[j].idx];
1343 const int idx1 = getAgentIndex(nei);
1344
1345 float diff[3];
1346 dtVsub(diff, ag->npos, nei->npos);
1347 diff[1] = 0;
1348
1349 float dist = dtVlenSqr(diff);
1350 if (dist > dtSqr(ag->params.radius + nei->params.radius))
1351 continue;
1352 dist = dtMathSqrtf(dist);
1353 float pen = (ag->params.radius + nei->params.radius) - dist;
1354 if (dist < 0.0001f)
1355 {
1356 // Agents on top of each other, try to choose diverging separation directions.
1357 if (idx0 > idx1)
1358 dtVset(diff, -ag->dvel[2],0,ag->dvel[0]);
1359 else
1360 dtVset(diff, ag->dvel[2],0,-ag->dvel[0]);
1361 pen = 0.01f;
1362 }
1363 else
1364 {
1365 pen = (1.0f/dist) * (pen*0.5f) * COLLISION_RESOLVE_FACTOR;
1366 }
1367
1368 dtVmad(ag->disp, ag->disp, diff, pen);
1369
1370 w += 1.0f;
1371 }
1372
1373 if (w > 0.0001f)
1374 {
1375 const float iw = 1.0f / w;
1376 dtVscale(ag->disp, ag->disp, iw);
1377 }
1378 }
1379
1380 for (int i = 0; i < nagents; ++i)
1381 {
1382 dtCrowdAgent* ag = agents[i];
1383 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1384 continue;
1385
1386 dtVadd(ag->npos, ag->npos, ag->disp);
1387 }
1388 }
1389
1390 for (int i = 0; i < nagents; ++i)
1391 {
1392 dtCrowdAgent* ag = agents[i];
1393 if (ag->state != DT_CROWDAGENT_STATE_WALKING)
1394 continue;
1395
1396 // Move along navmesh.
1397 ag->corridor.movePosition(ag->npos, m_navquery, &m_filters[ag->params.queryFilterType]);
1398 // Get valid constrained position back.
1399 dtVcopy(ag->npos, ag->corridor.getPos());
1400
1401 // If not using path, truncate the corridor to just one poly.
1402 if (ag->targetState == DT_CROWDAGENT_TARGET_NONE || ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
1403 {
1404 ag->corridor.reset(ag->corridor.getFirstPoly(), ag->npos);
1405 ag->partial = false;
1406 }
1407
1408 }
1409
1410 // Update agents using off-mesh connection.
1411 for (int i = 0; i < nagents; ++i)
1412 {
1413 dtCrowdAgent* ag = agents[i];
1414 const int idx = (int)(ag - m_agents);
1415 dtCrowdAgentAnimation* anim = &m_agentAnims[idx];
1416 if (!anim->active)
1417 continue;
1418
1419
1420 anim->t += dt;
1421 if (anim->t > anim->tmax)
1422 {
1423 // Reset animation
1424 anim->active = false;
1425 // Prepare agent for walking.
1426 ag->state = DT_CROWDAGENT_STATE_WALKING;
1427 continue;
1428 }
1429
1430 // Update position
1431 const float ta = anim->tmax*0.15f;
1432 const float tb = anim->tmax;
1433 if (anim->t < ta)
1434 {
1435 const float u = tween(anim->t, 0.0, ta);
1436 dtVlerp(ag->npos, anim->initPos, anim->startPos, u);
1437 }
1438 else
1439 {
1440 const float u = tween(anim->t, ta, tb);
1441 dtVlerp(ag->npos, anim->startPos, anim->endPos, u);
1442 }
1443
1444 // Update velocity.
1445 dtVset(ag->vel, 0,0,0);
1446 dtVset(ag->dvel, 0,0,0);
1447 }
1448
1449 }