CrowdManager.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../Navigation/CrowdAgent.h"
  28. #include "../Navigation/CrowdManager.h"
  29. #include "../Navigation/DynamicNavigationMesh.h"
  30. #include "../Navigation/NavigationEvents.h"
  31. #include "../Scene/Node.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. // ATOMIC BEGIN
  35. #include <DetourCrowd/include/DetourCrowd.h>
  36. // ATOMIC END
  37. #include "../DebugNew.h"
  38. namespace Atomic
  39. {
  40. extern const char* NAVIGATION_CATEGORY;
  41. static const unsigned DEFAULT_MAX_AGENTS = 512;
  42. static const float DEFAULT_MAX_AGENT_RADIUS = 0.f;
  43. void CrowdAgentUpdateCallback(dtCrowdAgent* ag, float dt)
  44. {
  45. static_cast<CrowdAgent*>(ag->params.userData)->OnCrowdUpdate(ag, dt);
  46. }
  47. CrowdManager::CrowdManager(Context* context) :
  48. Component(context),
  49. crowd_(0),
  50. navigationMeshId_(0),
  51. maxAgents_(DEFAULT_MAX_AGENTS),
  52. maxAgentRadius_(DEFAULT_MAX_AGENT_RADIUS),
  53. numQueryFilterTypes_(0),
  54. numObstacleAvoidanceTypes_(0)
  55. {
  56. // The actual buffer is allocated inside dtCrowd, we only track the number of "slots" being configured explicitly
  57. numAreas_.Reserve(DT_CROWD_MAX_QUERY_FILTER_TYPE);
  58. for (unsigned i = 0; i < DT_CROWD_MAX_QUERY_FILTER_TYPE; ++i)
  59. numAreas_.Push(0);
  60. }
  61. CrowdManager::~CrowdManager()
  62. {
  63. dtFreeCrowd(crowd_);
  64. crowd_ = 0;
  65. }
  66. void CrowdManager::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<CrowdManager>(NAVIGATION_CATEGORY);
  69. ATOMIC_ATTRIBUTE("Max Agents", unsigned, maxAgents_, DEFAULT_MAX_AGENTS, AM_DEFAULT);
  70. ATOMIC_ATTRIBUTE("Max Agent Radius", float, maxAgentRadius_, DEFAULT_MAX_AGENT_RADIUS, AM_DEFAULT);
  71. ATOMIC_ATTRIBUTE("Navigation Mesh", unsigned, navigationMeshId_, 0, AM_DEFAULT | AM_COMPONENTID);
  72. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Filter Types", GetQueryFilterTypesAttr, SetQueryFilterTypesAttr, VariantVector,
  73. Variant::emptyVariantVector, AM_DEFAULT);
  74. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Obstacle Avoidance Types", GetObstacleAvoidanceTypesAttr, SetObstacleAvoidanceTypesAttr,
  75. VariantVector, Variant::emptyVariantVector, AM_DEFAULT);
  76. }
  77. void CrowdManager::ApplyAttributes()
  78. {
  79. // Values from Editor, saved-file, or network must be checked before applying
  80. maxAgents_ = Max(1U, maxAgents_);
  81. maxAgentRadius_ = Max(0.f, maxAgentRadius_);
  82. bool navMeshChange = false;
  83. Scene* scene = GetScene();
  84. if (scene && navigationMeshId_)
  85. {
  86. NavigationMesh* navMesh = dynamic_cast<NavigationMesh*>(scene->GetComponent(navigationMeshId_));
  87. if (navMesh && navMesh != navigationMesh_)
  88. {
  89. SetNavigationMesh(navMesh); // This will also CreateCrowd(), so the rest of the function is unnecessary
  90. return;
  91. }
  92. }
  93. // In case of receiving an invalid component id, revert it back to the existing navmesh component id (if any)
  94. navigationMeshId_ = navigationMesh_ ? navigationMesh_->GetID() : 0;
  95. // If the Detour crowd initialization parameters have changed then recreate it
  96. if (crowd_ && (navMeshChange || crowd_->getAgentCount() != maxAgents_ || crowd_->getMaxAgentRadius() != maxAgentRadius_))
  97. CreateCrowd();
  98. }
  99. void CrowdManager::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  100. {
  101. if (debug && crowd_)
  102. {
  103. // Current position-to-target line
  104. for (int i = 0; i < crowd_->getAgentCount(); i++)
  105. {
  106. const dtCrowdAgent* ag = crowd_->getAgent(i);
  107. if (!ag->active)
  108. continue;
  109. // Draw CrowdAgent shape (from its radius & height)
  110. CrowdAgent* crowdAgent = static_cast<CrowdAgent*>(ag->params.userData);
  111. crowdAgent->DrawDebugGeometry(debug, depthTest);
  112. // Draw move target if any
  113. if (crowdAgent->GetTargetState() == CA_TARGET_NONE || crowdAgent->GetTargetState() == CA_TARGET_VELOCITY)
  114. continue;
  115. Color color(0.6f, 0.2f, 0.2f, 1.0f);
  116. // Draw line to target
  117. Vector3 pos1(ag->npos[0], ag->npos[1], ag->npos[2]);
  118. Vector3 pos2;
  119. for (int i = 0; i < ag->ncorners; ++i)
  120. {
  121. pos2.x_ = ag->cornerVerts[i * 3];
  122. pos2.y_ = ag->cornerVerts[i * 3 + 1];
  123. pos2.z_ = ag->cornerVerts[i * 3 + 2];
  124. debug->AddLine(pos1, pos2, color, depthTest);
  125. pos1 = pos2;
  126. }
  127. pos2.x_ = ag->targetPos[0];
  128. pos2.y_ = ag->targetPos[1];
  129. pos2.z_ = ag->targetPos[2];
  130. debug->AddLine(pos1, pos2, color, depthTest);
  131. // Draw target circle
  132. debug->AddSphere(Sphere(pos2, 0.5f), color, depthTest);
  133. }
  134. }
  135. }
  136. void CrowdManager::DrawDebugGeometry(bool depthTest)
  137. {
  138. Scene* scene = GetScene();
  139. if (scene)
  140. {
  141. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  142. if (debug)
  143. DrawDebugGeometry(debug, depthTest);
  144. }
  145. }
  146. void CrowdManager::SetCrowdTarget(const Vector3& position, Node* node)
  147. {
  148. if (!crowd_)
  149. return;
  150. PODVector<CrowdAgent*> agents = GetAgents(node, false); // Get all crowd agent components
  151. Vector3 moveTarget(position);
  152. for (unsigned i = 0; i < agents.Size(); ++i)
  153. {
  154. // Give application a chance to determine the desired crowd formation when they reach the target position
  155. CrowdAgent* agent = agents[i];
  156. using namespace CrowdAgentFormation;
  157. VariantMap& map = GetEventDataMap();
  158. map[P_NODE] = agent->GetNode();
  159. map[P_CROWD_AGENT] = agent;
  160. map[P_INDEX] = i;
  161. map[P_SIZE] = agents.Size();
  162. map[P_POSITION] = moveTarget; // Expect the event handler will modify this position accordingly
  163. SendEvent(E_CROWD_AGENT_FORMATION, map);
  164. moveTarget = map[P_POSITION].GetVector3();
  165. agent->SetTargetPosition(moveTarget);
  166. }
  167. }
  168. void CrowdManager::SetCrowdVelocity(const Vector3& velocity, Node* node)
  169. {
  170. if (!crowd_)
  171. return;
  172. PODVector<CrowdAgent*> agents = GetAgents(node, true); // Get only crowd agent components already in the crowd
  173. for (unsigned i = 0; i < agents.Size(); ++i)
  174. agents[i]->SetTargetVelocity(velocity);
  175. }
  176. void CrowdManager::ResetCrowdTarget(Node* node)
  177. {
  178. if (!crowd_)
  179. return;
  180. PODVector<CrowdAgent*> agents = GetAgents(node, true);
  181. for (unsigned i = 0; i < agents.Size(); ++i)
  182. agents[i]->ResetTarget();
  183. }
  184. void CrowdManager::SetMaxAgents(unsigned maxAgents)
  185. {
  186. if (maxAgents != maxAgents_ && maxAgents > 0)
  187. {
  188. maxAgents_ = maxAgents;
  189. CreateCrowd();
  190. MarkNetworkUpdate();
  191. }
  192. }
  193. void CrowdManager::SetMaxAgentRadius(float maxAgentRadius)
  194. {
  195. if (maxAgentRadius != maxAgentRadius_ && maxAgentRadius > 0.f)
  196. {
  197. maxAgentRadius_ = maxAgentRadius;
  198. CreateCrowd();
  199. MarkNetworkUpdate();
  200. }
  201. }
  202. void CrowdManager::SetNavigationMesh(NavigationMesh* navMesh)
  203. {
  204. UnsubscribeFromEvent(E_COMPONENTADDED);
  205. UnsubscribeFromEvent(E_NAVIGATION_MESH_REBUILT);
  206. UnsubscribeFromEvent(E_COMPONENTREMOVED);
  207. if (navMesh != navigationMesh_) // It is possible to reset navmesh pointer back to 0
  208. {
  209. Scene* scene = GetScene();
  210. navigationMesh_ = navMesh;
  211. navigationMeshId_ = navMesh ? navMesh->GetID() : 0;
  212. if (navMesh)
  213. {
  214. SubscribeToEvent(navMesh, E_NAVIGATION_MESH_REBUILT, ATOMIC_HANDLER(CrowdManager, HandleNavMeshChanged));
  215. SubscribeToEvent(scene, E_COMPONENTREMOVED, ATOMIC_HANDLER(CrowdManager, HandleNavMeshChanged));
  216. }
  217. CreateCrowd();
  218. MarkNetworkUpdate();
  219. }
  220. }
  221. void CrowdManager::SetQueryFilterTypesAttr(const VariantVector& value)
  222. {
  223. if (!crowd_)
  224. return;
  225. unsigned index = 0;
  226. unsigned queryFilterType = 0;
  227. numQueryFilterTypes_ = index < value.Size() ? Min(value[index++].GetUInt(), (unsigned)DT_CROWD_MAX_QUERY_FILTER_TYPE) : 0;
  228. while (queryFilterType < numQueryFilterTypes_)
  229. {
  230. if (index + 3 <= value.Size())
  231. {
  232. dtQueryFilter* filter = crowd_->getEditableFilter(queryFilterType);
  233. assert(filter);
  234. filter->setIncludeFlags((unsigned short)value[index++].GetUInt());
  235. filter->setExcludeFlags((unsigned short)value[index++].GetUInt());
  236. unsigned prevNumAreas = numAreas_[queryFilterType];
  237. numAreas_[queryFilterType] = Min(value[index++].GetUInt(), (unsigned)DT_MAX_AREAS);
  238. // Must loop thru based on previous number of areas, the new area cost (if any) can only be set in the next attribute get/set iteration
  239. if (index + prevNumAreas <= value.Size())
  240. {
  241. for (unsigned i = 0; i < prevNumAreas; ++i)
  242. filter->setAreaCost(i, value[index++].GetFloat());
  243. }
  244. }
  245. ++queryFilterType;
  246. }
  247. }
  248. void CrowdManager::SetIncludeFlags(unsigned queryFilterType, unsigned short flags)
  249. {
  250. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  251. if (filter)
  252. {
  253. filter->setIncludeFlags(flags);
  254. if (numQueryFilterTypes_ < queryFilterType + 1)
  255. numQueryFilterTypes_ = queryFilterType + 1;
  256. MarkNetworkUpdate();
  257. }
  258. }
  259. void CrowdManager::SetExcludeFlags(unsigned queryFilterType, unsigned short flags)
  260. {
  261. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  262. if (filter)
  263. {
  264. filter->setExcludeFlags(flags);
  265. if (numQueryFilterTypes_ < queryFilterType + 1)
  266. numQueryFilterTypes_ = queryFilterType + 1;
  267. MarkNetworkUpdate();
  268. }
  269. }
  270. void CrowdManager::SetAreaCost(unsigned queryFilterType, unsigned areaID, float cost)
  271. {
  272. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  273. if (filter && areaID < DT_MAX_AREAS)
  274. {
  275. filter->setAreaCost((int)areaID, cost);
  276. if (numQueryFilterTypes_ < queryFilterType + 1)
  277. numQueryFilterTypes_ = queryFilterType + 1;
  278. if (numAreas_[queryFilterType] < areaID + 1)
  279. numAreas_[queryFilterType] = areaID + 1;
  280. MarkNetworkUpdate();
  281. }
  282. }
  283. void CrowdManager::SetObstacleAvoidanceTypesAttr(const VariantVector& value)
  284. {
  285. if (!crowd_)
  286. return;
  287. unsigned index = 0;
  288. unsigned obstacleAvoidanceType = 0;
  289. numObstacleAvoidanceTypes_ = index < value.Size() ? Min(value[index++].GetUInt(), (unsigned)DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) : 0;
  290. while (obstacleAvoidanceType < numObstacleAvoidanceTypes_)
  291. {
  292. if (index + 10 <= value.Size())
  293. {
  294. dtObstacleAvoidanceParams params;
  295. params.velBias = value[index++].GetFloat();
  296. params.weightDesVel = value[index++].GetFloat();
  297. params.weightCurVel = value[index++].GetFloat();
  298. params.weightSide = value[index++].GetFloat();
  299. params.weightToi = value[index++].GetFloat();
  300. params.horizTime = value[index++].GetFloat();
  301. params.gridSize = (unsigned char)value[index++].GetUInt();
  302. params.adaptiveDivs = (unsigned char)value[index++].GetUInt();
  303. params.adaptiveRings = (unsigned char)value[index++].GetUInt();
  304. params.adaptiveDepth = (unsigned char)value[index++].GetUInt();
  305. crowd_->setObstacleAvoidanceParams(obstacleAvoidanceType, &params);
  306. }
  307. ++obstacleAvoidanceType;
  308. }
  309. }
  310. void CrowdManager::SetObstacleAvoidanceParams(unsigned obstacleAvoidanceType, const CrowdObstacleAvoidanceParams& params)
  311. {
  312. if (crowd_ && obstacleAvoidanceType < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)
  313. {
  314. crowd_->setObstacleAvoidanceParams(obstacleAvoidanceType, reinterpret_cast<const dtObstacleAvoidanceParams*>(&params));
  315. if (numObstacleAvoidanceTypes_ < obstacleAvoidanceType + 1)
  316. numObstacleAvoidanceTypes_ = obstacleAvoidanceType + 1;
  317. MarkNetworkUpdate();
  318. }
  319. }
  320. Vector3 CrowdManager::FindNearestPoint(const Vector3& point, int queryFilterType, dtPolyRef* nearestRef)
  321. {
  322. if (nearestRef)
  323. *nearestRef = 0;
  324. return crowd_ && navigationMesh_ ?
  325. navigationMesh_->FindNearestPoint(point, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType), nearestRef) : point;
  326. }
  327. Vector3 CrowdManager::MoveAlongSurface(const Vector3& start, const Vector3& end, int queryFilterType, int maxVisited)
  328. {
  329. return crowd_ && navigationMesh_ ?
  330. navigationMesh_->MoveAlongSurface(start, end, Vector3(crowd_->getQueryExtents()), maxVisited, crowd_->getFilter(queryFilterType)) :
  331. end;
  332. }
  333. void CrowdManager::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, int queryFilterType)
  334. {
  335. if (crowd_ && navigationMesh_)
  336. navigationMesh_->FindPath(dest, start, end, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType));
  337. }
  338. Vector3 CrowdManager::GetRandomPoint(int queryFilterType, dtPolyRef* randomRef)
  339. {
  340. if (randomRef)
  341. *randomRef = 0;
  342. return crowd_ && navigationMesh_ ? navigationMesh_->GetRandomPoint(crowd_->getFilter(queryFilterType), randomRef) :
  343. Vector3::ZERO;
  344. }
  345. Vector3 CrowdManager::GetRandomPointInCircle(const Vector3& center, float radius, int queryFilterType, dtPolyRef* randomRef)
  346. {
  347. if (randomRef)
  348. *randomRef = 0;
  349. return crowd_ && navigationMesh_ ?
  350. navigationMesh_->GetRandomPointInCircle(center, radius, Vector3(crowd_->getQueryExtents()),
  351. crowd_->getFilter(queryFilterType), randomRef) : center;
  352. }
  353. float CrowdManager::GetDistanceToWall(const Vector3& point, float radius, int queryFilterType, Vector3* hitPos, Vector3* hitNormal)
  354. {
  355. if (hitPos)
  356. *hitPos = Vector3::ZERO;
  357. if (hitNormal)
  358. *hitNormal = Vector3::DOWN;
  359. return crowd_ && navigationMesh_ ?
  360. navigationMesh_->GetDistanceToWall(point, radius, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType),
  361. hitPos, hitNormal) : radius;
  362. }
  363. Vector3 CrowdManager::Raycast(const Vector3& start, const Vector3& end, int queryFilterType, Vector3* hitNormal)
  364. {
  365. if (hitNormal)
  366. *hitNormal = Vector3::DOWN;
  367. return crowd_ && navigationMesh_ ?
  368. navigationMesh_->Raycast(start, end, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType), hitNormal)
  369. : end;
  370. }
  371. unsigned CrowdManager::GetNumAreas(unsigned queryFilterType) const
  372. {
  373. return queryFilterType < numQueryFilterTypes_ ? numAreas_[queryFilterType] : 0;
  374. }
  375. VariantVector CrowdManager::GetQueryFilterTypesAttr() const
  376. {
  377. VariantVector ret;
  378. if (crowd_)
  379. {
  380. unsigned totalNumAreas = 0;
  381. for (unsigned i = 0; i < numQueryFilterTypes_; ++i)
  382. totalNumAreas += numAreas_[i];
  383. ret.Reserve(numQueryFilterTypes_ * 3 + totalNumAreas + 1);
  384. ret.Push(numQueryFilterTypes_);
  385. for (unsigned i = 0; i < numQueryFilterTypes_; ++i)
  386. {
  387. const dtQueryFilter* filter = crowd_->getFilter(i);
  388. assert(filter);
  389. ret.Push(filter->getIncludeFlags());
  390. ret.Push(filter->getExcludeFlags());
  391. ret.Push(numAreas_[i]);
  392. for (unsigned j = 0; j < numAreas_[i]; ++j)
  393. ret.Push(filter->getAreaCost(j));
  394. }
  395. }
  396. else
  397. ret.Push(0);
  398. return ret;
  399. }
  400. unsigned short CrowdManager::GetIncludeFlags(unsigned queryFilterType) const
  401. {
  402. if (queryFilterType >= numQueryFilterTypes_)
  403. ATOMIC_LOGWARNINGF("Query filter type %d is not configured yet, returning the default include flags initialized by dtCrowd",
  404. queryFilterType);
  405. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  406. return (unsigned short)(filter ? filter->getIncludeFlags() : 0xffff);
  407. }
  408. unsigned short CrowdManager::GetExcludeFlags(unsigned queryFilterType) const
  409. {
  410. if (queryFilterType >= numQueryFilterTypes_)
  411. ATOMIC_LOGWARNINGF("Query filter type %d is not configured yet, returning the default exclude flags initialized by dtCrowd",
  412. queryFilterType);
  413. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  414. return (unsigned short)(filter ? filter->getExcludeFlags() : 0);
  415. }
  416. float CrowdManager::GetAreaCost(unsigned queryFilterType, unsigned areaID) const
  417. {
  418. if (queryFilterType >= numQueryFilterTypes_ || areaID >= numAreas_[queryFilterType])
  419. ATOMIC_LOGWARNINGF(
  420. "Query filter type %d and/or area id %d are not configured yet, returning the default area cost initialized by dtCrowd",
  421. queryFilterType, areaID);
  422. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  423. return filter ? filter->getAreaCost((int)areaID) : 1.f;
  424. }
  425. VariantVector CrowdManager::GetObstacleAvoidanceTypesAttr() const
  426. {
  427. VariantVector ret;
  428. if (crowd_)
  429. {
  430. ret.Reserve(numObstacleAvoidanceTypes_ * 10 + 1);
  431. ret.Push(numObstacleAvoidanceTypes_);
  432. for (unsigned i = 0; i < numObstacleAvoidanceTypes_; ++i)
  433. {
  434. const dtObstacleAvoidanceParams* params = crowd_->getObstacleAvoidanceParams(i);
  435. assert(params);
  436. ret.Push(params->velBias);
  437. ret.Push(params->weightDesVel);
  438. ret.Push(params->weightCurVel);
  439. ret.Push(params->weightSide);
  440. ret.Push(params->weightToi);
  441. ret.Push(params->horizTime);
  442. ret.Push(params->gridSize);
  443. ret.Push(params->adaptiveDivs);
  444. ret.Push(params->adaptiveRings);
  445. ret.Push(params->adaptiveDepth);
  446. }
  447. }
  448. else
  449. ret.Push(0);
  450. return ret;
  451. }
  452. const CrowdObstacleAvoidanceParams& CrowdManager::GetObstacleAvoidanceParams(unsigned obstacleAvoidanceType) const
  453. {
  454. static const CrowdObstacleAvoidanceParams EMPTY_PARAMS = CrowdObstacleAvoidanceParams();
  455. const dtObstacleAvoidanceParams* params = crowd_ ? crowd_->getObstacleAvoidanceParams(obstacleAvoidanceType) : 0;
  456. return params ? *reinterpret_cast<const CrowdObstacleAvoidanceParams*>(params) : EMPTY_PARAMS;
  457. }
  458. PODVector<CrowdAgent*> CrowdManager::GetAgents(Node* node, bool inCrowdFilter) const
  459. {
  460. if (!node)
  461. node = GetScene();
  462. PODVector<CrowdAgent*> agents;
  463. node->GetComponents<CrowdAgent>(agents, true);
  464. if (inCrowdFilter)
  465. {
  466. PODVector<CrowdAgent*>::Iterator i = agents.Begin();
  467. while (i != agents.End())
  468. {
  469. if ((*i)->IsInCrowd())
  470. ++i;
  471. else
  472. i = agents.Erase(i);
  473. }
  474. }
  475. return agents;
  476. }
  477. bool CrowdManager::CreateCrowd()
  478. {
  479. if (!navigationMesh_ || !navigationMesh_->InitializeQuery())
  480. return false;
  481. // Preserve the existing crowd configuration before recreating it
  482. VariantVector queryFilterTypeConfiguration, obstacleAvoidanceTypeConfiguration;
  483. bool recreate = crowd_ != 0;
  484. if (recreate)
  485. {
  486. queryFilterTypeConfiguration = GetQueryFilterTypesAttr();
  487. obstacleAvoidanceTypeConfiguration = GetObstacleAvoidanceTypesAttr();
  488. dtFreeCrowd(crowd_);
  489. }
  490. crowd_ = dtAllocCrowd();
  491. // Initialize the crowd
  492. if (maxAgentRadius_ == 0.f)
  493. maxAgentRadius_ = navigationMesh_->GetAgentRadius();
  494. if (!crowd_->init(maxAgents_, maxAgentRadius_, navigationMesh_->navMesh_, CrowdAgentUpdateCallback))
  495. {
  496. ATOMIC_LOGERROR("Could not initialize DetourCrowd");
  497. return false;
  498. }
  499. if (recreate)
  500. {
  501. // Reconfigure the newly initialized crowd
  502. SetQueryFilterTypesAttr(queryFilterTypeConfiguration);
  503. SetObstacleAvoidanceTypesAttr(obstacleAvoidanceTypeConfiguration);
  504. // Re-add the existing crowd agents
  505. PODVector<CrowdAgent*> agents = GetAgents();
  506. for (unsigned i = 0; i < agents.Size(); ++i)
  507. {
  508. // Keep adding until the crowd cannot take it anymore
  509. if (agents[i]->AddAgentToCrowd(true) == -1)
  510. {
  511. ATOMIC_LOGWARNINGF("CrowdManager: %d crowd agents orphaned", agents.Size() - i);
  512. break;
  513. }
  514. }
  515. }
  516. return true;
  517. }
  518. int CrowdManager::AddAgent(CrowdAgent* agent, const Vector3& pos)
  519. {
  520. if (!crowd_ || !navigationMesh_ || !agent)
  521. return -1;
  522. dtCrowdAgentParams params;
  523. params.userData = agent;
  524. if (agent->radius_ == 0.f)
  525. agent->radius_ = navigationMesh_->GetAgentRadius();
  526. if (agent->height_ == 0.f)
  527. agent->height_ = navigationMesh_->GetAgentHeight();
  528. // dtCrowd::addAgent() requires the query filter type to find the nearest position on navmesh as the initial agent's position
  529. params.queryFilterType = (unsigned char)agent->GetQueryFilterType();
  530. return crowd_->addAgent(pos.Data(), &params);
  531. }
  532. void CrowdManager::RemoveAgent(CrowdAgent* agent)
  533. {
  534. if (!crowd_ || !agent)
  535. return;
  536. dtCrowdAgent* agt = crowd_->getEditableAgent(agent->GetAgentCrowdId());
  537. if (agt)
  538. agt->params.userData = 0;
  539. crowd_->removeAgent(agent->GetAgentCrowdId());
  540. }
  541. void CrowdManager::OnSceneSet(Scene* scene)
  542. {
  543. // Subscribe to the scene subsystem update, which will trigger the crowd update step, and grab a reference
  544. // to the scene's NavigationMesh
  545. if (scene)
  546. {
  547. if (scene != node_)
  548. {
  549. ATOMIC_LOGERROR("CrowdManager is a scene component and should only be attached to the scene node");
  550. return;
  551. }
  552. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, ATOMIC_HANDLER(CrowdManager, HandleSceneSubsystemUpdate));
  553. // Attempt to auto discover a NavigationMesh component (or its derivative) under the scene node
  554. if (navigationMeshId_ == 0)
  555. {
  556. NavigationMesh* navMesh = scene->GetDerivedComponent<NavigationMesh>(true);
  557. if (navMesh)
  558. SetNavigationMesh(navMesh);
  559. else
  560. {
  561. // If not found, attempt to find in a delayed manner
  562. SubscribeToEvent(scene, E_COMPONENTADDED, ATOMIC_HANDLER(CrowdManager, HandleComponentAdded));
  563. }
  564. }
  565. }
  566. else
  567. {
  568. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  569. UnsubscribeFromEvent(E_NAVIGATION_MESH_REBUILT);
  570. UnsubscribeFromEvent(E_COMPONENTADDED);
  571. UnsubscribeFromEvent(E_COMPONENTREMOVED);
  572. navigationMesh_ = 0;
  573. }
  574. }
  575. void CrowdManager::Update(float delta)
  576. {
  577. assert(crowd_ && navigationMesh_);
  578. ATOMIC_PROFILE(UpdateCrowd);
  579. crowd_->update(delta, 0);
  580. }
  581. const dtCrowdAgent* CrowdManager::GetDetourCrowdAgent(int agent) const
  582. {
  583. return crowd_ ? crowd_->getAgent(agent) : 0;
  584. }
  585. const dtQueryFilter* CrowdManager::GetDetourQueryFilter(unsigned queryFilterType) const
  586. {
  587. return crowd_ ? crowd_->getFilter(queryFilterType) : 0;
  588. }
  589. void CrowdManager::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  590. {
  591. // Perform update tick as long as the crowd is initialized and the associated navmesh has not been removed
  592. if (crowd_ && navigationMesh_)
  593. {
  594. using namespace SceneSubsystemUpdate;
  595. if (IsEnabledEffective())
  596. Update(eventData[P_TIMESTEP].GetFloat());
  597. }
  598. }
  599. void CrowdManager::HandleNavMeshChanged(StringHash eventType, VariantMap& eventData)
  600. {
  601. NavigationMesh* navMesh;
  602. if (eventType == E_NAVIGATION_MESH_REBUILT)
  603. {
  604. navMesh = static_cast<NavigationMesh*>(eventData[NavigationMeshRebuilt::P_MESH].GetPtr());
  605. // Reset internal pointer so that the same navmesh can be reassigned and the crowd creation be reattempted
  606. if (navMesh == navigationMesh_)
  607. navigationMesh_.Reset();
  608. }
  609. else
  610. {
  611. // eventType == E_COMPONENTREMOVED
  612. navMesh = static_cast<NavigationMesh*>(eventData[ComponentRemoved::P_COMPONENT].GetPtr());
  613. // Only interested in navmesh component being used to initialized the crowd
  614. if (navMesh != navigationMesh_)
  615. return;
  616. // Since this is a component removed event, reset our own navmesh pointer
  617. navMesh = 0;
  618. }
  619. SetNavigationMesh(navMesh);
  620. }
  621. void CrowdManager::HandleComponentAdded(StringHash eventType, VariantMap& eventData)
  622. {
  623. Scene* scene = GetScene();
  624. if (scene)
  625. {
  626. NavigationMesh* navMesh = scene->GetDerivedComponent<NavigationMesh>(true);
  627. if (navMesh)
  628. SetNavigationMesh(navMesh);
  629. }
  630. }
  631. }