CrowdNavigation.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 <Urho3D/Urho3D.h>
  23. #include <Urho3D/Core/CoreEvents.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/Graphics/AnimatedModel.h>
  26. #include <Urho3D/Graphics/AnimationController.h>
  27. #include <Urho3D/Graphics/Camera.h>
  28. #include <Urho3D/Graphics/DebugRenderer.h>
  29. #include <Urho3D/Graphics/Graphics.h>
  30. #include <Urho3D/Graphics/Light.h>
  31. #include <Urho3D/Graphics/Material.h>
  32. #include <Urho3D/Graphics/Model.h>
  33. #include <Urho3D/Graphics/Octree.h>
  34. #include <Urho3D/Graphics/Renderer.h>
  35. #include <Urho3D/Graphics/StaticModel.h>
  36. #include <Urho3D/Graphics/Zone.h>
  37. #include <Urho3D/Input/Input.h>
  38. #include <Urho3D/Math/MathDefs.h>
  39. #include <Urho3D/Navigation/CrowdAgent.h>
  40. #include <Urho3D/Navigation/CrowdManager.h>
  41. #include <Urho3D/Navigation/DynamicNavigationMesh.h>
  42. #include <Urho3D/Navigation/Navigable.h>
  43. #include <Urho3D/Navigation/NavigationEvents.h>
  44. #include <Urho3D/Navigation/Obstacle.h>
  45. #include <Urho3D/Navigation/OffMeshConnection.h>
  46. #include <Urho3D/Resource/ResourceCache.h>
  47. #include <Urho3D/Resource/XMLFile.h>
  48. #include <Urho3D/Scene/Scene.h>
  49. #include <Urho3D/UI/Cursor.h>
  50. #include <Urho3D/UI/Font.h>
  51. #include <Urho3D/UI/Text.h>
  52. #include <Urho3D/UI/UI.h>
  53. #include "CrowdNavigation.h"
  54. #include <Urho3D/DebugNew.h>
  55. static const String INSTRUCTION("instructionText");
  56. DEFINE_APPLICATION_MAIN(CrowdNavigation)
  57. CrowdNavigation::CrowdNavigation(Context* context) :
  58. Sample(context),
  59. drawDebug_(false)
  60. {
  61. }
  62. void CrowdNavigation::Start()
  63. {
  64. // Execute base class startup
  65. Sample::Start();
  66. // Create the scene content
  67. CreateScene();
  68. // Create the UI content
  69. CreateUI();
  70. // Setup the viewport for displaying the scene
  71. SetupViewport();
  72. // Hook up to the frame update and render post-update events
  73. SubscribeToEvents();
  74. }
  75. void CrowdNavigation::CreateScene()
  76. {
  77. ResourceCache* cache = GetSubsystem<ResourceCache>();
  78. scene_ = new Scene(context_);
  79. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  80. // Also create a DebugRenderer component so that we can draw debug geometry
  81. scene_->CreateComponent<Octree>();
  82. scene_->CreateComponent<DebugRenderer>();
  83. // Create scene node & StaticModel component for showing a static plane
  84. Node* planeNode = scene_->CreateChild("Plane");
  85. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  86. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  87. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  88. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  89. // Create a Zone component for ambient lighting & fog control
  90. Node* zoneNode = scene_->CreateChild("Zone");
  91. Zone* zone = zoneNode->CreateComponent<Zone>();
  92. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  93. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  94. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  95. zone->SetFogStart(100.0f);
  96. zone->SetFogEnd(300.0f);
  97. // Create a directional light to the world. Enable cascaded shadows on it
  98. Node* lightNode = scene_->CreateChild("DirectionalLight");
  99. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  100. Light* light = lightNode->CreateComponent<Light>();
  101. light->SetLightType(LIGHT_DIRECTIONAL);
  102. light->SetCastShadows(true);
  103. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  104. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  105. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  106. // Create randomly sized boxes. If boxes are big enough, make them occluders
  107. Node* boxGroup = scene_->CreateChild("Boxes");
  108. for (unsigned i = 0; i < 20; ++i)
  109. {
  110. Node* boxNode = boxGroup->CreateChild("Box");
  111. float size = 1.0f + Random(10.0f);
  112. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  113. boxNode->SetScale(size);
  114. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  115. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  116. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  117. boxObject->SetCastShadows(true);
  118. if (size >= 3.0f)
  119. boxObject->SetOccluder(true);
  120. }
  121. // Create a DynamicNavigationMesh component to the scene root
  122. DynamicNavigationMesh* navMesh = scene_->CreateComponent<DynamicNavigationMesh>();
  123. // Enable drawing debug geometry for obstacles and off-mesh connections
  124. navMesh->SetDrawObstacles(true);
  125. navMesh->SetDrawOffMeshConnections(true);
  126. // Set the agent height large enough to exclude the layers under boxes
  127. navMesh->SetAgentHeight(10.0f);
  128. // Set nav mesh cell height to minimum (allows agents to be grounded)
  129. navMesh->SetCellHeight(0.05f);
  130. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  131. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  132. scene_->CreateComponent<Navigable>();
  133. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  134. // in the scene and still update the mesh correctly
  135. navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
  136. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  137. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  138. // it will use renderable geometry instead
  139. navMesh->Build();
  140. // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  141. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  142. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  143. CreateBoxOffMeshConnections(navMesh, boxGroup);
  144. // Create some mushrooms as obstacles. Note that obstacles are non-walkable areas
  145. for (unsigned i = 0; i < 100; ++i)
  146. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  147. // Create a CrowdManager component to the scene root
  148. CrowdManager* crowdManager = scene_->CreateComponent<CrowdManager>();
  149. CrowdObstacleAvoidanceParams params = crowdManager->GetObstacleAvoidanceParams(0);
  150. // Set the params to "High (66)" setting
  151. params.velBias = 0.5f;
  152. params.adaptiveDivs = 7;
  153. params.adaptiveRings = 3;
  154. params.adaptiveDepth = 3;
  155. crowdManager->SetObstacleAvoidanceParams(0, params);
  156. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  157. CreateMovingBarrels(navMesh);
  158. // Create Jack node as crowd agent
  159. SpawnJack(Vector3(-5.0f, 0.0f, 20.0f), scene_->CreateChild("Jacks"));
  160. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside the scene, because
  161. // we want it to be unaffected by scene load / save
  162. cameraNode_ = new Node(context_);
  163. Camera* camera = cameraNode_->CreateComponent<Camera>();
  164. camera->SetFarClip(300.0f);
  165. // Set an initial position for the camera scene node above the plane and looking down
  166. cameraNode_->SetPosition(Vector3(0.0f, 50.0f, 0.0f));
  167. pitch_ = 80.0f;
  168. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  169. }
  170. void CrowdNavigation::CreateUI()
  171. {
  172. ResourceCache* cache = GetSubsystem<ResourceCache>();
  173. UI* ui = GetSubsystem<UI>();
  174. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  175. // control the camera, and when visible, it will point the raycast target
  176. XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  177. SharedPtr<Cursor> cursor(new Cursor(context_));
  178. cursor->SetStyleAuto(style);
  179. ui->SetCursor(cursor);
  180. // Set starting position of the cursor at the rendering window center
  181. Graphics* graphics = GetSubsystem<Graphics>();
  182. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  183. // Construct new Text object, set string to display and font to use
  184. Text* instructionText = ui->GetRoot()->CreateChild<Text>(INSTRUCTION);
  185. instructionText->SetText(
  186. "Use WASD keys to move, RMB to rotate view\n"
  187. "LMB to set destination, SHIFT+LMB to spawn a Jack\n"
  188. "CTRL+LMB to teleport main agent\n"
  189. "MMB to add obstacles or remove obstacles/agents\n"
  190. "F5 to save scene, F7 to load\n"
  191. "Space to toggle debug geometry\n"
  192. "F12 to toggle this instruction text"
  193. );
  194. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  195. // The text has multiple rows. Center them in relation to each other
  196. instructionText->SetTextAlignment(HA_CENTER);
  197. // Position the text relative to the screen center
  198. instructionText->SetHorizontalAlignment(HA_CENTER);
  199. instructionText->SetVerticalAlignment(VA_CENTER);
  200. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  201. }
  202. void CrowdNavigation::SetupViewport()
  203. {
  204. Renderer* renderer = GetSubsystem<Renderer>();
  205. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  206. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  207. renderer->SetViewport(0, viewport);
  208. }
  209. void CrowdNavigation::SubscribeToEvents()
  210. {
  211. // Subscribe HandleUpdate() function for processing update events
  212. SubscribeToEvent(E_UPDATE, HANDLER(CrowdNavigation, HandleUpdate));
  213. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  214. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(CrowdNavigation, HandlePostRenderUpdate));
  215. // Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
  216. // use a larger extents for finding a point on the navmesh to fix the agent's position
  217. SubscribeToEvent(E_CROWD_AGENT_FAILURE, HANDLER(CrowdNavigation, HandleCrowdAgentFailure));
  218. // Subscribe HandleCrowdAgentReposition() function for controlling the animation
  219. SubscribeToEvent(E_CROWD_AGENT_REPOSITION, HANDLER(CrowdNavigation, HandleCrowdAgentReposition));
  220. // Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation
  221. SubscribeToEvent(E_CROWD_AGENT_FORMATION, HANDLER(CrowdNavigation, HandleCrowdAgentFormation));
  222. }
  223. void CrowdNavigation::SpawnJack(const Vector3& pos, Node* jackGroup)
  224. {
  225. ResourceCache* cache = GetSubsystem<ResourceCache>();
  226. SharedPtr<Node> jackNode(jackGroup->CreateChild("Jack"));
  227. jackNode->SetPosition(pos);
  228. AnimatedModel* modelObject = jackNode->CreateComponent<AnimatedModel>();
  229. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  230. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  231. modelObject->SetCastShadows(true);
  232. jackNode->CreateComponent<AnimationController>();
  233. // Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius
  234. CrowdAgent* agent = jackNode->CreateComponent<CrowdAgent>();
  235. agent->SetHeight(2.0f);
  236. agent->SetMaxSpeed(3.0f);
  237. agent->SetMaxAccel(3.0f);
  238. }
  239. void CrowdNavigation::CreateMushroom(const Vector3& pos)
  240. {
  241. ResourceCache* cache = GetSubsystem<ResourceCache>();
  242. Node* mushroomNode = scene_->CreateChild("Mushroom");
  243. mushroomNode->SetPosition(pos);
  244. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  245. mushroomNode->SetScale(2.0f + Random(0.5f));
  246. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  247. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  248. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  249. mushroomObject->SetCastShadows(true);
  250. // Create the navigation Obstacle component and set its height & radius proportional to scale
  251. Obstacle* obstacle = mushroomNode->CreateComponent<Obstacle>();
  252. obstacle->SetRadius(mushroomNode->GetScale().x_);
  253. obstacle->SetHeight(mushroomNode->GetScale().y_);
  254. }
  255. void CrowdNavigation::CreateBoxOffMeshConnections(DynamicNavigationMesh* navMesh, Node* boxGroup)
  256. {
  257. const Vector<SharedPtr<Node> >& boxes = boxGroup->GetChildren();
  258. for (unsigned i=0; i < boxes.Size(); ++i)
  259. {
  260. Node* box = boxes[i];
  261. Vector3 boxPos = box->GetPosition();
  262. float boxHalfSize = box->GetScale().x_ / 2;
  263. // Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection.
  264. Node* connectionStart = box->CreateChild("ConnectionStart");
  265. connectionStart->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0))); // Base of box
  266. Node* connectionEnd = connectionStart->CreateChild("ConnectionEnd");
  267. connectionEnd->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0))); // Top of box
  268. // Create the OffMeshConnection component to one node and link the other node
  269. OffMeshConnection* connection = connectionStart->CreateComponent<OffMeshConnection>();
  270. connection->SetEndPoint(connectionEnd);
  271. }
  272. }
  273. void CrowdNavigation::CreateMovingBarrels(DynamicNavigationMesh* navMesh)
  274. {
  275. ResourceCache* cache = GetSubsystem<ResourceCache>();
  276. Node* barrel = scene_->CreateChild("Barrel");
  277. StaticModel* model = barrel->CreateComponent<StaticModel>();
  278. model->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
  279. Material* material = cache->GetResource<Material>("Materials/StoneTiled.xml");
  280. model->SetMaterial(material);
  281. material->SetTexture(TU_DIFFUSE, cache->GetResource<Texture2D>("Textures/TerrainDetail2.dds"));
  282. model->SetCastShadows(true);
  283. for (unsigned i = 0; i < 20; ++i)
  284. {
  285. Node* clone = barrel->Clone();
  286. float size = 0.5f + Random(1.0f);
  287. clone->SetScale(Vector3(size / 1.5f, size * 2.0f, size / 1.5f));
  288. clone->SetPosition(navMesh->FindNearestPoint(Vector3(Random(80.0f) - 40.0, size * 0.5 , Random(80.0f) - 40.0)));
  289. CrowdAgent* agent = clone->CreateComponent<CrowdAgent>();
  290. agent->SetRadius(clone->GetScale().x_ * 0.5f);
  291. agent->SetHeight(size);
  292. agent->SetNavigationQuality(NAVIGATIONQUALITY_LOW);
  293. }
  294. barrel->Remove();
  295. }
  296. void CrowdNavigation::SetPathPoint(bool spawning)
  297. {
  298. Vector3 hitPos;
  299. Drawable* hitDrawable;
  300. if (Raycast(250.0f, hitPos, hitDrawable))
  301. {
  302. DynamicNavigationMesh* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
  303. Vector3 pathPos = navMesh->FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  304. Node* jackGroup = scene_->GetChild("Jacks");
  305. if (spawning)
  306. // Spawn a jack at the target position
  307. SpawnJack(pathPos, jackGroup);
  308. else
  309. // Set crowd agents target position
  310. scene_->GetComponent<CrowdManager>()->SetCrowdTarget(pathPos, jackGroup);
  311. }
  312. }
  313. void CrowdNavigation::AddOrRemoveObject()
  314. {
  315. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  316. Vector3 hitPos;
  317. Drawable* hitDrawable;
  318. if (Raycast(250.0f, hitPos, hitDrawable))
  319. {
  320. Node* hitNode = hitDrawable->GetNode();
  321. // Note that navmesh rebuild happens when the Obstacle component is removed
  322. if (hitNode->GetName() == "Mushroom")
  323. hitNode->Remove();
  324. else if (hitNode->GetName() == "Jack")
  325. hitNode->Remove();
  326. else
  327. CreateMushroom(hitPos);
  328. }
  329. }
  330. bool CrowdNavigation::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
  331. {
  332. hitDrawable = 0;
  333. UI* ui = GetSubsystem<UI>();
  334. IntVector2 pos = ui->GetCursorPosition();
  335. // Check the cursor is visible and there is no UI element in front of the cursor
  336. if (!ui->GetCursor()->IsVisible() || ui->GetElementAt(pos, true))
  337. return false;
  338. Graphics* graphics = GetSubsystem<Graphics>();
  339. Camera* camera = cameraNode_->GetComponent<Camera>();
  340. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  341. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  342. PODVector<RayQueryResult> results;
  343. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  344. scene_->GetComponent<Octree>()->RaycastSingle(query);
  345. if (results.Size())
  346. {
  347. RayQueryResult& result = results[0];
  348. hitPos = result.position_;
  349. hitDrawable = result.drawable_;
  350. return true;
  351. }
  352. return false;
  353. }
  354. void CrowdNavigation::MoveCamera(float timeStep)
  355. {
  356. // Right mouse button controls mouse cursor visibility: hide when pressed
  357. UI* ui = GetSubsystem<UI>();
  358. Input* input = GetSubsystem<Input>();
  359. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  360. // Do not move if the UI has a focused element (the console)
  361. if (ui->GetFocusElement())
  362. return;
  363. // Movement speed as world units per second
  364. const float MOVE_SPEED = 20.0f;
  365. // Mouse sensitivity as degrees per pixel
  366. const float MOUSE_SENSITIVITY = 0.1f;
  367. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  368. // Only move the camera when the cursor is hidden
  369. if (!ui->GetCursor()->IsVisible())
  370. {
  371. IntVector2 mouseMove = input->GetMouseMove();
  372. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  373. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  374. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  375. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  376. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  377. }
  378. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  379. if (input->GetKeyDown('W'))
  380. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  381. if (input->GetKeyDown('S'))
  382. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  383. if (input->GetKeyDown('A'))
  384. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  385. if (input->GetKeyDown('D'))
  386. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  387. // Set destination or spawn a new jack with left mouse button
  388. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  389. SetPathPoint(input->GetQualifierDown(QUAL_SHIFT));
  390. // Add new obstacle or remove existing obstacle/agent with middle mouse button
  391. else if (input->GetMouseButtonPress(MOUSEB_MIDDLE))
  392. AddOrRemoveObject();
  393. // Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory
  394. if (input->GetKeyPress(KEY_F5))
  395. {
  396. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_WRITE);
  397. scene_->SaveXML(saveFile);
  398. }
  399. else if (input->GetKeyPress(KEY_F7))
  400. {
  401. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_READ);
  402. scene_->LoadXML(loadFile);
  403. }
  404. // Toggle debug geometry with space
  405. else if (input->GetKeyPress(KEY_SPACE))
  406. drawDebug_ = !drawDebug_;
  407. // Toggle instruction text with F12
  408. else if (input->GetKeyPress(KEY_F12))
  409. {
  410. UIElement* instruction = ui->GetRoot()->GetChild(INSTRUCTION);
  411. instruction->SetVisible(!instruction->IsVisible());
  412. }
  413. }
  414. void CrowdNavigation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  415. {
  416. using namespace Update;
  417. // Take the frame time step, which is stored as a float
  418. float timeStep = eventData[P_TIMESTEP].GetFloat();
  419. // Move the camera, scale movement with time step
  420. MoveCamera(timeStep);
  421. }
  422. void CrowdNavigation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  423. {
  424. if (drawDebug_)
  425. {
  426. // Visualize navigation mesh, obstacles and off-mesh connections
  427. scene_->GetComponent<DynamicNavigationMesh>()->DrawDebugGeometry(true);
  428. // Visualize agents' path and position to reach
  429. scene_->GetComponent<CrowdManager>()->DrawDebugGeometry(true);
  430. }
  431. }
  432. void CrowdNavigation::HandleCrowdAgentFailure(StringHash eventType, VariantMap& eventData)
  433. {
  434. using namespace CrowdAgentFailure;
  435. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  436. CrowdAgentState agentState = (CrowdAgentState)eventData[P_CROWD_AGENT_STATE].GetInt();
  437. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  438. if (agentState == CA_STATE_INVALID)
  439. {
  440. // Get a point on the navmesh using more generous extents
  441. Vector3 newPos = scene_->GetComponent<DynamicNavigationMesh>()->FindNearestPoint(node->GetPosition(), Vector3(5.0f, 5.0f, 5.0f));
  442. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  443. node->SetPosition(newPos);
  444. }
  445. }
  446. void CrowdNavigation::HandleCrowdAgentReposition(StringHash eventType, VariantMap& eventData)
  447. {
  448. static const char* WALKING_ANI = "Models/Jack_Walk.ani";
  449. using namespace CrowdAgentReposition;
  450. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  451. CrowdAgent* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
  452. Vector3 velocity = eventData[P_VELOCITY].GetVector3();
  453. float timeStep = eventData[P_TIMESTEP].GetFloat();
  454. // Only Jack agent has animation controller
  455. AnimationController* animCtrl = node->GetComponent<AnimationController>();
  456. if (animCtrl)
  457. {
  458. float speed = velocity.Length();
  459. if (animCtrl->IsPlaying(WALKING_ANI))
  460. {
  461. float speedRatio = speed / agent->GetMaxSpeed();
  462. // Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep
  463. node->SetRotation(node->GetRotation().Slerp(Quaternion(Vector3::FORWARD, velocity), 10.0f * timeStep * speedRatio));
  464. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  465. animCtrl->SetSpeed(WALKING_ANI, speedRatio);
  466. }
  467. else
  468. animCtrl->Play(WALKING_ANI, 0, true, 0.1f);
  469. // If speed is too low then stopping the animation
  470. if (speed < agent->GetRadius())
  471. animCtrl->Stop(WALKING_ANI, 0.8f);
  472. }
  473. }
  474. void CrowdNavigation::HandleCrowdAgentFormation(StringHash eventType, VariantMap& eventData)
  475. {
  476. using namespace CrowdAgentFormation;
  477. unsigned index = eventData[P_INDEX].GetUInt();
  478. unsigned size = eventData[P_SIZE].GetUInt();
  479. Vector3 position = eventData[P_POSITION].GetVector3();
  480. // The first agent will always move to the exact position, all other agents will select a random point nearby
  481. if (index)
  482. {
  483. CrowdManager* crowdManager = static_cast<CrowdManager*>(GetEventSender());
  484. CrowdAgent* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
  485. eventData[P_POSITION] = crowdManager->GetRandomPointInCircle(position, agent->GetRadius(), agent->GetQueryFilterType());
  486. }
  487. }