15_Navigation.lua 15 KB

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