13_Ragdolls.lua 18 KB

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