39_CrowdNavigation.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. -- CrowdNavigation example.
  2. -- This sample demonstrates:
  3. -- - Generating a cached navigation mesh into the scene
  4. -- - Performing path queries to the navigation mesh
  5. -- - Adding and removing obstacles at runtime from the dynamic mesh
  6. -- - Visualizing custom debug geometry
  7. -- - Raycasting drawable components
  8. -- - Making a node follow the Detour path
  9. -- - Crowd movement management
  10. require "LuaScripts/Utilities/Sample"
  11. local endPos = nil
  12. local currentPath = {}
  13. local jackNodes = {}
  14. local crowdManager = nil
  15. local mushrooms = {}
  16. function Start()
  17. -- Execute the common startup for samples
  18. SampleStart()
  19. -- Create the scene content
  20. CreateScene()
  21. -- Create the UI content
  22. CreateUI()
  23. -- Setup the viewport for displaying the scene
  24. SetupViewport()
  25. -- Hook up to the frame update and render post-update events
  26. SubscribeToEvents()
  27. end
  28. function CreateScene()
  29. scene_ = Scene()
  30. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  31. -- Also create a DebugRenderer component so that we can draw debug geometry
  32. scene_:CreateComponent("Octree")
  33. scene_:CreateComponent("DebugRenderer")
  34. scene_:CreateComponent("PhysicsWorld")
  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 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 a DynamicNavigationMesh component to the scene root
  75. local navMesh = scene_:CreateComponent("DynamicNavigationMesh")
  76. -- Set nav mesh tilesize to something reasonable
  77. navMesh.tileSize = 64;
  78. -- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  79. -- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  80. scene_:CreateComponent("Navigable")
  81. -- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  82. -- in the scene and still update the mesh correctly
  83. navMesh.padding = Vector3(0.0, 10.0, 0.0)
  84. -- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  85. -- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  86. -- it will use renderable geometry instead
  87. navMesh:Build()
  88. crowdManager = scene_:CreateComponent("DetourCrowdManager")
  89. -- Create Jack node that will follow the path
  90. SpawnJack(Vector3(-5, 0, 20))
  91. -- Create some mushrooms
  92. local NUM_MUSHROOMS = 100
  93. for i = 1, NUM_MUSHROOMS do
  94. CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0))
  95. end
  96. -- Create the camera. Limit far clip distance to match the fog
  97. cameraNode = scene_:CreateChild("Camera")
  98. local camera = cameraNode:CreateComponent("Camera")
  99. camera.farClip = 300.0
  100. -- Set an initial position for the camera scene node above the plane
  101. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  102. end
  103. function CreateUI()
  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. local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
  107. local cursor = Cursor:new()
  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. local instructionText = ui.root:CreateChild("Text")
  114. instructionText.text = "Use WASD keys to move, RMB to rotate view\n"..
  115. "LMB to set destination, SHIFT+LMB to spawn a jack\n"..
  116. "MMB to add or remove obstacles\n"..
  117. "Space to toggle debug geometry"
  118. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  119. -- The text has multiple rows. Center them in relation to each other
  120. instructionText.textAlignment = HA_CENTER
  121. -- Position the text relative to the screen center
  122. instructionText.horizontalAlignment = HA_CENTER
  123. instructionText.verticalAlignment = VA_CENTER
  124. instructionText:SetPosition(0, ui.root.height / 4)
  125. end
  126. function SetupViewport()
  127. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  128. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  129. renderer:SetViewport(0, viewport)
  130. end
  131. function SubscribeToEvents()
  132. -- Subscribe HandleUpdate() function for processing update events
  133. SubscribeToEvent("Update", "HandleUpdate")
  134. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  135. -- debug geometry
  136. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  137. end
  138. function MoveCamera(timeStep)
  139. -- Right mouse button controls mouse cursor visibility: hide when pressed
  140. ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT)
  141. -- Do not move if the UI has a focused element (the console)
  142. if ui.focusElement ~= nil then
  143. return
  144. end
  145. -- Movement speed as world units per second
  146. local MOVE_SPEED = 20.0
  147. -- Mouse sensitivity as degrees per pixel
  148. local MOUSE_SENSITIVITY = 0.1
  149. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  150. -- Only move the camera when the cursor is hidden
  151. if not ui.cursor.visible then
  152. local mouseMove = input.mouseMove
  153. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  154. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  155. pitch = Clamp(pitch, -90.0, 90.0)
  156. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  157. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  158. end
  159. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  160. if input:GetKeyDown(KEY_W) then
  161. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  162. end
  163. if input:GetKeyDown(KEY_S) then
  164. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  165. end
  166. if input:GetKeyDown(KEY_A) then
  167. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  168. end
  169. if input:GetKeyDown(KEY_D) then
  170. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  171. end
  172. -- Set destination or spawn a jack with left mouse button
  173. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  174. SetPathPoint()
  175. end
  176. -- Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  177. if input:GetMouseButtonPress(MOUSEB_MIDDLE) then
  178. AddOrRemoveObject()
  179. end
  180. -- Toggle debug geometry with space
  181. if input:GetKeyPress(KEY_SPACE) then
  182. drawDebug = not drawDebug
  183. end
  184. end
  185. function SetPathPoint()
  186. local result, hitPos, hitDrawable = Raycast(250.0)
  187. local navMesh = scene_:GetComponent("DynamicNavigationMesh")
  188. if result then
  189. local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE)
  190. if input:GetQualifierDown(QUAL_SHIFT) then
  191. -- spawn a jack
  192. SpawnJack(pathPos)
  193. else
  194. -- Calculate path from Jack's current position to the end point
  195. local ct = table.maxn(jackNodes)
  196. if ct > 0 then
  197. for i = 1, ct do
  198. local agt = jackNodes[i]:GetComponent("CrowdAgent")
  199. agt.enabled = true
  200. if i == 1 then
  201. -- The first agent will always move to the exact target
  202. agt:SetMoveTarget(pathPos)
  203. else
  204. -- Keep the random point on the navigation mesh
  205. local targetPos = navMesh:FindNearestPoint(pathPos + Vector3(Random(7.0), 0, Random(7.0)), Vector3.ONE)
  206. agt:SetMoveTarget(targetPos)
  207. end
  208. end
  209. end
  210. end
  211. end
  212. end
  213. function GetIndexOf(tableTarget, objectTarget)
  214. for k,v in pairs(tableTarget) do
  215. if objectTarget == v then
  216. return k
  217. end
  218. end
  219. return -1
  220. end
  221. function AddOrRemoveObject()
  222. -- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  223. local result, hitPos, hitDrawable = Raycast(250.0)
  224. if result then
  225. local hitNode = hitDrawable:GetNode()
  226. if hitNode.name == "Mushroom" then
  227. local idx = GetIndexOf(mushrooms, hitNode)
  228. if idx >= 0 then
  229. table.remove(mushrooms, idx)
  230. end
  231. hitNode:Remove()
  232. else
  233. local newNode = CreateMushroom(hitPos)
  234. local newObject = newNode:GetComponent("StaticModel")
  235. end
  236. end
  237. end
  238. function SpawnJack(pos)
  239. local jackNode = scene_:CreateChild("Jack")
  240. jackNode.position = pos
  241. local modelObject = jackNode:CreateComponent("AnimatedModel")
  242. modelObject.model = cache:GetResource("Model", "Models/Jack.mdl")
  243. modelObject.material = cache:GetResource("Material", "Materials/Jack.xml")
  244. modelObject.castShadows = true
  245. local agent = jackNode:CreateComponent("CrowdAgent")
  246. agent.enabled = false;
  247. table.insert(jackNodes, jackNode)
  248. end
  249. function CreateMushroom(pos)
  250. local mushroomNode = scene_:CreateChild("Mushroom")
  251. mushroomNode.position = pos
  252. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  253. mushroomNode:SetScale(2.0 + Random(0.5))
  254. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  255. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  256. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  257. mushroomObject.castShadows = true
  258. local obstacleObject = mushroomNode:CreateComponent("Obstacle")
  259. obstacleObject.radius = 2.5
  260. table.insert(mushrooms, mushroomNode)
  261. return mushroomNode
  262. end
  263. function Raycast(maxDistance)
  264. local hitPos = nil
  265. local hitDrawable = nil
  266. local pos = ui.cursorPosition
  267. -- Check the cursor is visible and there is no UI element in front of the cursor
  268. if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then
  269. return false, nil, nil
  270. end
  271. local camera = cameraNode:GetComponent("Camera")
  272. local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height)
  273. -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  274. local octree = scene_:GetComponent("Octree")
  275. local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY)
  276. if result.drawable ~= nil then
  277. -- Calculate hit position in world space
  278. hitPos = cameraRay.origin + cameraRay.direction * result.distance
  279. hitDrawable = result.drawable
  280. return true, hitPos, hitDrawable
  281. end
  282. return false, nil, nil
  283. end
  284. function HandleUpdate(eventType, eventData)
  285. -- Take the frame time step, which is stored as a float
  286. local timeStep = eventData:GetFloat("TimeStep")
  287. -- Move the camera, scale movement with time step
  288. MoveCamera(timeStep)
  289. -- Make the CrowdAgents face the direction of their velocity
  290. local ct = table.maxn(jackNodes)
  291. if ct > 0 then
  292. for i = 1, ct do
  293. local agent = jackNodes[i]:GetComponent("CrowdAgent")
  294. jackNodes[i].worldDirection = agent:GetActualVelocity()
  295. end
  296. end
  297. end
  298. function HandlePostRenderUpdate(eventType, eventData)
  299. -- If draw debug mode is enabled, draw navigation mesh debug geometry
  300. if drawDebug then
  301. local navMesh = scene_:GetComponent("DynamicNavigationMesh")
  302. navMesh:DrawDebugGeometry(true)
  303. -- Visualize the start and end points and the last calculated path
  304. local size = table.maxn(jackNodes)
  305. if size > 0 then
  306. for i = 1, size do
  307. local agent = jackNodes[i]:GetComponent("CrowdAgent")
  308. agent:DrawDebugGeometry(true)
  309. end
  310. end
  311. size = table.maxn(mushrooms)
  312. if size > 0 then
  313. for i = 1, size do
  314. local obstacle = mushrooms[i]:GetComponent("Obstacle")
  315. obstacle:DrawDebugGeometry(true)
  316. end
  317. end
  318. end
  319. end
  320. -- Create XML patch instructions for screen joystick layout specific to this sample app
  321. function GetScreenJoystickPatchString()
  322. return
  323. "<patch>" ..
  324. " <add sel=\"/element\">" ..
  325. " <element type=\"Button\">" ..
  326. " <attribute name=\"Name\" value=\"Button3\" />" ..
  327. " <attribute name=\"Position\" value=\"-120 -120\" />" ..
  328. " <attribute name=\"Size\" value=\"96 96\" />" ..
  329. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  330. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  331. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  332. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  333. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  334. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  335. " <element type=\"Text\">" ..
  336. " <attribute name=\"Name\" value=\"Label\" />" ..
  337. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  338. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  339. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  340. " <attribute name=\"Text\" value=\"Spawn Jack\" />" ..
  341. " </element>" ..
  342. " <element type=\"Text\">" ..
  343. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  344. " <attribute name=\"Text\" value=\"LSHIFT\" />" ..
  345. " </element>" ..
  346. " <element type=\"Text\">" ..
  347. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  348. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  349. " </element>" ..
  350. " </element>" ..
  351. " <element type=\"Button\">" ..
  352. " <attribute name=\"Name\" value=\"Button4\" />" ..
  353. " <attribute name=\"Position\" value=\"-120 -12\" />" ..
  354. " <attribute name=\"Size\" value=\"96 96\" />" ..
  355. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  356. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  357. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  358. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  359. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  360. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  361. " <element type=\"Text\">" ..
  362. " <attribute name=\"Name\" value=\"Label\" />" ..
  363. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  364. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  365. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  366. " <attribute name=\"Text\" value=\"Obstacles\" />" ..
  367. " </element>" ..
  368. " <element type=\"Text\">" ..
  369. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  370. " <attribute name=\"Text\" value=\"MIDDLE\" />" ..
  371. " </element>" ..
  372. " </element>" ..
  373. " </add>" ..
  374. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  375. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" ..
  376. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  377. " <element type=\"Text\">" ..
  378. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  379. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  380. " </element>" ..
  381. " </add>" ..
  382. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  383. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  384. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  385. " <element type=\"Text\">" ..
  386. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  387. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  388. " </element>" ..
  389. " </add>" ..
  390. "</patch>"
  391. end