CrowdAgent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. //
  2. // Copyright (c) 2008-2015 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 "../Scene/Component.h"
  23. #include "../Core/Context.h"
  24. #include "../Navigation/CrowdAgent.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../Navigation/DetourCrowdManager.h"
  27. #include "../IO/Log.h"
  28. #include "../IO/MemoryBuffer.h"
  29. #include "../Navigation/NavigationEvents.h"
  30. #include "../Scene/Node.h"
  31. #include "../Core/Profiler.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/Serializable.h"
  34. #include "../Core/Variant.h"
  35. #include <Detour/include/DetourCommon.h>
  36. #include <DetourCrowd/include/DetourCrowd.h>
  37. #include "../DebugNew.h"
  38. namespace Atomic
  39. {
  40. extern const char* NAVIGATION_CATEGORY;
  41. static const unsigned DEFAULT_AGENT_NAVIGATION_FILTER_TYPE = 0;
  42. static const float DEFAULT_AGENT_MAX_SPEED = 0.f;
  43. static const float DEFAULT_AGENT_MAX_ACCEL = 0.f;
  44. static const NavigationQuality DEFAULT_AGENT_AVOIDANCE_QUALITY = NAVIGATIONQUALITY_HIGH;
  45. static const NavigationPushiness DEFAULT_AGENT_NAVIGATION_PUSHINESS = PUSHINESS_MEDIUM;
  46. const char* crowdAgentAvoidanceQualityNames[] = {
  47. "low",
  48. "medium",
  49. "high",
  50. 0
  51. };
  52. const char* crowdAgentPushinessNames[] = {
  53. "low",
  54. "medium",
  55. "high",
  56. 0
  57. };
  58. CrowdAgent::CrowdAgent(Context* context) :
  59. Component(context),
  60. inCrowd_(false),
  61. agentCrowdId_(-1),
  62. targetRef_(-1),
  63. updateNodePosition_(true),
  64. maxAccel_(DEFAULT_AGENT_MAX_ACCEL),
  65. maxSpeed_(DEFAULT_AGENT_MAX_SPEED),
  66. radius_(0.0f),
  67. height_(0.0f),
  68. filterType_(DEFAULT_AGENT_NAVIGATION_FILTER_TYPE),
  69. navQuality_(DEFAULT_AGENT_AVOIDANCE_QUALITY),
  70. navPushiness_(DEFAULT_AGENT_NAVIGATION_PUSHINESS),
  71. previousTargetState_(CROWD_AGENT_TARGET_NONE),
  72. previousAgentState_(CROWD_AGENT_READY),
  73. ignoreTransformChanges_(false)
  74. {
  75. }
  76. CrowdAgent::~CrowdAgent()
  77. {
  78. RemoveAgentFromCrowd();
  79. }
  80. void CrowdAgent::RegisterObject(Context* context)
  81. {
  82. context->RegisterFactory<CrowdAgent>(NAVIGATION_CATEGORY);
  83. ACCESSOR_ATTRIBUTE("Max Accel", GetMaxAccel, SetMaxAccel, float, DEFAULT_AGENT_MAX_ACCEL, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE("Max Speed", GetMaxSpeed, SetMaxSpeed, float, DEFAULT_AGENT_MAX_SPEED, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE("Radius", GetRadius, SetRadius, float, 0.0f, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE("Height", GetHeight, SetHeight, float, 0.0f, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE("Target Position", GetTargetPosition, SetMoveTarget, Vector3, Vector3::ZERO, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE("Navigation Filter", GetNavigationFilterType, SetNavigationFilterType, unsigned, DEFAULT_AGENT_NAVIGATION_FILTER_TYPE, AM_DEFAULT);
  89. ENUM_ACCESSOR_ATTRIBUTE("Navigation Pushiness", GetNavigationPushiness, SetNavigationPushiness, NavigationPushiness, crowdAgentPushinessNames, PUSHINESS_LOW, AM_DEFAULT);
  90. ENUM_ACCESSOR_ATTRIBUTE("Navigation Quality", GetNavigationQuality, SetNavigationQuality, NavigationQuality, crowdAgentAvoidanceQualityNames, NAVIGATIONQUALITY_LOW, AM_DEFAULT);
  91. MIXED_ACCESSOR_ATTRIBUTE("Agent Data", GetAgentDataAttr, SetAgentDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  92. }
  93. void CrowdAgent::OnNodeSet(Node* node)
  94. {
  95. if (node)
  96. {
  97. Scene* scene = GetScene();
  98. if (scene)
  99. {
  100. if (scene == node)
  101. LOGERROR(GetTypeName() + " should not be created to the root scene node");
  102. crowdManager_ = scene->GetOrCreateComponent<DetourCrowdManager>();
  103. AddAgentToCrowd();
  104. }
  105. node->AddListener(this);
  106. }
  107. else
  108. RemoveAgentFromCrowd();
  109. }
  110. void CrowdAgent::OnSetEnabled()
  111. {
  112. bool enabled = IsEnabledEffective();
  113. if (enabled && !inCrowd_)
  114. AddAgentToCrowd();
  115. else if (!enabled && inCrowd_)
  116. RemoveAgentFromCrowd();
  117. }
  118. void CrowdAgent::DrawDebugGeometry(bool depthTest)
  119. {
  120. Scene* scene = GetScene();
  121. if (scene)
  122. {
  123. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  124. if (debug)
  125. DrawDebugGeometry(debug, depthTest);
  126. }
  127. }
  128. void CrowdAgent::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  129. {
  130. if (node_)
  131. {
  132. const Vector3 pos = GetPosition();
  133. const Vector3 vel = GetActualVelocity();
  134. const Vector3 desiredVel = GetDesiredVelocity();
  135. const Vector3 agentHeightVec(0, height_, 0);
  136. debug->AddLine(pos + 0.5f * agentHeightVec, pos + vel + 0.5f * agentHeightVec, Color::GREEN, depthTest);
  137. debug->AddLine(pos + 0.25f * agentHeightVec, pos + desiredVel + 0.25f * agentHeightVec, Color::RED, depthTest);
  138. debug->AddCylinder(pos, radius_, height_, HasArrived() ? Color::GREEN : Color::WHITE, depthTest);
  139. }
  140. }
  141. const dtCrowdAgent* CrowdAgent::GetDetourCrowdAgent() const
  142. {
  143. return crowdManager_ && inCrowd_ ? crowdManager_->GetCrowdAgent(agentCrowdId_) : 0;
  144. }
  145. void CrowdAgent::AddAgentToCrowd()
  146. {
  147. if (!crowdManager_ || !crowdManager_->crowd_ || !node_)
  148. return;
  149. PROFILE(AddAgentToCrowd);
  150. if (!inCrowd_)
  151. {
  152. inCrowd_ = true;
  153. agentCrowdId_ = crowdManager_->AddAgent(this, node_->GetPosition());
  154. if (agentCrowdId_ == -1)
  155. {
  156. inCrowd_ = false;
  157. LOGERROR("AddAgentToCrowd: Could not add agent to crowd");
  158. return;
  159. }
  160. crowdManager_->UpdateAgentNavigationQuality(this, navQuality_);
  161. crowdManager_->UpdateAgentPushiness(this, navPushiness_);
  162. previousAgentState_ = GetAgentState();
  163. previousTargetState_ = GetTargetState();
  164. // Agent created, but initial state is invalid and needs to be addressed
  165. if (previousAgentState_ == CROWD_AGENT_INVALID)
  166. {
  167. VariantMap& map = GetContext()->GetEventDataMap();
  168. map[CrowdAgentFailure::P_NODE] = GetNode();
  169. map[CrowdAgentFailure::P_CROWD_AGENT] = this;
  170. map[CrowdAgentFailure::P_CROWD_TARGET_STATE] = previousTargetState_;
  171. map[CrowdAgentFailure::P_CROWD_AGENT_STATE] = previousAgentState_;
  172. map[CrowdAgentFailure::P_POSITION] = GetPosition();
  173. map[CrowdAgentFailure::P_VELOCITY] = GetActualVelocity();
  174. SendEvent(E_CROWD_AGENT_FAILURE, map);
  175. // Reevaluate states as handling of event may have resulted in changes
  176. previousAgentState_ = GetAgentState();
  177. previousTargetState_ = GetTargetState();
  178. }
  179. // Save the initial position to prevent CrowdAgentReposition event being triggered unnecessarily
  180. previousPosition_ = GetPosition();
  181. }
  182. }
  183. void CrowdAgent::RemoveAgentFromCrowd()
  184. {
  185. if (crowdManager_ && agentCrowdId_ != -1 && inCrowd_)
  186. {
  187. crowdManager_->RemoveAgent(this);
  188. inCrowd_ = false;
  189. agentCrowdId_ = -1;
  190. }
  191. }
  192. void CrowdAgent::SetNavigationFilterType(unsigned filterType)
  193. {
  194. filterType_ = filterType;
  195. if (crowdManager_ && inCrowd_)
  196. {
  197. // If in the crowd it's necessary to force the update of the query filter
  198. dtCrowdAgentParams params = crowdManager_->GetCrowdAgent(agentCrowdId_)->params;
  199. params.queryFilterType = (unsigned char)filterType;
  200. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  201. MarkNetworkUpdate();
  202. }
  203. }
  204. void CrowdAgent::SetMoveTarget(const Vector3& position)
  205. {
  206. if (crowdManager_) {
  207. if (!inCrowd_)
  208. AddAgentToCrowd();
  209. targetPosition_ = position;
  210. if (crowdManager_->SetAgentTarget(this, position, targetRef_))
  211. MarkNetworkUpdate();
  212. }
  213. }
  214. void CrowdAgent::ResetMoveTarget()
  215. {
  216. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  217. if (agent && agent->active)
  218. {
  219. targetPosition_ = Vector3::ZERO;
  220. crowdManager_->GetCrowd()->resetMoveTarget(agentCrowdId_);
  221. MarkNetworkUpdate();
  222. }
  223. }
  224. void CrowdAgent::SetMoveVelocity(const Vector3& velocity)
  225. {
  226. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  227. if (agent && agent->active)
  228. {
  229. crowdManager_->GetCrowd()->requestMoveVelocity(agentCrowdId_, velocity.Data());
  230. MarkNetworkUpdate();
  231. }
  232. }
  233. void CrowdAgent::SetMaxSpeed(float speed)
  234. {
  235. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  236. if (agent)
  237. {
  238. maxSpeed_ = speed;
  239. dtCrowdAgentParams params = agent->params;
  240. params.maxSpeed = speed;
  241. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  242. MarkNetworkUpdate();
  243. }
  244. }
  245. void CrowdAgent::SetMaxAccel(float accel)
  246. {
  247. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  248. if (agent)
  249. {
  250. maxAccel_ = accel;
  251. dtCrowdAgentParams params = agent->params;
  252. params.maxAcceleration = accel;
  253. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  254. MarkNetworkUpdate();
  255. }
  256. }
  257. void CrowdAgent::SetRadius(float radius)
  258. {
  259. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  260. if (agent)
  261. {
  262. radius_ = radius;
  263. dtCrowdAgentParams params = agent->params;
  264. params.radius = radius;
  265. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  266. MarkNetworkUpdate();
  267. }
  268. }
  269. void CrowdAgent::SetHeight(float height)
  270. {
  271. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  272. if (agent)
  273. {
  274. height_ = height;
  275. dtCrowdAgentParams params = agent->params;
  276. params.height = height;
  277. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  278. MarkNetworkUpdate();
  279. }
  280. }
  281. void CrowdAgent::SetNavigationQuality(NavigationQuality val)
  282. {
  283. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  284. if (agent)
  285. {
  286. navQuality_ = val;
  287. crowdManager_->UpdateAgentNavigationQuality(this, navQuality_);
  288. MarkNetworkUpdate();
  289. }
  290. }
  291. void CrowdAgent::SetNavigationPushiness(NavigationPushiness val)
  292. {
  293. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  294. if (agent)
  295. {
  296. navPushiness_ = val;
  297. crowdManager_->UpdateAgentPushiness(this, navPushiness_);
  298. MarkNetworkUpdate();
  299. }
  300. }
  301. Vector3 CrowdAgent::GetPosition() const
  302. {
  303. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  304. return agent && agent->active ? Vector3(agent->npos) : node_->GetPosition();
  305. }
  306. Vector3 CrowdAgent::GetDesiredVelocity() const
  307. {
  308. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  309. return agent && agent->active ? Vector3(agent->dvel) : Vector3::ZERO;
  310. }
  311. Vector3 CrowdAgent::GetActualVelocity() const
  312. {
  313. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  314. return agent && agent->active ? Vector3(agent->vel) : Vector3::ZERO;
  315. }
  316. Atomic::CrowdAgentState CrowdAgent::GetAgentState() const
  317. {
  318. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  319. return agent && agent->active ? (CrowdAgentState)agent->state : CROWD_AGENT_INVALID;
  320. }
  321. Atomic::CrowdTargetState CrowdAgent::GetTargetState() const
  322. {
  323. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  324. return agent && agent->active ? (CrowdTargetState)agent->targetState : CROWD_AGENT_TARGET_NONE;
  325. }
  326. bool CrowdAgent::HasArrived() const
  327. {
  328. // Is the agent at or near the end of its path?
  329. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  330. return agent && agent->active && (!agent->ncorners ||
  331. (agent->cornerFlags[agent->ncorners - 1] & DT_STRAIGHTPATH_END &&
  332. Equals(dtVdist2D(agent->npos, &agent->cornerVerts[(agent->ncorners - 1) * 3]), 0.f)));
  333. }
  334. void CrowdAgent::SetUpdateNodePosition(bool unodepos)
  335. {
  336. updateNodePosition_ = unodepos;
  337. MarkNetworkUpdate();
  338. }
  339. void CrowdAgent::OnCrowdAgentReposition(const Vector3& newPos, const Vector3& newVel)
  340. {
  341. if (node_)
  342. {
  343. // Notify parent node of the reposition
  344. if (newPos != previousPosition_)
  345. {
  346. previousPosition_ = newPos;
  347. VariantMap& map = GetContext()->GetEventDataMap();
  348. map[CrowdAgentReposition::P_NODE] = GetNode();
  349. map[CrowdAgentReposition::P_CROWD_AGENT] = this;
  350. map[CrowdAgentReposition::P_POSITION] = newPos;
  351. map[CrowdAgentReposition::P_VELOCITY] = newVel;
  352. map[CrowdAgentReposition::P_ARRIVED] = HasArrived();
  353. SendEvent(E_CROWD_AGENT_REPOSITION, map);
  354. if (updateNodePosition_)
  355. {
  356. ignoreTransformChanges_ = true;
  357. node_->SetPosition(newPos);
  358. ignoreTransformChanges_ = false;
  359. }
  360. }
  361. // Send a notification event if we've reached the destination
  362. CrowdTargetState newTargetState = GetTargetState();
  363. CrowdAgentState newAgentState = GetAgentState();
  364. if (newAgentState != previousAgentState_ || newTargetState != previousTargetState_)
  365. {
  366. VariantMap& map = GetContext()->GetEventDataMap();
  367. map[CrowdAgentStateChanged::P_NODE] = GetNode();
  368. map[CrowdAgentStateChanged::P_CROWD_AGENT] = this;
  369. map[CrowdAgentStateChanged::P_CROWD_TARGET_STATE] = newTargetState;
  370. map[CrowdAgentStateChanged::P_CROWD_AGENT_STATE] = newAgentState;
  371. map[CrowdAgentStateChanged::P_POSITION] = newPos;
  372. map[CrowdAgentStateChanged::P_VELOCITY] = newVel;
  373. SendEvent(E_CROWD_AGENT_STATE_CHANGED, map);
  374. // Send a failure event if either state is a failed status
  375. if (newAgentState == CROWD_AGENT_INVALID || newTargetState == CROWD_AGENT_TARGET_FAILED)
  376. {
  377. VariantMap& map = GetContext()->GetEventDataMap();
  378. map[CrowdAgentFailure::P_NODE] = GetNode();
  379. map[CrowdAgentFailure::P_CROWD_AGENT] = this;
  380. map[CrowdAgentFailure::P_CROWD_TARGET_STATE] = newTargetState;
  381. map[CrowdAgentFailure::P_CROWD_AGENT_STATE] = newAgentState;
  382. map[CrowdAgentFailure::P_POSITION] = newPos;
  383. map[CrowdAgentFailure::P_VELOCITY] = newVel;
  384. SendEvent(E_CROWD_AGENT_FAILURE, map);
  385. }
  386. // State may have been altered during the handling of the event
  387. previousAgentState_ = GetAgentState();
  388. previousTargetState_ = GetTargetState();
  389. }
  390. }
  391. }
  392. PODVector<unsigned char> CrowdAgent::GetAgentDataAttr() const
  393. {
  394. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  395. if (!agent)
  396. return Variant::emptyBuffer;
  397. // Reading it back in isn't this simple, see SetAgentDataAttr
  398. VectorBuffer ret;
  399. ret.Write(agent, sizeof(dtCrowdAgent));
  400. return ret.GetBuffer();
  401. }
  402. void CrowdAgent::SetAgentDataAttr(const PODVector<unsigned char>& value)
  403. {
  404. if (value.Empty())
  405. return;
  406. dtCrowdAgent* agent = const_cast<dtCrowdAgent*>(GetDetourCrowdAgent());
  407. if (!agent)
  408. return;
  409. MemoryBuffer buffer(value);
  410. // Path corridor is tricky
  411. char corridorData[sizeof(dtPathCorridor)];
  412. // Duplicate the existing path corridor into a block
  413. memcpy(corridorData, &agent->corridor, sizeof(dtPathCorridor));
  414. // Read the entire block of the crowd agent
  415. buffer.Read(agent, sizeof(dtCrowdAgent));
  416. // Restore the values of the original path corridor
  417. memcpy(&agent->corridor, corridorData, sizeof(dtPathCorridor));
  418. // Tell the path corridor to rebuild the path, it will reevaluate the path, existing velocities maintained
  419. agent->corridor.reset(agent->targetRef, agent->targetPos);
  420. agent->params.userData = this;
  421. }
  422. void CrowdAgent::OnMarkedDirty(Node* node)
  423. {
  424. if (!ignoreTransformChanges_ && IsEnabledEffective())
  425. {
  426. dtCrowdAgent* agent = const_cast<dtCrowdAgent*>(GetDetourCrowdAgent());
  427. if (agent)
  428. {
  429. memcpy(agent->npos, node->GetWorldPosition().Data(), sizeof(float) * 3);
  430. // If the node has been externally altered, provide the opportunity for DetourCrowd to reevaluate the crowd agent
  431. if (agent->state == CROWD_AGENT_INVALID)
  432. agent->state = CROWD_AGENT_READY;
  433. }
  434. }
  435. }
  436. }