13_Ragdolls.lua 18 KB

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