CrowdNavigation.cpp 26 KB

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