11_Physics.lua 11 KB

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