CrowdManager.cpp 26 KB

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