39_CrowdNavigation.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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.Linq;
  25. using AtomicEngine;
  26. namespace FeatureExamples
  27. {
  28. public class CrowdNavigationSample : Sample
  29. {
  30. bool drawDebug;
  31. CrowdManager crowdManager;
  32. public CrowdNavigationSample() : base() { }
  33. public override void Start()
  34. {
  35. base.Start();
  36. CreateScene();
  37. CreateUI();
  38. SetupViewport();
  39. SubscribeToEvents();
  40. }
  41. void CreateUI()
  42. {
  43. var cache = GetSubsystem<ResourceCache>();
  44. SimpleCreateInstructions(
  45. "Use WASD keys to move, RMB to rotate view\n" +
  46. "LMB to set destination, SHIFT+LMB to spawn a Jack\n" +
  47. "CTRL+LMB to teleport main agent\n" +
  48. "MMB to add obstacles or remove obstacles/agents\n" +
  49. "F5 to save scene, F7 to load\n" +
  50. "Space to toggle debug geometry");
  51. }
  52. protected override void Update(float timeStep)
  53. {
  54. MoveCamera(timeStep);
  55. base.Update(timeStep);
  56. }
  57. void SubscribeToEvents()
  58. {
  59. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  60. {
  61. if (drawDebug)
  62. {
  63. // Visualize navigation mesh, obstacles and off-mesh connections
  64. scene.GetComponent<DynamicNavigationMesh>().DrawDebugGeometry(true);
  65. // Visualize agents' path and position to reach
  66. crowdManager.DrawDebugGeometry(true);
  67. }
  68. });
  69. SubscribeToEvent<CrowdAgentFailureEvent>(e =>
  70. {
  71. Node node = e.Node;
  72. CrowdAgentState agentState = (CrowdAgentState) e.CrowdAgentState;
  73. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  74. if (agentState == CrowdAgentState.CA_STATE_INVALID)
  75. {
  76. // Get a point on the navmesh using more generous extents
  77. Vector3 newPos = scene.GetComponent<DynamicNavigationMesh>().FindNearestPoint(node.Position, new Vector3(5.0f, 5.0f, 5.0f));
  78. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  79. node.Position = newPos;
  80. }
  81. });
  82. SubscribeToEvent<CrowdAgentRepositionEvent>(e =>
  83. {
  84. string WALKING_ANI = "Models/Jack_Walk.ani";
  85. Node node = e.Node;
  86. Vector3 velocity = e.Velocity;
  87. // Only Jack agent has animation controller
  88. AnimationController animCtrl = node.GetComponent<AnimationController>();
  89. if (animCtrl != null)
  90. {
  91. float speed = velocity.Length;
  92. if (animCtrl.IsPlaying(WALKING_ANI))
  93. {
  94. float speedRatio = speed / e.CrowdAgent.MaxSpeed;
  95. // Face the direction of its velocity but moderate the turning speed based on the speed ratio as we do not have timeStep here
  96. node.Rotation = Quaternion.Slerp(node.Rotation, Quaternion.FromRotationTo(Vector3.UnitZ, velocity), 10f * e.TimeStep * speedRatio);
  97. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  98. animCtrl.SetSpeed(WALKING_ANI, speedRatio);
  99. }
  100. else
  101. animCtrl.Play(WALKING_ANI, 0, true, 0.1f);
  102. // If speed is too low then stopping the animation
  103. if (speed < e.CrowdAgent.Radius)
  104. animCtrl.Stop(WALKING_ANI, 0.8f);
  105. }
  106. });
  107. }
  108. void MoveCamera(float timeStep)
  109. {
  110. // Right mouse button controls mouse cursor visibility: hide when pressed
  111. Input input = GetSubsystem<Input>();
  112. var rightMouseDown = input.GetMouseButtonDown(Constants.MOUSEB_RIGHT);
  113. // Movement speed as world units per second
  114. const float moveSpeed = 20.0f;
  115. // Mouse sensitivity as degrees per pixel
  116. const float mouseSensitivity = 0.1f;
  117. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  118. // Only move the camera when the cursor is hidden
  119. if (rightMouseDown)
  120. {
  121. IntVector2 mouseMove = input.MouseMove;
  122. Yaw += mouseSensitivity * mouseMove.X;
  123. Pitch += mouseSensitivity * mouseMove.Y;
  124. Pitch = MathHelper.Clamp(Pitch, -90.0f, 90.0f);
  125. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  126. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0.0f);
  127. }
  128. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  129. if (input.GetKeyDown(Constants.KEY_W)) CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  130. if (input.GetKeyDown(Constants.KEY_S)) CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  131. if (input.GetKeyDown(Constants.KEY_A)) CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  132. if (input.GetKeyDown(Constants.KEY_D)) CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  133. const int qualShift = 1;
  134. // Set destination or spawn a new jack with left mouse button
  135. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  136. SetPathPoint(input.GetQualifierDown(qualShift));
  137. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  138. if (input.GetMouseButtonPress(Constants.MOUSEB_MIDDLE))
  139. AddOrRemoveObject();
  140. /*
  141. // Check for loading/saving the scene. Save the scene to the file Data/Scenes/CrowdNavigation.xml relative to the executable
  142. // directory
  143. if (input.GetKeyPress(Key.F5))
  144. scene.SaveXml(FileSystem.ProgramDir + "Data/Scenes/CrowdNavigation.xml");
  145. if (input.GetKeyPress(Key.F7))
  146. scene.LoadXml(FileSystem.ProgramDir + "Data/Scenes/CrowdNavigation.xml");
  147. */
  148. // Toggle debug geometry with space
  149. if (input.GetKeyPress(Constants.KEY_SPACE))
  150. drawDebug = !drawDebug;
  151. }
  152. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  153. {
  154. var input = GetSubsystem<Input>();
  155. hitDrawable = null;
  156. hitPos = new Vector3();
  157. var graphics = GetSubsystem<Graphics>();
  158. Camera camera = CameraNode.GetComponent<Camera>();
  159. IntVector2 pos = input.MousePosition;
  160. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  161. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  162. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  163. scene.GetComponent<Octree>().RaycastSingle(query);
  164. if (query.Results.Count > 0)
  165. {
  166. var first = query.Results.First();
  167. hitPos = first.Position;
  168. hitDrawable = first.Drawable;
  169. return true;
  170. }
  171. return false;
  172. }
  173. void SetPathPoint(bool spawning)
  174. {
  175. Vector3 hitPos;
  176. Drawable hitDrawable;
  177. if (Raycast(250.0f, out hitPos, out hitDrawable))
  178. {
  179. DynamicNavigationMesh navMesh = scene.GetComponent<DynamicNavigationMesh>();
  180. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, new Vector3(1.0f, 1.0f, 1.0f));
  181. Node jackGroup = scene.GetChild("Jacks", false);
  182. if (spawning)
  183. // Spawn a jack at the target position
  184. SpawnJack(pathPos, jackGroup);
  185. else
  186. // Set crowd agents target position
  187. scene.GetComponent<CrowdManager>().SetCrowdTarget(pathPos, jackGroup);
  188. }
  189. }
  190. void AddOrRemoveObject()
  191. {
  192. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  193. Vector3 hitPos;
  194. Drawable hitDrawable;
  195. if (Raycast(250.0f, out hitPos, out hitDrawable))
  196. {
  197. Node hitNode = hitDrawable.Node;
  198. // Note that navmesh rebuild happens when the Obstacle component is removed
  199. if (hitNode.Name == "Mushroom")
  200. hitNode.Remove();
  201. else if (hitNode.Name == "Jack")
  202. hitNode.Remove();
  203. else
  204. CreateMushroom(hitPos);
  205. }
  206. }
  207. void SetupViewport()
  208. {
  209. var renderer = GetSubsystem<Renderer>();
  210. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  211. }
  212. void CreateScene()
  213. {
  214. var cache = GetSubsystem<ResourceCache>();
  215. scene = new Scene();
  216. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  217. // Also create a DebugRenderer component so that we can draw debug geometry
  218. scene.CreateComponent<Octree>();
  219. scene.CreateComponent<DebugRenderer>();
  220. // Create scene node & StaticModel component for showing a static plane
  221. Node planeNode = scene.CreateChild("Plane");
  222. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  223. StaticModel planeObject = planeNode.CreateComponent<StaticModel>();
  224. planeObject.Model = (cache.Get<Model>("Models/Plane.mdl"));
  225. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  226. // Create a Zone component for ambient lighting & fog control
  227. Node zoneNode = scene.CreateChild("Zone");
  228. Zone zone = zoneNode.CreateComponent<Zone>();
  229. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  230. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  231. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  232. zone.FogStart = 100.0f;
  233. zone.FogEnd = 300.0f;
  234. // Create a directional light to the world. Enable cascaded shadows on it
  235. Node lightNode = scene.CreateChild("DirectionalLight");
  236. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  237. Light light = lightNode.CreateComponent<Light>();
  238. light.LightType = LightType.LIGHT_DIRECTIONAL;
  239. light.CastShadows = true;
  240. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  241. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  242. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  243. // Create randomly sized boxes. If boxes are big enough, make them occluders
  244. const uint numBoxes = 20;
  245. Node boxGroup = scene.CreateChild("Boxes");
  246. for (uint i = 0; i < numBoxes; ++i)
  247. {
  248. Node boxNode = boxGroup.CreateChild("Box");
  249. float size = 1.0f + NextRandom(10.0f);
  250. boxNode.Position = (new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f));
  251. boxNode.SetScale(size);
  252. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  253. boxObject.Model = (cache.Get<Model>("Models/Box.mdl"));
  254. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  255. boxObject.CastShadows = true;
  256. if (size >= 3.0f)
  257. boxObject.Occluder = true;
  258. }
  259. // Create a DynamicNavigationMesh component to the scene root
  260. DynamicNavigationMesh navMesh = scene.CreateComponent<DynamicNavigationMesh>();
  261. // Set the agent height large enough to exclude the layers under boxes
  262. navMesh.AgentHeight = 10.0f;
  263. navMesh.CellHeight = 0.05f;
  264. navMesh.DrawObstacles = true;
  265. navMesh.DrawOffMeshConnections = true;
  266. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  267. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  268. scene.CreateComponent<Navigable>();
  269. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  270. // in the scene and still update the mesh correctly
  271. navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
  272. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  273. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  274. // it will use renderable geometry instead
  275. navMesh.Build();
  276. // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  277. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  278. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  279. CreateBoxOffMeshConnections(navMesh, boxGroup);
  280. // Create some mushrooms
  281. const uint numMushrooms = 100;
  282. for (uint i = 0; i < numMushrooms; ++i)
  283. CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
  284. // Create a CrowdManager component to the scene root
  285. crowdManager = scene.CreateComponent<CrowdManager>();
  286. var parameters = crowdManager.GetObstacleAvoidanceParams(0);
  287. // Set the params to "High (66)" setting
  288. parameters.VelBias = 0.5f;
  289. parameters.AdaptiveDivs = 7;
  290. parameters.AdaptiveRings = 3;
  291. parameters.AdaptiveDepth = 3;
  292. crowdManager.SetObstacleAvoidanceParams(0, parameters);
  293. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  294. CreateMovingBarrels(navMesh);
  295. // Create Jack node that will follow the path
  296. SpawnJack(new Vector3(-5.0f, 0.0f, 20.0f), scene.CreateChild("Jacks"));
  297. // Create the camera. Limit far clip distance to match the fog
  298. CameraNode = new Node();
  299. Camera camera = CameraNode.CreateComponent<Camera>();
  300. camera.FarClip = 300.0f;
  301. // Set an initial position for the camera scene node above the plane
  302. CameraNode.Position = new Vector3(0.0f, 50.0f, 0.0f);
  303. Pitch = 80.0f;
  304. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0.0f);
  305. }
  306. void SpawnJack(Vector3 pos, Node jackGroup)
  307. {
  308. var cache = GetSubsystem<ResourceCache>();
  309. Node jackNode = jackGroup.CreateChild("Jack");
  310. jackNode.Position = pos;
  311. AnimatedModel modelObject = jackNode.CreateComponent<AnimatedModel>();
  312. modelObject.Model = (cache.Get<Model>("Models/Jack.mdl"));
  313. modelObject.SetMaterial(cache.Get<Material>("Materials/Jack.xml"));
  314. modelObject.CastShadows = true;
  315. jackNode.CreateComponent<AnimationController>();
  316. // Create the CrowdAgent
  317. var agent = jackNode.CreateComponent<CrowdAgent>();
  318. agent.Height = 2.0f;
  319. agent.MaxSpeed = 3.0f;
  320. agent.MaxAccel = 3.0f;
  321. }
  322. void CreateMushroom(Vector3 pos)
  323. {
  324. var cache = GetSubsystem<ResourceCache>();
  325. Node mushroomNode = scene.CreateChild("Mushroom");
  326. mushroomNode.Position = (pos);
  327. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  328. mushroomNode.SetScale(2.0f + NextRandom(0.5f));
  329. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  330. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  331. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  332. mushroomObject.CastShadows = true;
  333. // Create the navigation obstacle
  334. Obstacle obstacle = mushroomNode.CreateComponent<Obstacle>();
  335. obstacle.Radius = mushroomNode.Scale.X;
  336. obstacle.Height = mushroomNode.Scale.Y;
  337. }
  338. void CreateBoxOffMeshConnections(DynamicNavigationMesh navMesh, Node boxGroup)
  339. {
  340. foreach (var box in boxGroup.GetChildren())
  341. {
  342. var boxPos = box.Position;
  343. float boxHalfSize = box.Scale.X / 2;
  344. var connectionStart = box.CreateChild("ConnectionStart");
  345. connectionStart.SetWorldPosition(navMesh.FindNearestPoint(boxPos + new Vector3(boxHalfSize, -boxHalfSize, 0), Vector3.One));
  346. var connectionEnd = box.CreateChild("ConnectionEnd");
  347. connectionEnd.SetWorldPosition(navMesh.FindNearestPoint(boxPos + new Vector3(boxHalfSize, boxHalfSize, 0), Vector3.One));
  348. OffMeshConnection connection = connectionStart.CreateComponent<OffMeshConnection>();
  349. connection.EndPoint = connectionEnd;
  350. }
  351. }
  352. void CreateMovingBarrels(DynamicNavigationMesh navMesh)
  353. {
  354. var cache = GetSubsystem<ResourceCache>();
  355. Node barrel = scene.CreateChild("Barrel");
  356. StaticModel model = barrel.CreateComponent<StaticModel>();
  357. model.Model = cache.Get<Model>("Models/Cylinder.mdl");
  358. Material material = cache.Get<Material>("Materials/StoneTiled.xml");
  359. model.SetMaterial(material);
  360. material.SetTexture(TextureUnit.TU_DIFFUSE, cache.Get<Texture2D>("Textures/TerrainDetail2.dds"));
  361. model.CastShadows = true;
  362. for (int i = 0; i < 20; ++i)
  363. {
  364. Node clone = barrel.Clone(CreateMode.REPLICATED);
  365. float size = 0.5f + NextRandom(1.0f);
  366. clone.Scale = new Vector3(size / 1.5f, size * 2.0f, size / 1.5f);
  367. clone.Position = navMesh.FindNearestPoint(new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f), Vector3.One);
  368. CrowdAgent agent = clone.CreateComponent<CrowdAgent>();
  369. agent.Radius = clone.Scale.X * 0.5f;
  370. agent.Height = size;
  371. agent.NavigationQuality = NavigationQuality.NAVIGATIONQUALITY_LOW;
  372. }
  373. barrel.Remove();
  374. }
  375. }
  376. }