12_PhysicsStressTest.lua 12 KB

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