15_Navigation.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using AtomicEngine;
  27. namespace FeatureExamples
  28. {
  29. public class NavigationSample : Sample
  30. {
  31. Scene scene;
  32. float yaw;
  33. float pitch;
  34. bool drawDebug;
  35. Node jackNode;
  36. Vector3 endPos;
  37. List<Vector3> currentPath = new List<Vector3>();
  38. public NavigationSample() : base() { }
  39. public override void Start()
  40. {
  41. base.Start();
  42. CreateScene();
  43. CreateUI();
  44. SetupViewport();
  45. SubscribeToEvents();
  46. }
  47. void SubscribeToEvents()
  48. {
  49. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  50. {
  51. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  52. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  53. // bones properly
  54. if (drawDebug)
  55. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  56. if (currentPath.Count > 0)
  57. {
  58. // Visualize the current calculated path
  59. DebugRenderer debug = scene.GetComponent<DebugRenderer>();
  60. debug.AddBoundingBox(new BoundingBox(endPos - new Vector3(0.1f, 0.1f, 0.1f), endPos + new Vector3(0.1f, 0.1f, 0.1f)),
  61. new Color(1.0f, 1.0f, 1.0f), true);
  62. // Draw the path with a small upward bias so that it does not clip into the surfaces
  63. Vector3 bias = new Vector3(0.0f, 0.05f, 0.0f);
  64. debug.AddLine(jackNode.Position + bias, currentPath[0] + bias, new Color(1.0f, 1.0f, 1.0f), true);
  65. if (currentPath.Count > 1)
  66. {
  67. for (int i = 0; i < currentPath.Count - 1; ++i)
  68. debug.AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, new Color(1.0f, 1.0f, 1.0f), true);
  69. }
  70. }
  71. });
  72. }
  73. protected override void Update(float timeStep)
  74. {
  75. base.Update(timeStep);
  76. MoveCamera(timeStep);
  77. FollowPath(timeStep);
  78. }
  79. void MoveCamera(float timeStep)
  80. {
  81. var input = GetSubsystem<Input>();
  82. // Right mouse button controls mouse cursor visibility: hide when pressed
  83. bool rightMouseDown = input.GetMouseButtonDown(Constants.MOUSEB_RIGHT);
  84. // Movement speed as world units per second
  85. const float moveSpeed = 20.0f;
  86. // Mouse sensitivity as degrees per pixel
  87. const float mouseSensitivity = 0.1f;
  88. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  89. // Only move the camera when the cursor is hidden
  90. if (rightMouseDown)
  91. {
  92. IntVector2 mouseMove = input.MouseMove;
  93. yaw += mouseSensitivity * mouseMove.X;
  94. pitch += mouseSensitivity * mouseMove.Y;
  95. pitch = MathHelper.Clamp(pitch, -90.0f, 90.0f);
  96. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  97. CameraNode.Rotation = new Quaternion(pitch, yaw, 0.0f);
  98. }
  99. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  100. if (input.GetKeyDown(Constants.KEY_W))
  101. CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  102. if (input.GetKeyDown(Constants.KEY_S))
  103. CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  104. if (input.GetKeyDown(Constants.KEY_A))
  105. CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  106. if (input.GetKeyDown(Constants.KEY_D))
  107. CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  108. // Set destination or teleport with left mouse button
  109. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  110. SetPathPoint();
  111. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  112. if (input.GetMouseButtonPress(Constants.MOUSEB_MIDDLE))
  113. AddOrRemoveObject();
  114. // Toggle debug geometry with space
  115. if (input.GetKeyPress(Constants.KEY_SPACE))
  116. drawDebug = !drawDebug;
  117. }
  118. void SetupViewport()
  119. {
  120. var renderer = GetSubsystem<Renderer>();
  121. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  122. }
  123. void CreateUI()
  124. {
  125. SimpleCreateInstructions(
  126. "Use WASD keys to move, RMB to rotate view\n" +
  127. "LMB to set destination, SHIFT+LMB to teleport\n" +
  128. "MMB to add or remove obstacles\n" +
  129. "Space to toggle debug geometry");
  130. }
  131. void CreateScene()
  132. {
  133. var cache = GetSubsystem<ResourceCache>();
  134. scene = new Scene();
  135. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  136. // Also create a DebugRenderer component so that we can draw debug geometry
  137. scene.CreateComponent<Octree>();
  138. scene.CreateComponent<DebugRenderer>();
  139. // Create scene node & StaticModel component for showing a static plane
  140. Node planeNode = scene.CreateChild("Plane");
  141. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  142. StaticModel planeObject = planeNode.CreateComponent<StaticModel>();
  143. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  144. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  145. // Create a Zone component for ambient lighting & fog control
  146. Node zoneNode = scene.CreateChild("Zone");
  147. Zone zone = zoneNode.CreateComponent<Zone>();
  148. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  149. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  150. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  151. zone.FogStart = 100.0f;
  152. zone.FogEnd = 300.0f;
  153. // Create a directional light to the world. Enable cascaded shadows on it
  154. Node lightNode = scene.CreateChild("DirectionalLight");
  155. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  156. Light light = lightNode.CreateComponent<Light>();
  157. light.LightType = LightType.LIGHT_DIRECTIONAL;
  158. light.CastShadows = true;
  159. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  160. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  161. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  162. // Create some mushrooms
  163. const uint numMushrooms = 100;
  164. for (uint i = 0; i < numMushrooms; ++i)
  165. CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
  166. // Create randomly sized boxes. If boxes are big enough, make them occluders
  167. const uint numBoxes = 20;
  168. for (uint i = 0; i < numBoxes; ++i)
  169. {
  170. Node boxNode = scene.CreateChild("Box");
  171. float size = 1.0f + NextRandom(10.0f);
  172. boxNode.Position = new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f);
  173. boxNode.SetScale(size);
  174. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  175. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  176. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  177. boxObject.CastShadows = true;
  178. if (size >= 3.0f)
  179. boxObject.Occluder = true;
  180. }
  181. // Create Jack node that will follow the path
  182. jackNode = scene.CreateChild("Jack");
  183. jackNode.Position = new Vector3(-5.0f, 0.0f, 20.0f);
  184. AnimatedModel modelObject = jackNode.CreateComponent<AnimatedModel>();
  185. modelObject.Model = cache.Get<Model>("Models/Jack.mdl");
  186. modelObject.SetMaterial(cache.Get<Material>("Materials/Jack.xml"));
  187. modelObject.CastShadows = true;
  188. // Create a NavigationMesh component to the scene root
  189. NavigationMesh navMesh = scene.CreateComponent<NavigationMesh>();
  190. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  191. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  192. scene.CreateComponent<Navigable>();
  193. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  194. // in the scene and still update the mesh correctly
  195. navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
  196. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  197. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  198. // it will use renderable geometry instead
  199. navMesh.Build();
  200. // Create the camera. Limit far clip distance to match the fog
  201. CameraNode = scene.CreateChild("Camera");
  202. Camera camera = CameraNode.CreateComponent<Camera>();
  203. camera.FarClip = 300.0f;
  204. // Set an initial position for the camera scene node above the plane
  205. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  206. }
  207. void SetPathPoint()
  208. {
  209. var input = GetSubsystem<Input>();
  210. Vector3 hitPos;
  211. Drawable hitDrawable;
  212. NavigationMesh navMesh = scene.GetComponent<NavigationMesh>();
  213. if (Raycast(250.0f, out hitPos, out hitDrawable))
  214. {
  215. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, new Vector3(1.0f, 1.0f, 1.0f));
  216. if (input.GetQualifierDown(Constants.QUAL_SHIFT))
  217. {
  218. // Teleport
  219. currentPath.Clear();
  220. jackNode.LookAt(new Vector3(pathPos.X, jackNode.Position.Y, pathPos.Z), Vector3.UnitY, TransformSpace.TS_WORLD);
  221. jackNode.Position = (pathPos);
  222. }
  223. else
  224. {
  225. // Calculate path from Jack's current position to the end point
  226. endPos = pathPos;
  227. var result = navMesh.FindPath(currentPath, jackNode.Position, endPos);
  228. }
  229. }
  230. }
  231. void AddOrRemoveObject()
  232. {
  233. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  234. Vector3 hitPos;
  235. Drawable hitDrawable;
  236. if (Raycast(250.0f, out hitPos, out hitDrawable))
  237. {
  238. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  239. // drawable component
  240. BoundingBox updateBox;
  241. Node hitNode = hitDrawable.Node;
  242. if (hitNode.Name == "Mushroom")
  243. {
  244. updateBox = hitDrawable.WorldBoundingBox;
  245. hitNode.Remove();
  246. }
  247. else
  248. {
  249. Node newNode = CreateMushroom(hitPos);
  250. updateBox = newNode.GetComponent<StaticModel>().WorldBoundingBox;
  251. }
  252. // Rebuild part of the navigation mesh, then recalculate path if applicable
  253. NavigationMesh navMesh = scene.GetComponent<NavigationMesh>();
  254. navMesh.Build(updateBox);
  255. if (currentPath.Count > 0)
  256. navMesh.FindPath(currentPath, jackNode.Position, endPos);
  257. }
  258. }
  259. Node CreateMushroom(Vector3 pos)
  260. {
  261. var cache = GetSubsystem<ResourceCache>();
  262. Node mushroomNode = scene.CreateChild("Mushroom");
  263. mushroomNode.Position = pos;
  264. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  265. mushroomNode.SetScale(2.0f + NextRandom(0.5f));
  266. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  267. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  268. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  269. mushroomObject.CastShadows = true;
  270. return mushroomNode;
  271. }
  272. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  273. {
  274. var input = GetSubsystem<Input>();
  275. hitDrawable = null;
  276. hitPos = new Vector3();
  277. var graphics = GetSubsystem<Graphics>();
  278. Camera camera = CameraNode.GetComponent<Camera>();
  279. IntVector2 pos = input.MousePosition;
  280. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  281. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  282. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  283. scene.GetComponent<Octree>().RaycastSingle(query);
  284. if (query.Results.Count > 0)
  285. {
  286. var first = query.Results.First();
  287. hitPos = first.Position;
  288. hitDrawable = first.Drawable;
  289. return true;
  290. }
  291. return false;
  292. }
  293. void FollowPath(float timeStep)
  294. {
  295. if (currentPath.Count > 0)
  296. {
  297. Vector3 nextWaypoint = currentPath[0]; // NB: currentPath[0] is the next waypoint in order
  298. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  299. float move = 5.0f * timeStep;
  300. float distance = (jackNode.Position - nextWaypoint).Length;
  301. if (move > distance)
  302. move = distance;
  303. jackNode.LookAt(nextWaypoint, Vector3.UnitY, TransformSpace.TS_WORLD);
  304. jackNode.Translate(Vector3.UnitZ * move, TransformSpace.TS_LOCAL);
  305. // Remove waypoint if reached it
  306. if (distance < 0.1f)
  307. currentPath.RemoveAt(0);
  308. }
  309. }
  310. }
  311. }