13_Ragdolls.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. -- Ragdoll example.
  2. -- This sample demonstrates:
  3. -- - Detecting physics collisions
  4. -- - Moving an AnimatedModel's bones with physics and connecting them with constraints
  5. -- - Using rolling friction to stop rolling objects from moving infinitely
  6. require "LuaScripts/Utilities/Sample"
  7. function Start()
  8. -- Execute the common startup for samples
  9. SampleStart()
  10. -- Create the scene content
  11. CreateScene()
  12. -- Create the UI content
  13. CreateInstructions()
  14. -- Setup the viewport for displaying the scene
  15. SetupViewport()
  16. -- Set the mouse mode to use in the sample
  17. SampleInitMouseMode(MM_RELATIVE)
  18. -- Hook up to the frame update and render post-update events
  19. SubscribeToEvents()
  20. end
  21. function CreateScene()
  22. scene_ = Scene()
  23. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  24. -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  25. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  26. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  27. scene_:CreateComponent("Octree")
  28. scene_:CreateComponent("PhysicsWorld")
  29. scene_:CreateComponent("DebugRenderer")
  30. -- Create a Zone component for ambient lighting & fog control
  31. local zoneNode = scene_:CreateChild("Zone")
  32. local zone = zoneNode:CreateComponent("Zone")
  33. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  34. zone.ambientColor = Color(0.15, 0.15, 0.15)
  35. zone.fogColor = Color(0.5, 0.5, 0.7)
  36. zone.fogStart = 100.0
  37. zone.fogEnd = 300.0
  38. -- Create a directional light to the world. Enable cascaded shadows on it
  39. local lightNode = scene_:CreateChild("DirectionalLight")
  40. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  41. local light = lightNode:CreateComponent("Light")
  42. light.lightType = LIGHT_DIRECTIONAL
  43. light.castShadows = true
  44. light.shadowBias = BiasParameters(0.00025, 0.5)
  45. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  46. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  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. -- We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that
  57. -- the spheres will eventually come to rest
  58. body.rollingFriction = 0.15
  59. local shape = floorNode:CreateComponent("CollisionShape")
  60. -- 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
  61. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  62. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  63. -- Create animated models
  64. for z = -1, 1 do
  65. for x = -4, 4 do
  66. local modelNode = scene_:CreateChild("Jack")
  67. modelNode.position = Vector3(x * 5.0, 0.0, z * 5.0)
  68. modelNode.rotation = Quaternion(0.0, 180.0, 0.0)
  69. local modelObject = modelNode:CreateComponent("AnimatedModel")
  70. modelObject.model = cache:GetResource("Model", "Models/Jack.mdl")
  71. modelObject.material = cache:GetResource("Material", "Materials/Jack.xml")
  72. modelObject.castShadows = true
  73. -- Set the model to also update when invisible to avoid staying invisible when the model should come into
  74. -- view, but does not as the bounding box is not updated
  75. modelObject.updateInvisible = true
  76. -- Create a rigid body and a collision shape. These will act as a trigger for transforming the
  77. -- model into a ragdoll when hit by a moving object
  78. local body = modelNode:CreateComponent("RigidBody")
  79. -- The trigger mode makes the rigid body only detect collisions, but impart no forces on the
  80. -- colliding objects
  81. body.trigger = true
  82. local shape = modelNode:CreateComponent("CollisionShape")
  83. -- Create the capsule shape with an offset so that it is correctly aligned with the model, which
  84. -- has its origin at the feet
  85. shape:SetCapsule(0.7, 2.0, Vector3(0.0, 1.0, 0.0))
  86. -- Create a custom script object that reacts to collisions and creates the ragdoll
  87. modelNode:CreateScriptObject("CreateRagdoll")
  88. end
  89. end
  90. -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  91. -- the scene, because we want it to be unaffected by scene load / save
  92. cameraNode = Node()
  93. local camera = cameraNode:CreateComponent("Camera")
  94. camera.farClip = 300.0
  95. -- Set an initial position for the camera scene node above the floor
  96. cameraNode.position = Vector3(0.0, 5.0, -20.0)
  97. end
  98. function CreateInstructions()
  99. -- Construct new Text object, set string to display and font to use
  100. local instructionText = ui.root:CreateChild("Text")
  101. instructionText:SetText(
  102. "Use WASD keys and mouse to move\n"..
  103. "LMB to spawn physics objects\n"..
  104. "F5 to save scene, F7 to load\n"..
  105. "Space to toggle physics debug geometry")
  106. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  107. -- The text has multiple rows. Center them in relation to each other
  108. instructionText.textAlignment = HA_CENTER
  109. -- Position the text relative to the screen center
  110. instructionText.horizontalAlignment = HA_CENTER
  111. instructionText.verticalAlignment = VA_CENTER
  112. instructionText:SetPosition(0, ui.root.height / 4)
  113. end
  114. function SetupViewport()
  115. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  116. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  117. renderer:SetViewport(0, viewport)
  118. end
  119. function SubscribeToEvents()
  120. -- Subscribe HandleUpdate() function for processing update events
  121. SubscribeToEvent("Update", "HandleUpdate")
  122. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  123. -- debug geometry
  124. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  125. end
  126. function MoveCamera(timeStep)
  127. -- Do not move if the UI has a focused element (the console)
  128. if ui.focusElement ~= nil then
  129. return
  130. end
  131. -- Movement speed as world units per second
  132. local MOVE_SPEED = 20.0
  133. -- Mouse sensitivity as degrees per pixel
  134. local MOUSE_SENSITIVITY = 0.1
  135. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  136. local mouseMove = input.mouseMove
  137. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  138. pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y
  139. pitch = Clamp(pitch, -90.0, 90.0)
  140. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  141. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  142. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  143. if input:GetKeyDown(KEY_W) then
  144. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  145. end
  146. if input:GetKeyDown(KEY_S) then
  147. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  148. end
  149. if input:GetKeyDown(KEY_A) then
  150. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  151. end
  152. if input:GetKeyDown(KEY_D) then
  153. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  154. end
  155. -- "Shoot" a physics object with left mousebutton
  156. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  157. SpawnObject()
  158. end
  159. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  160. -- directory
  161. if input:GetKeyPress(KEY_F5) then
  162. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml")
  163. end
  164. if input:GetKeyPress(KEY_F7) then
  165. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml")
  166. end
  167. -- Toggle debug geometry with space
  168. if input:GetKeyPress(KEY_SPACE) then
  169. drawDebug = not drawDebug
  170. end
  171. end
  172. function SpawnObject()
  173. local boxNode = scene_:CreateChild("Sphere")
  174. boxNode.position = cameraNode.position
  175. boxNode.rotation = cameraNode.rotation
  176. boxNode:SetScale(0.25)
  177. local boxObject = boxNode:CreateComponent("StaticModel")
  178. boxObject.model = cache:GetResource("Model", "Models/Sphere.mdl")
  179. boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml")
  180. boxObject.castShadows = true
  181. local body = boxNode:CreateComponent("RigidBody")
  182. body.mass = 1.0
  183. body.rollingFriction = 0.15
  184. local shape = boxNode:CreateComponent("CollisionShape")
  185. shape:SetSphere(1.0)
  186. local OBJECT_VELOCITY = 10.0
  187. -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  188. -- to overcome gravity better
  189. body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
  190. end
  191. function HandleUpdate(eventType, eventData)
  192. -- Take the frame time step, which is stored as a float
  193. local timeStep = eventData["TimeStep"]:GetFloat()
  194. -- Move the camera, scale movement with time step
  195. MoveCamera(timeStep)
  196. end
  197. function HandlePostRenderUpdate(eventType, eventData)
  198. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  199. if drawDebug then
  200. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  201. end
  202. end
  203. -- CreateRagdoll script object class
  204. CreateRagdoll = ScriptObject()
  205. function CreateRagdoll:Start()
  206. -- Subscribe physics collisions that concern this scene node
  207. self:SubscribeToEvent(self.node, "NodeCollision", "CreateRagdoll:HandleNodeCollision")
  208. end
  209. function CreateRagdoll:HandleNodeCollision(eventType, eventData)
  210. -- Get the other colliding body, make sure it is moving (has nonzero mass)
  211. local otherBody = eventData["OtherBody"]:GetPtr("RigidBody")
  212. if otherBody.mass > 0.0 then
  213. -- We do not need the physics components in the AnimatedModel's root scene node anymore
  214. self.node:RemoveComponent("RigidBody")
  215. self.node:RemoveComponent("CollisionShape")
  216. -- Create RigidBody & CollisionShape components to bones
  217. self:CreateRagdollBone("Bip01_Pelvis", SHAPE_BOX, Vector3(0.3, 0.2, 0.25), Vector3(0.0, 0.0, 0.0),
  218. Quaternion(0.0, 0.0, 0.0))
  219. self:CreateRagdollBone("Bip01_Spine1", SHAPE_BOX, Vector3(0.35, 0.2, 0.3), Vector3(0.15, 0.0, 0.0),
  220. Quaternion(0.0, 0.0, 0.0))
  221. self:CreateRagdollBone("Bip01_L_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0),
  222. Quaternion(0.0, 0.0, 90.0))
  223. self:CreateRagdollBone("Bip01_R_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0),
  224. Quaternion(0.0, 0.0, 90.0))
  225. self:CreateRagdollBone("Bip01_L_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0),
  226. Quaternion(0.0, 0.0, 90.0))
  227. self:CreateRagdollBone("Bip01_R_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0),
  228. Quaternion(0.0, 0.0, 90.0))
  229. self:CreateRagdollBone("Bip01_Head", SHAPE_BOX, Vector3(0.2, 0.2, 0.2), Vector3(0.1, 0.0, 0.0),
  230. Quaternion(0.0, 0.0, 0.0))
  231. self:CreateRagdollBone("Bip01_L_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0),
  232. Quaternion(0.0, 0.0, 90.0))
  233. self:CreateRagdollBone("Bip01_R_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0),
  234. Quaternion(0.0, 0.0, 90.0))
  235. self:CreateRagdollBone("Bip01_L_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0),
  236. Quaternion(0.0, 0.0, 90.0))
  237. self:CreateRagdollBone("Bip01_R_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0),
  238. Quaternion(0.0, 0.0, 90.0))
  239. -- Create Constraints between bones
  240. self:CreateRagdollConstraint("Bip01_L_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0),
  241. Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true)
  242. self:CreateRagdollConstraint("Bip01_R_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0),
  243. Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true)
  244. self:CreateRagdollConstraint("Bip01_L_Calf", "Bip01_L_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0),
  245. Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true)
  246. self:CreateRagdollConstraint("Bip01_R_Calf", "Bip01_R_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0),
  247. Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true)
  248. self:CreateRagdollConstraint("Bip01_Spine1", "Bip01_Pelvis", CONSTRAINT_HINGE, Vector3(0.0, 0.0, 1.0),
  249. Vector3(0.0, 0.0, 1.0), Vector2(45.0, 0.0), Vector2(-10.0, 0.0), true)
  250. self:CreateRagdollConstraint("Bip01_Head", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(-1.0, 0.0, 0.0),
  251. Vector3(-1.0, 0.0, 0.0), Vector2(0.0, 30.0), Vector2(0.0, 0.0), true)
  252. self:CreateRagdollConstraint("Bip01_L_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0),
  253. Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false)
  254. self:CreateRagdollConstraint("Bip01_R_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0),
  255. Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false)
  256. self:CreateRagdollConstraint("Bip01_L_Forearm", "Bip01_L_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0),
  257. Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true)
  258. self:CreateRagdollConstraint("Bip01_R_Forearm", "Bip01_R_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0),
  259. Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true)
  260. -- Disable keyframe animation from all bones so that they will not interfere with the ragdoll
  261. local model = self.node:GetComponent("AnimatedModel")
  262. local skeleton = model.skeleton
  263. for i = 0, skeleton.numBones - 1 do
  264. skeleton:GetBone(i).animated = false
  265. end
  266. -- Finally remove self (the ScriptInstance which holds this script object) from the scene node. Note that this must
  267. -- be the last operation performed in the function
  268. self.instance:Remove()
  269. end
  270. end
  271. function CreateRagdoll:CreateRagdollBone(boneName, type, size, position, rotation)
  272. -- Find the correct child scene node recursively
  273. local boneNode = self.node:GetChild(boneName, true)
  274. if boneNode == nil then
  275. print("Could not find bone " .. boneName .. " for creating ragdoll physics components\n")
  276. return
  277. end
  278. local body = boneNode:CreateComponent("RigidBody")
  279. -- Set mass to make movable
  280. body.mass = 1.0
  281. -- Set damping parameters to smooth out the motion
  282. body.linearDamping = 0.05
  283. body.angularDamping = 0.85
  284. -- Set rest thresholds to ensure the ragdoll rigid bodies come to rest to not consume CPU endlessly
  285. body.linearRestThreshold = 1.5
  286. body.angularRestThreshold = 2.5
  287. local shape = boneNode:CreateComponent("CollisionShape")
  288. -- We use either a box or a capsule shape for all of the bones
  289. if type == SHAPE_BOX then
  290. shape:SetBox(size, position, rotation)
  291. else
  292. shape:SetCapsule(size.x, size.y, position, rotation)
  293. end
  294. end
  295. function CreateRagdoll:CreateRagdollConstraint(boneName, parentName, type, axis, parentAxis, highLimit, lowLimit, disableCollision)
  296. local boneNode = self.node:GetChild(boneName, true)
  297. local parentNode = self.node:GetChild(parentName, true)
  298. if boneNode == nil then
  299. print("Could not find bone " .. boneName .. " for creating ragdoll constraint\n")
  300. return
  301. end
  302. if parentNode == nil then
  303. print("Could not find bone " .. parentName .. " for creating ragdoll constraint\n")
  304. return
  305. end
  306. local constraint = boneNode:CreateComponent("Constraint")
  307. constraint.constraintType = type
  308. -- Most of the constraints in the ragdoll will work better when the connected bodies don't collide against each other
  309. constraint.disableCollision = disableCollision
  310. -- The connected body must be specified before setting the world position
  311. constraint.otherBody = parentNode:GetComponent("RigidBody")
  312. -- Position the constraint at the child bone we are connecting
  313. constraint.worldPosition = boneNode.worldPosition
  314. -- Configure axes and limits
  315. constraint.axis = axis
  316. constraint.otherAxis = parentAxis
  317. constraint.highLimit = highLimit
  318. constraint.lowLimit = lowLimit
  319. end
  320. -- Create XML patch instructions for screen joystick layout specific to this sample app
  321. function GetScreenJoystickPatchString()
  322. return
  323. "<patch>" ..
  324. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  325. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" ..
  326. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  327. " <element type=\"Text\">" ..
  328. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  329. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  330. " </element>" ..
  331. " </add>" ..
  332. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  333. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  334. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  335. " <element type=\"Text\">" ..
  336. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  337. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  338. " </element>" ..
  339. " </add>" ..
  340. "</patch>"
  341. end