15_Navigation.as 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Navigation example.
  2. // This sample demonstrates:
  3. // - Generating a navigation mesh into the scene
  4. // - Performing path queries to the navigation mesh
  5. // - Rebuilding the navigation mesh partially when adding or removing objects
  6. // - Visualizing custom debug geometry
  7. // - Raycasting drawable components
  8. // - Making a node follow the Detour path
  9. #include "Scripts/Utilities/Sample.as"
  10. Vector3 endPos;
  11. Array<Vector3> currentPath;
  12. Node@ jackNode;
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateUI();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Hook up to the frame update and render post-update events
  24. SubscribeToEvents();
  25. }
  26. void CreateScene()
  27. {
  28. scene_ = Scene();
  29. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  30. // Also create a DebugRenderer component so that we can draw debug geometry
  31. scene_.CreateComponent("Octree");
  32. scene_.CreateComponent("DebugRenderer");
  33. // Create scene node & StaticModel component for showing a static plane
  34. Node@ planeNode = scene_.CreateChild("Plane");
  35. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  36. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  37. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  38. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  39. // Create a Zone component for ambient lighting & fog control
  40. Node@ zoneNode = scene_.CreateChild("Zone");
  41. Zone@ zone = zoneNode.CreateComponent("Zone");
  42. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  43. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  44. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  45. zone.fogStart = 100.0f;
  46. zone.fogEnd = 300.0f;
  47. // Create a directional light to the world. Enable cascaded shadows on it
  48. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  49. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  50. Light@ light = lightNode.CreateComponent("Light");
  51. light.lightType = LIGHT_DIRECTIONAL;
  52. light.castShadows = true;
  53. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  54. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  55. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  56. // Create some mushrooms
  57. const uint NUM_MUSHROOMS = 100;
  58. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  59. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  60. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  61. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  62. const uint NUM_BOXES = 20;
  63. for (uint i = 0; i < NUM_BOXES; ++i)
  64. {
  65. Node@ boxNode = scene_.CreateChild("Box");
  66. float size = 1.0f + Random(10.0f);
  67. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  68. boxNode.SetScale(size);
  69. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  70. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  71. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  72. boxObject.castShadows = true;
  73. if (size >= 3.0f)
  74. boxObject.occluder = true;
  75. }
  76. // Create Jack node that will follow the path
  77. jackNode = scene_.CreateChild("Jack");
  78. jackNode.position = Vector3(-5.0f, 0.0f, 20.0f);
  79. AnimatedModel@ modelObject = jackNode.CreateComponent("AnimatedModel");
  80. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  81. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  82. modelObject.castShadows = true;
  83. // Create a NavigationMesh component to the scene root
  84. NavigationMesh@ navMesh = scene_.CreateComponent("NavigationMesh");
  85. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  86. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  87. scene_.CreateComponent("Navigable");
  88. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  89. // in the scene and still update the mesh correctly
  90. navMesh.padding = Vector3(0.0f, 10.0f, 0.0f);
  91. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  92. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  93. // it will use renderable geometry instead
  94. navMesh.Build();
  95. // Create the camera. Limit far clip distance to match the fog
  96. cameraNode = scene_.CreateChild("Camera");
  97. Camera@ camera = cameraNode.CreateComponent("Camera");
  98. camera.farClip = 300.0f;
  99. // Set an initial position for the camera scene node above the plane
  100. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  101. }
  102. void CreateUI()
  103. {
  104. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  105. // control the camera, and when visible, it will point the raycast target
  106. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  107. Cursor@ cursor = Cursor();
  108. cursor.SetStyleAuto(style);
  109. ui.cursor = cursor;
  110. // Set starting position of the cursor at the rendering window center
  111. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  112. // Construct new Text object, set string to display and font to use
  113. Text@ instructionText = ui.root.CreateChild("Text");
  114. instructionText.text =
  115. "Use WASD keys to move, RMB to rotate view\n"
  116. "LMB to set destination, SHIFT+LMB to teleport\n"
  117. "MMB to add or remove obstacles\n"
  118. "Space to toggle debug geometry";
  119. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  120. // The text has multiple rows. Center them in relation to each other
  121. instructionText.textAlignment = HA_CENTER;
  122. // Position the text relative to the screen center
  123. instructionText.horizontalAlignment = HA_CENTER;
  124. instructionText.verticalAlignment = VA_CENTER;
  125. instructionText.SetPosition(0, ui.root.height / 4);
  126. }
  127. void SetupViewport()
  128. {
  129. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  130. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  131. renderer.viewports[0] = viewport;
  132. }
  133. void SubscribeToEvents()
  134. {
  135. // Subscribe HandleUpdate() function for processing update events
  136. SubscribeToEvent("Update", "HandleUpdate");
  137. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  138. // debug geometry
  139. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  140. }
  141. void MoveCamera(float timeStep)
  142. {
  143. // Right mouse button controls mouse cursor visibility: hide when pressed
  144. ui.cursor.visible = !input.mouseButtonDown[MOUSEB_RIGHT];
  145. // Do not move if the UI has a focused element (the console)
  146. if (ui.focusElement !is null)
  147. return;
  148. // Movement speed as world units per second
  149. const float MOVE_SPEED = 20.0f;
  150. // Mouse sensitivity as degrees per pixel
  151. const float MOUSE_SENSITIVITY = 0.1f;
  152. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  153. // Only move the camera when the cursor is hidden
  154. if (!ui.cursor.visible)
  155. {
  156. IntVector2 mouseMove = input.mouseMove;
  157. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  158. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  159. pitch = Clamp(pitch, -90.0f, 90.0f);
  160. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  161. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  162. }
  163. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  164. if (input.keyDown['W'])
  165. cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  166. if (input.keyDown['S'])
  167. cameraNode.Translate(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  168. if (input.keyDown['A'])
  169. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  170. if (input.keyDown['D'])
  171. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  172. // Set destination or teleport with left mouse button
  173. if (input.mouseButtonPress[MOUSEB_LEFT])
  174. SetPathPoint();
  175. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  176. if (input.mouseButtonPress[MOUSEB_MIDDLE])
  177. AddOrRemoveObject();
  178. // Toggle debug geometry with space
  179. if (input.keyPress[KEY_SPACE])
  180. drawDebug = !drawDebug;
  181. }
  182. void SetPathPoint()
  183. {
  184. Vector3 hitPos;
  185. Drawable@ hitDrawable;
  186. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  187. if (Raycast(250.0f, hitPos, hitDrawable))
  188. {
  189. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  190. if (input.qualifierDown[QUAL_SHIFT])
  191. {
  192. // Teleport
  193. currentPath.Clear();
  194. jackNode.LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3(0.0f, 1.0f, 0.0f));
  195. jackNode.position = pathPos;
  196. }
  197. else
  198. {
  199. // Calculate path from Jack's current position to the end point
  200. endPos = pathPos;
  201. currentPath = navMesh.FindPath(jackNode.position, endPos);
  202. }
  203. }
  204. }
  205. void AddOrRemoveObject()
  206. {
  207. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  208. Vector3 hitPos;
  209. Drawable@ hitDrawable;
  210. if (Raycast(250.0f, hitPos, hitDrawable))
  211. {
  212. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  213. // drawable component
  214. BoundingBox updateBox;
  215. Node@ hitNode = hitDrawable.node;
  216. if (hitNode.name == "Mushroom")
  217. {
  218. updateBox = hitDrawable.worldBoundingBox;
  219. hitNode.Remove();
  220. }
  221. else
  222. {
  223. Node@ newNode = CreateMushroom(hitPos);
  224. StaticModel@ newObject = newNode.GetComponent("StaticModel");
  225. updateBox = newObject.worldBoundingBox;
  226. }
  227. // Rebuild part of the navigation mesh, then rebuild the path if applicable
  228. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  229. navMesh.Build(updateBox);
  230. if (currentPath.length > 0)
  231. currentPath = navMesh.FindPath(jackNode.position, endPos);
  232. }
  233. }
  234. Node@ CreateMushroom(const Vector3& pos)
  235. {
  236. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  237. mushroomNode.position = pos;
  238. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  239. mushroomNode.SetScale(2.0f + Random(0.5f));
  240. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  241. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  242. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  243. mushroomObject.castShadows = true;
  244. return mushroomNode;
  245. }
  246. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  247. {
  248. hitDrawable = null;
  249. IntVector2 pos = ui.cursorPosition;
  250. // Check the cursor is visible and there is no UI element in front of the cursor
  251. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  252. return false;
  253. Camera@ camera = cameraNode.GetComponent("Camera");
  254. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  255. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  256. // Note the convenience accessor to scene's Octree component
  257. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  258. if (result.drawable !is null)
  259. {
  260. hitPos = result.position;
  261. hitDrawable = result.drawable;
  262. return true;
  263. }
  264. return false;
  265. }
  266. void FollowPath(float timeStep)
  267. {
  268. if (currentPath.length > 0)
  269. {
  270. Vector3 nextWaypoint = currentPath[0]; // NB: currentPath[0] is the next waypoint in order
  271. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  272. float move = 5.0f * timeStep;
  273. float distance = (jackNode.position - nextWaypoint).length;
  274. if (move > distance)
  275. move = distance;
  276. jackNode.LookAt(nextWaypoint, Vector3(0.0f, 1.0f, 0.0f));
  277. jackNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * move);
  278. // Remove waypoint if reached it
  279. if ((jackNode.position - nextWaypoint).length < 0.1)
  280. currentPath.Erase(0);
  281. }
  282. }
  283. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  284. {
  285. // Take the frame time step, which is stored as a float
  286. float timeStep = eventData["TimeStep"].GetFloat();
  287. // Move the camera, scale movement with time step
  288. MoveCamera(timeStep);
  289. // Make Jack follow the Detour path
  290. FollowPath(timeStep);
  291. }
  292. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  293. {
  294. // If draw debug mode is enabled, draw navigation mesh debug geometry
  295. if (drawDebug)
  296. {
  297. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  298. navMesh.DrawDebugGeometry(true);
  299. }
  300. if (currentPath.length > 0)
  301. {
  302. // Visualize the current calculated path
  303. // Note the convenience accessor to the DebugRenderer component
  304. DebugRenderer@ debug = scene_.debugRenderer;
  305. debug.AddBoundingBox(BoundingBox(endPos - Vector3(0.1f, 0.1f, 0.1f), endPos + Vector3(0.1f, 0.1f, 0.1f)),
  306. Color(1.0f, 1.0f, 1.0f));
  307. // Draw the path with a small upward bias so that it does not clip into the surfaces
  308. Vector3 bias(0.0f, 0.05f, 0.0f);
  309. debug.AddLine(jackNode.position + bias, currentPath[0] + bias, Color(1.0f, 1.0f, 1.0f));
  310. if (currentPath.length > 1)
  311. {
  312. for (uint i = 0; i < currentPath.length - 1; ++i)
  313. debug.AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0f, 1.0f, 1.0f));
  314. }
  315. }
  316. }
  317. // Create XML patch instructions for screen joystick layout specific to this sample app
  318. String patchInstructions =
  319. "<patch>" +
  320. " <add sel=\"/element\">" +
  321. " <element type=\"Button\">" +
  322. " <attribute name=\"Name\" value=\"Button3\" />" +
  323. " <attribute name=\"Position\" value=\"-120 -120\" />" +
  324. " <attribute name=\"Size\" value=\"96 96\" />" +
  325. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  326. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  327. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  328. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  329. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  330. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  331. " <element type=\"Text\">" +
  332. " <attribute name=\"Name\" value=\"Label\" />" +
  333. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  334. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  335. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  336. " <attribute name=\"Text\" value=\"Teleport\" />" +
  337. " </element>" +
  338. " <element type=\"Text\">" +
  339. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  340. " <attribute name=\"Text\" value=\"LSHIFT\" />" +
  341. " </element>" +
  342. " <element type=\"Text\">" +
  343. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  344. " <attribute name=\"Text\" value=\"LEFT\" />" +
  345. " </element>" +
  346. " </element>" +
  347. " <element type=\"Button\">" +
  348. " <attribute name=\"Name\" value=\"Button4\" />" +
  349. " <attribute name=\"Position\" value=\"-120 -12\" />" +
  350. " <attribute name=\"Size\" value=\"96 96\" />" +
  351. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  352. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  353. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  354. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  355. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  356. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  357. " <element type=\"Text\">" +
  358. " <attribute name=\"Name\" value=\"Label\" />" +
  359. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  360. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  361. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  362. " <attribute name=\"Text\" value=\"Obstacles\" />" +
  363. " </element>" +
  364. " <element type=\"Text\">" +
  365. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  366. " <attribute name=\"Text\" value=\"MIDDLE\" />" +
  367. " </element>" +
  368. " </element>" +
  369. " </add>" +
  370. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  371. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" +
  372. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  373. " <element type=\"Text\">" +
  374. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  375. " <attribute name=\"Text\" value=\"LEFT\" />" +
  376. " </element>" +
  377. " </add>" +
  378. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  379. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  380. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  381. " <element type=\"Text\">" +
  382. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  383. " <attribute name=\"Text\" value=\"SPACE\" />" +
  384. " </element>" +
  385. " </add>" +
  386. "</patch>";