13_Ragdolls.lua 19 KB

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