11_Physics.lua 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. -- Physics example.
  2. -- This sample demonstrates:
  3. -- - Creating both static and moving physics objects to a scene
  4. -- - Displaying physics debug geometry
  5. -- - Using the Skybox component for setting up an unmoving sky
  6. -- - Saving a scene to a file and loading it to restore a previous state
  7. require "LuaScripts/Utilities/Sample"
  8. local scene_ = nil
  9. local cameraNode = nil
  10. local yaw = 0.0
  11. local pitch = 0.0
  12. local drawDebug = false
  13. function Start()
  14. -- Execute the common startup for samples
  15. SampleStart()
  16. -- Create the scene content
  17. CreateScene()
  18. -- Create the UI content
  19. CreateInstructions()
  20. -- Setup the viewport for displaying the scene
  21. SetupViewport()
  22. -- Hook up to the frame update and render post-update events
  23. SubscribeToEvents()
  24. end
  25. function CreateScene()
  26. scene_ = Scene()
  27. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  28. -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  29. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  30. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  31. scene_:CreateComponent("Octree")
  32. scene_:CreateComponent("PhysicsWorld")
  33. scene_:CreateComponent("DebugRenderer")
  34. -- Create a Zone component for ambient lighting & fog control
  35. local zoneNode = scene_:CreateChild("Zone")
  36. local zone = zoneNode:CreateComponent("Zone")
  37. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  38. zone.ambientColor = Color(0.15, 0.15, 0.15)
  39. zone.fogColor = Color(1.0, 1.0, 1.0)
  40. zone.fogStart = 300.0
  41. zone.fogEnd = 500.0
  42. -- Create a directional light to the world. Enable cascaded shadows on it
  43. local lightNode = scene_:CreateChild("DirectionalLight")
  44. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  45. local light = lightNode:CreateComponent("Light")
  46. light.lightType = LIGHT_DIRECTIONAL
  47. light.castShadows = true
  48. light.shadowBias = BiasParameters(0.00025, 0.5)
  49. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  50. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  51. -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  52. -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  53. -- generate the necessary 3D texture coordinates for cube mapping
  54. local skyNode = scene_:CreateChild("Sky")
  55. skyNode:SetScale(500.0) -- The scale actually does not matter
  56. local skybox = skyNode:CreateComponent("Skybox")
  57. skybox.model = cache:GetResource("Model", "Models/Box.mdl")
  58. skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
  59. -- Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  60. local floorNode = scene_:CreateChild("Floor")
  61. floorNode.position = Vector3(0.0, -0.5, 0.0)
  62. floorNode.scale = Vector3(1000.0, 1.0, 1000.0)
  63. local floorObject = floorNode:CreateComponent("StaticModel")
  64. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  65. floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  66. -- Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  67. -- parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  68. -- in the physics simulation
  69. local body = floorNode:CreateComponent("RigidBody")
  70. local shape = floorNode:CreateComponent("CollisionShape")
  71. -- 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
  72. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  73. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  74. -- Create a pyramid of movable physics objects
  75. for y = 0, 7 do
  76. for x = -y, y do
  77. local boxNode = scene_:CreateChild("Box")
  78. boxNode.position = Vector3(x, -y + 8.0, 0.0)
  79. local boxObject = boxNode:CreateComponent("StaticModel")
  80. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  81. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  82. boxObject.castShadows = true
  83. -- Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  84. -- and also adjust friction. The actual mass is not important only the mass ratios between colliding
  85. -- objects are significant
  86. local body = boxNode:CreateComponent("RigidBody")
  87. body.mass = 1.0
  88. body.friction = 0.75
  89. local shape = boxNode:CreateComponent("CollisionShape")
  90. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  91. end
  92. end
  93. -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  94. -- the scene, because we want it to be unaffected by scene load / save
  95. cameraNode = Node()
  96. local camera = cameraNode:CreateComponent("Camera")
  97. camera.farClip = 500.0
  98. -- Set an initial position for the camera scene node above the floor
  99. cameraNode.position = Vector3(0.0, 5.0, -20.0)
  100. end
  101. function CreateInstructions()
  102. -- Construct new Text object, set string to display and font to use
  103. local instructionText = ui.root:CreateChild("Text")
  104. instructionText:SetText("Use WASD keys and mouse to move\n"..
  105. "LMB to spawn physics objects\n"..
  106. "F5 to save scene, F7 to load\n"..
  107. "Space to toggle physics debug geometry")
  108. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  109. -- The text has multiple rows. Center them in relation to each other
  110. instructionText.textAlignment = HA_CENTER
  111. -- Position the text relative to the screen center
  112. instructionText.horizontalAlignment = HA_CENTER
  113. instructionText.verticalAlignment = VA_CENTER
  114. instructionText:SetPosition(0, ui.root.height / 4)
  115. end
  116. function SetupViewport()
  117. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  118. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  119. renderer:SetViewport(0, viewport)
  120. end
  121. function SubscribeToEvents()
  122. -- Subscribe HandleUpdate() function for processing update events
  123. SubscribeToEvent("Update", "HandleUpdate")
  124. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  125. -- debug geometry
  126. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  127. end
  128. function MoveCamera(timeStep)
  129. -- Do not move if the UI has a focused element (the console)
  130. if ui.focusElement ~= nil then
  131. return
  132. end
  133. -- Movement speed as world units per second
  134. local MOVE_SPEED = 20.0
  135. -- Mouse sensitivity as degrees per pixel
  136. local MOUSE_SENSITIVITY = 0.1
  137. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  138. local mouseMove = input.mouseMove
  139. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  140. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  141. pitch = Clamp(pitch, -90.0, 90.0)
  142. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  143. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  144. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  145. if input:GetKeyDown(KEY_W) then
  146. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  147. end
  148. if input:GetKeyDown(KEY_S) then
  149. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  150. end
  151. if input:GetKeyDown(KEY_A) then
  152. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  153. end
  154. if input:GetKeyDown(KEY_D) then
  155. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  156. end
  157. -- "Shoot" a physics object with left mousebutton
  158. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  159. SpawnObject()
  160. end
  161. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  162. -- directory
  163. if input:GetKeyPress(KEY_F5) then
  164. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  165. end
  166. if input:GetKeyPress(KEY_F7) then
  167. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  168. end
  169. -- Toggle debug geometry with space
  170. if input:GetKeyPress(KEY_SPACE) then
  171. drawDebug = not drawDebug
  172. end
  173. end
  174. function SpawnObject()
  175. -- Create a smaller box at camera position
  176. local boxNode = scene_:CreateChild("SmallBox")
  177. boxNode.position = cameraNode.position
  178. boxNode.rotation = cameraNode.rotation
  179. boxNode:SetScale(0.25)
  180. local boxObject = boxNode:CreateComponent("StaticModel")
  181. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  182. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  183. boxObject.castShadows = true
  184. -- Create physics components, use a smaller mass also
  185. local body = boxNode:CreateComponent("RigidBody")
  186. body.mass = 0.25
  187. body.friction = 0.75
  188. local shape = boxNode:CreateComponent("CollisionShape")
  189. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  190. local OBJECT_VELOCITY = 10.0
  191. -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  192. -- to overcome gravity better
  193. body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
  194. end
  195. function HandleUpdate(eventType, eventData)
  196. -- Take the frame time step, which is stored as a float
  197. local timeStep = eventData:GetFloat("TimeStep")
  198. -- Move the camera, scale movement with time step
  199. MoveCamera(timeStep)
  200. end
  201. function HandlePostRenderUpdate(eventType, eventData)
  202. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  203. -- Note the convenience accessor to the physics world component
  204. if drawDebug then
  205. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  206. end
  207. end