15_Navigation.lua 15 KB

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