Navigation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/AnimatedModel.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Graphics/DebugRenderer.h>
  27. #include <Urho3D/Graphics/Graphics.h>
  28. #include <Urho3D/Graphics/Light.h>
  29. #include <Urho3D/Graphics/Material.h>
  30. #include <Urho3D/Graphics/Octree.h>
  31. #include <Urho3D/Graphics/Renderer.h>
  32. #include <Urho3D/Graphics/Zone.h>
  33. #include <Urho3D/Input/Input.h>
  34. #include <Urho3D/Navigation/Navigable.h>
  35. #include <Urho3D/Navigation/NavigationMesh.h>
  36. #include <Urho3D/Resource/ResourceCache.h>
  37. #include <Urho3D/Scene/Scene.h>
  38. #include <Urho3D/UI/Font.h>
  39. #include <Urho3D/UI/Text.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include "Navigation.h"
  42. #include <Urho3D/DebugNew.h>
  43. DEFINE_APPLICATION_MAIN(Navigation)
  44. Navigation::Navigation(Context* context) :
  45. Sample(context),
  46. drawDebug_(false)
  47. {
  48. }
  49. void Navigation::Start()
  50. {
  51. // Execute base class startup
  52. Sample::Start();
  53. // Create the scene content
  54. CreateScene();
  55. // Create the UI content
  56. CreateUI();
  57. // Setup the viewport for displaying the scene
  58. SetupViewport();
  59. // Hook up to the frame update and render post-update events
  60. SubscribeToEvents();
  61. }
  62. void Navigation::CreateScene()
  63. {
  64. ResourceCache* cache = GetSubsystem<ResourceCache>();
  65. scene_ = new Scene(context_);
  66. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  67. // Also create a DebugRenderer component so that we can draw debug geometry
  68. scene_->CreateComponent<Octree>();
  69. scene_->CreateComponent<DebugRenderer>();
  70. // Create scene node & StaticModel component for showing a static plane
  71. Node* planeNode = scene_->CreateChild("Plane");
  72. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  73. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  74. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  75. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  76. // Create a Zone component for ambient lighting & fog control
  77. Node* zoneNode = scene_->CreateChild("Zone");
  78. Zone* zone = zoneNode->CreateComponent<Zone>();
  79. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  80. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  81. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  82. zone->SetFogStart(100.0f);
  83. zone->SetFogEnd(300.0f);
  84. // Create a directional light to the world. Enable cascaded shadows on it
  85. Node* lightNode = scene_->CreateChild("DirectionalLight");
  86. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  87. Light* light = lightNode->CreateComponent<Light>();
  88. light->SetLightType(LIGHT_DIRECTIONAL);
  89. light->SetCastShadows(true);
  90. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  91. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  92. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  93. // Create some mushrooms
  94. const unsigned NUM_MUSHROOMS = 100;
  95. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  96. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  97. // Create randomly sized boxes. If boxes are big enough, make them occluders
  98. const unsigned NUM_BOXES = 20;
  99. for (unsigned i = 0; i < NUM_BOXES; ++i)
  100. {
  101. Node* boxNode = scene_->CreateChild("Box");
  102. float size = 1.0f + Random(10.0f);
  103. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  104. boxNode->SetScale(size);
  105. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  106. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  107. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  108. boxObject->SetCastShadows(true);
  109. if (size >= 3.0f)
  110. boxObject->SetOccluder(true);
  111. }
  112. // Create Jack node that will follow the path
  113. jackNode_ = scene_->CreateChild("Jack");
  114. jackNode_->SetPosition(Vector3(-5.0f, 0.0f, 20.0f));
  115. AnimatedModel* modelObject = jackNode_->CreateComponent<AnimatedModel>();
  116. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  117. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  118. modelObject->SetCastShadows(true);
  119. // Create a NavigationMesh component to the scene root
  120. NavigationMesh* navMesh = scene_->CreateComponent<NavigationMesh>();
  121. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  122. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  123. scene_->CreateComponent<Navigable>();
  124. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  125. // in the scene and still update the mesh correctly
  126. navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
  127. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  128. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  129. // it will use renderable geometry instead
  130. navMesh->Build();
  131. // Create the camera. Limit far clip distance to match the fog
  132. cameraNode_ = scene_->CreateChild("Camera");
  133. Camera* camera = cameraNode_->CreateComponent<Camera>();
  134. camera->SetFarClip(300.0f);
  135. // Set an initial position for the camera scene node above the plane and looking down
  136. cameraNode_->SetPosition(Vector3(0.0f, 50.0f, 0.0f));
  137. pitch_ = 80.0f;
  138. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  139. }
  140. void Navigation::CreateUI()
  141. {
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. UI* ui = GetSubsystem<UI>();
  144. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  145. // control the camera, and when visible, it will point the raycast target
  146. XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  147. SharedPtr<Cursor> cursor(new Cursor(context_));
  148. cursor->SetStyleAuto(style);
  149. ui->SetCursor(cursor);
  150. // Set starting position of the cursor at the rendering window center
  151. Graphics* graphics = GetSubsystem<Graphics>();
  152. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  153. // Construct new Text object, set string to display and font to use
  154. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  155. instructionText->SetText(
  156. "Use WASD keys to move, RMB to rotate view\n"
  157. "LMB to set destination, SHIFT+LMB to teleport\n"
  158. "MMB to add or remove obstacles\n"
  159. "Space to toggle debug geometry"
  160. );
  161. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  162. // The text has multiple rows. Center them in relation to each other
  163. instructionText->SetTextAlignment(HA_CENTER);
  164. // Position the text relative to the screen center
  165. instructionText->SetHorizontalAlignment(HA_CENTER);
  166. instructionText->SetVerticalAlignment(VA_CENTER);
  167. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  168. }
  169. void Navigation::SetupViewport()
  170. {
  171. Renderer* renderer = GetSubsystem<Renderer>();
  172. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  173. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  174. renderer->SetViewport(0, viewport);
  175. }
  176. void Navigation::SubscribeToEvents()
  177. {
  178. // Subscribe HandleUpdate() function for processing update events
  179. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Navigation, HandleUpdate));
  180. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  181. // debug geometry
  182. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Navigation, HandlePostRenderUpdate));
  183. }
  184. void Navigation::MoveCamera(float timeStep)
  185. {
  186. // Right mouse button controls mouse cursor visibility: hide when pressed
  187. UI* ui = GetSubsystem<UI>();
  188. Input* input = GetSubsystem<Input>();
  189. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  190. // Do not move if the UI has a focused element (the console)
  191. if (ui->GetFocusElement())
  192. return;
  193. // Movement speed as world units per second
  194. const float MOVE_SPEED = 20.0f;
  195. // Mouse sensitivity as degrees per pixel
  196. const float MOUSE_SENSITIVITY = 0.1f;
  197. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  198. // Only move the camera when the cursor is hidden
  199. if (!ui->GetCursor()->IsVisible())
  200. {
  201. IntVector2 mouseMove = input->GetMouseMove();
  202. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  203. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  204. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  205. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  206. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  207. }
  208. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  209. if (input->GetKeyDown('W'))
  210. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  211. if (input->GetKeyDown('S'))
  212. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  213. if (input->GetKeyDown('A'))
  214. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  215. if (input->GetKeyDown('D'))
  216. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  217. // Set destination or teleport with left mouse button
  218. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  219. SetPathPoint();
  220. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  221. if (input->GetMouseButtonPress(MOUSEB_MIDDLE))
  222. AddOrRemoveObject();
  223. // Toggle debug geometry with space
  224. if (input->GetKeyPress(KEY_SPACE))
  225. drawDebug_ = !drawDebug_;
  226. }
  227. void Navigation::SetPathPoint()
  228. {
  229. Vector3 hitPos;
  230. Drawable* hitDrawable;
  231. NavigationMesh* navMesh = scene_->GetComponent<NavigationMesh>();
  232. if (Raycast(250.0f, hitPos, hitDrawable))
  233. {
  234. Vector3 pathPos = navMesh->FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  235. if (GetSubsystem<Input>()->GetQualifierDown(QUAL_SHIFT))
  236. {
  237. // Teleport
  238. currentPath_.Clear();
  239. jackNode_->LookAt(Vector3(pathPos.x_, jackNode_->GetPosition().y_, pathPos.z_), Vector3::UP);
  240. jackNode_->SetPosition(pathPos);
  241. }
  242. else
  243. {
  244. // Calculate path from Jack's current position to the end point
  245. endPos_ = pathPos;
  246. navMesh->FindPath(currentPath_, jackNode_->GetPosition(), endPos_);
  247. }
  248. }
  249. }
  250. void Navigation::AddOrRemoveObject()
  251. {
  252. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  253. Vector3 hitPos;
  254. Drawable* hitDrawable;
  255. if (Raycast(250.0f, hitPos, hitDrawable))
  256. {
  257. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  258. // drawable component
  259. BoundingBox updateBox;
  260. Node* hitNode = hitDrawable->GetNode();
  261. if (hitNode->GetName() == "Mushroom")
  262. {
  263. updateBox = hitDrawable->GetWorldBoundingBox();
  264. hitNode->Remove();
  265. }
  266. else
  267. {
  268. Node* newNode = CreateMushroom(hitPos);
  269. updateBox = newNode->GetComponent<StaticModel>()->GetWorldBoundingBox();
  270. }
  271. // Rebuild part of the navigation mesh, then recalculate path if applicable
  272. NavigationMesh* navMesh = scene_->GetComponent<NavigationMesh>();
  273. navMesh->Build(updateBox);
  274. if (currentPath_.Size())
  275. navMesh->FindPath(currentPath_, jackNode_->GetPosition(), endPos_);
  276. }
  277. }
  278. Node* Navigation::CreateMushroom(const Vector3& pos)
  279. {
  280. ResourceCache* cache = GetSubsystem<ResourceCache>();
  281. Node* mushroomNode = scene_->CreateChild("Mushroom");
  282. mushroomNode->SetPosition(pos);
  283. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  284. mushroomNode->SetScale(2.0f + Random(0.5f));
  285. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  286. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  287. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  288. mushroomObject->SetCastShadows(true);
  289. return mushroomNode;
  290. }
  291. bool Navigation::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
  292. {
  293. hitDrawable = 0;
  294. UI* ui = GetSubsystem<UI>();
  295. IntVector2 pos = ui->GetCursorPosition();
  296. // Check the cursor is visible and there is no UI element in front of the cursor
  297. if (!ui->GetCursor()->IsVisible() || ui->GetElementAt(pos, true))
  298. return false;
  299. Graphics* graphics = GetSubsystem<Graphics>();
  300. Camera* camera = cameraNode_->GetComponent<Camera>();
  301. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  302. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  303. PODVector<RayQueryResult> results;
  304. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  305. scene_->GetComponent<Octree>()->RaycastSingle(query);
  306. if (results.Size())
  307. {
  308. RayQueryResult& result = results[0];
  309. hitPos = result.position_;
  310. hitDrawable = result.drawable_;
  311. return true;
  312. }
  313. return false;
  314. }
  315. void Navigation::FollowPath(float timeStep)
  316. {
  317. if (currentPath_.Size())
  318. {
  319. Vector3 nextWaypoint = currentPath_[0]; // NB: currentPath[0] is the next waypoint in order
  320. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  321. float move = 5.0f * timeStep;
  322. float distance = (jackNode_->GetPosition() - nextWaypoint).Length();
  323. if (move > distance)
  324. move = distance;
  325. jackNode_->LookAt(nextWaypoint, Vector3::UP);
  326. jackNode_->Translate(Vector3::FORWARD * move);
  327. // Remove waypoint if reached it
  328. if (distance < 0.1f)
  329. currentPath_.Erase(0);
  330. }
  331. }
  332. void Navigation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  333. {
  334. using namespace Update;
  335. // Take the frame time step, which is stored as a float
  336. float timeStep = eventData[P_TIMESTEP].GetFloat();
  337. // Move the camera, scale movement with time step
  338. MoveCamera(timeStep);
  339. // Make Jack follow the Detour path
  340. FollowPath(timeStep);
  341. }
  342. void Navigation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  343. {
  344. // If draw debug mode is enabled, draw navigation mesh debug geometry
  345. if (drawDebug_)
  346. scene_->GetComponent<NavigationMesh>()->DrawDebugGeometry(true);
  347. if (currentPath_.Size())
  348. {
  349. // Visualize the current calculated path
  350. DebugRenderer* debug = scene_->GetComponent<DebugRenderer>();
  351. debug->AddBoundingBox(BoundingBox(endPos_ - Vector3(0.1f, 0.1f, 0.1f), endPos_ + Vector3(0.1f, 0.1f, 0.1f)),
  352. Color(1.0f, 1.0f, 1.0f));
  353. // Draw the path with a small upward bias so that it does not clip into the surfaces
  354. Vector3 bias(0.0f, 0.05f, 0.0f);
  355. debug->AddLine(jackNode_->GetPosition() + bias, currentPath_[0] + bias, Color(1.0f, 1.0f, 1.0f));
  356. if (currentPath_.Size() > 1)
  357. {
  358. for (unsigned i = 0; i < currentPath_.Size() - 1; ++i)
  359. debug->AddLine(currentPath_[i] + bias, currentPath_[i + 1] + bias, Color(1.0f, 1.0f, 1.0f));
  360. }
  361. }
  362. }