12_PhysicsStressTest.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. -- Physics stress test example.
  2. -- This sample demonstrates:
  3. -- - Physics and rendering performance with a high (1000) moving object count
  4. -- - Using triangle meshes for collision
  5. -- - Optimizing physics simulation by leaving out collision event signaling
  6. -- - Usage of Lua Coroutine to yield/resume based on time step
  7. require "LuaScripts/Utilities/Sample"
  8. function Start()
  9. -- Execute the common startup for samples
  10. SampleStart()
  11. -- Create the scene content
  12. CreateScene()
  13. -- Create the UI content
  14. CreateInstructions()
  15. -- Setup the viewport for displaying the scene
  16. SetupViewport()
  17. -- Hook up to the frame update and render post-update events
  18. SubscribeToEvents()
  19. end
  20. function CreateScene()
  21. scene_ = Scene()
  22. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  23. -- Create a physics simulation world with default parameters, which will update at 60ps. Like the Octree must
  24. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  25. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  26. scene_:CreateComponent("Octree")
  27. scene_:CreateComponent("PhysicsWorld")
  28. scene_:CreateComponent("DebugRenderer")
  29. -- Create a Zone component for ambient lighting & fog control
  30. local zoneNode = scene_:CreateChild("Zone")
  31. local zone = zoneNode:CreateComponent("Zone")
  32. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  33. zone.ambientColor = Color(0.15, 0.15, 0.15)
  34. zone.fogColor = Color(0.5, 0.5, 0.7)
  35. zone.fogStart = 100.0
  36. zone.fogEnd = 300.0
  37. -- Create a directional light to the world. Enable cascaded shadows on it
  38. local lightNode = scene_:CreateChild("DirectionalLight")
  39. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  40. local light = lightNode:CreateComponent("Light")
  41. light.lightType = LIGHT_DIRECTIONAL
  42. light.castShadows = true
  43. light.shadowBias = BiasParameters(0.00025, 0.5)
  44. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  45. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  46. if true then
  47. -- Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  48. local floorNode = scene_:CreateChild("Floor")
  49. floorNode.position = Vector3(0.0, -0.5, 0.0)
  50. floorNode.scale = Vector3(500.0, 1.0, 500.0)
  51. local floorObject = floorNode:CreateComponent("StaticModel")
  52. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  53. floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  54. -- Make the floor physical by adding RigidBody and CollisionShape components
  55. local body = floorNode:CreateComponent("RigidBody")
  56. local shape = floorNode:CreateComponent("CollisionShape")
  57. -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  58. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  59. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  60. end
  61. -- Create static mushrooms with triangle mesh collision
  62. local NUM_MUSHROOMS = 50
  63. for i = 1, NUM_MUSHROOMS do
  64. local mushroomNode = scene_:CreateChild("Mushroom")
  65. mushroomNode.position = Vector3(Random(400.0) - 200.0, 0.0, Random(400.0) - 200.0)
  66. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  67. mushroomNode:SetScale(5.0 + Random(5.0))
  68. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  69. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  70. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  71. mushroomObject.castShadows = true
  72. local body = mushroomNode:CreateComponent("RigidBody")
  73. local shape = mushroomNode:CreateComponent("CollisionShape")
  74. -- By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  75. shape:SetTriangleMesh(mushroomObject.model)
  76. end
  77. -- Start coroutine to create a large amount of falling physics objects
  78. coroutine.start(function()
  79. local NUM_OBJECTS = 1000
  80. for i = 1, NUM_OBJECTS do
  81. local boxNode = scene_:CreateChild("Box")
  82. boxNode.position = Vector3(0.0, 100.0, 0.0)
  83. local boxObject = boxNode:CreateComponent("StaticModel")
  84. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  85. boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml")
  86. boxObject.castShadows = true
  87. -- Give the RigidBody mass to make it movable and also adjust friction
  88. local body = boxNode:CreateComponent("RigidBody")
  89. body.mass = 1.0
  90. body.friction = 1.0
  91. -- Set linear velocity
  92. body.linearVelocity = Vector3(0.0, -50.0, 0.0)
  93. -- Disable collision event signaling to reduce CPU load of the physics simulation
  94. body.collisionEventMode = COLLISION_NEVER
  95. local shape = boxNode:CreateComponent("CollisionShape")
  96. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  97. -- sleep coroutine
  98. coroutine.sleep(0.1)
  99. end
  100. end)
  101. -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  102. -- the scene, because we want it to be unaffected by scene load/save
  103. cameraNode = Node()
  104. local camera = cameraNode:CreateComponent("Camera")
  105. camera.farClip = 300.0
  106. -- Set an initial position for the camera scene node above the floor
  107. cameraNode.position = Vector3(0.0, 3.0, -20.0)
  108. end
  109. function CreateInstructions()
  110. -- Construct new Text object, set string to display and font to use
  111. local instructionText = ui.root:CreateChild("Text")
  112. instructionText:SetText("Use WASD keys and mouse to move\n"..
  113. "LMB to spawn physics objects\n"..
  114. "F5 to save scene, F7 to load\n"..
  115. "Space to toggle physics debug geometry")
  116. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  117. -- The text has multiple rows. Center them in relation to each other
  118. instructionText.textAlignment = HA_CENTER
  119. -- Position the text relative to the screen center
  120. instructionText.horizontalAlignment = HA_CENTER
  121. instructionText.verticalAlignment = VA_CENTER
  122. instructionText:SetPosition(0, ui.root.height / 4)
  123. end
  124. function SetupViewport()
  125. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  126. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  127. renderer:SetViewport(0, viewport)
  128. end
  129. function SubscribeToEvents()
  130. -- Subscribe HandleUpdate() function for processing update events
  131. SubscribeToEvent("Update", "HandleUpdate")
  132. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  133. -- debug geometry
  134. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  135. end
  136. function MoveCamera(timeStep)
  137. -- Do not move if the UI has a focused element (the console)
  138. if ui.focusElement ~= nil then
  139. return
  140. end
  141. -- Movement speed as world units per second
  142. local MOVE_SPEED = 20.0
  143. -- Mouse sensitivity as degrees per pixel
  144. local MOUSE_SENSITIVITY = 0.1
  145. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  146. local mouseMove = input.mouseMove
  147. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  148. pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y
  149. pitch = Clamp(pitch, -90.0, 90.0)
  150. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  151. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  152. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  153. if input:GetKeyDown(KEY_W) then
  154. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  155. end
  156. if input:GetKeyDown(KEY_S) then
  157. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  158. end
  159. if input:GetKeyDown(KEY_A) then
  160. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  161. end
  162. if input:GetKeyDown(KEY_D) then
  163. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  164. end
  165. -- "Shoot" a physics object with left mousebutton
  166. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  167. SpawnObject()
  168. end
  169. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  170. -- directory
  171. if input:GetKeyPress(KEY_F5) then
  172. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml")
  173. end
  174. if input:GetKeyPress(KEY_F7) then
  175. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml")
  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 SpawnObject()
  183. -- Create a smaller box at camera position
  184. local boxNode = scene_:CreateChild("SmallBox")
  185. boxNode.position = cameraNode.position
  186. boxNode.rotation = cameraNode.rotation
  187. boxNode:SetScale(0.25)
  188. local boxObject = boxNode:CreateComponent("StaticModel")
  189. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  190. boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml")
  191. boxObject.castShadows = true
  192. -- Create physics components, use a smaller mass also
  193. local body = boxNode:CreateComponent("RigidBody")
  194. body.mass = 0.25
  195. body.friction = 0.75
  196. local shape = boxNode:CreateComponent("CollisionShape")
  197. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  198. local OBJECT_VELOCITY = 10.0
  199. -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  200. -- to overcome gravity better
  201. body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
  202. end
  203. function HandleUpdate(eventType, eventData)
  204. -- Take the frame time step, which is stored as a float
  205. local timeStep = eventData:GetFloat("TimeStep")
  206. -- Move the camera, scale movement with time step
  207. MoveCamera(timeStep)
  208. end
  209. function HandlePostRenderUpdate(eventType, eventData)
  210. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  211. if drawDebug then
  212. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  213. end
  214. end
  215. -- Create XML patch instructions for screen joystick layout specific to this sample app
  216. function GetScreenJoystickPatchString()
  217. return
  218. "<patch>" ..
  219. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  220. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" ..
  221. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  222. " <element type=\"Text\">" ..
  223. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  224. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  225. " </element>" ..
  226. " </add>" ..
  227. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  228. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  229. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  230. " <element type=\"Text\">" ..
  231. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  232. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  233. " </element>" ..
  234. " </add>" ..
  235. "</patch>"
  236. end