15_Navigation.lua 19 KB

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