Navigation.cpp 16 KB

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