Introduction


What is a 'ragdoll'?

From widipedia http://en.wikipedia.org/wiki/Ragdoll_physics

Early video games used manually created animations for characters' death sequences. This had the advantage of low CPU utilization, as the data needed to animate a "dying" character was chosen from a set number of pre-drawn frames. As computers increased in power, it became possible to do limited real-time physical simulations. A ragdoll is therefore a collection of multiple rigid bodies (each of which is ordinarily tied to a bone in the graphics engine's skeletal animation system) tied together by a system of constraints that restrict how the bones may move relative to each other. When the character dies, their body begins to collapse to the ground, honouring these restrictions on each of the joints' motion, which often looks more realistic.

The term ragdoll comes from the problem that the articulated systems, due to the limits of the solvers used, tend to have little or zero joint/skeletal muscle stiffness, leading to a character collapsing much like a toy rag doll, often into comically improbable or compromising positions.

Caveat


This is not turn-key code. You will need to adapt this to your own model. The code linked below just handles the ragdoll components and not the setting up of your Ogre::SceneNodes or Ogre::AnimationStates

Pre-requisites

  • Ogre 1.8 or later.
  • You have a functioning application with an in-game object that you'd like to ragdoll, this object should be encapsulated in its own class and should have a animations.
  • You have integrated Bullet Physics into your application, if you are using another physics engine then the concepts will be the same but the terminology may differ.
  • You have looked at the Bullet Physics ragdoll demo (and the code behind it) as much of this tutorial is based on that. Here is a youtube link of that demo: http://www.youtube.com/watch?v=6306NHb9nq4

Theory


The premise is that you have an animated Ogre::Entity (henceforth known as 'creep') moving around your scene and on some event it starts ragdolling e.g when it's health gets to zero.

To accomplish this we will encapsulate our creep in a class with some functions that can be called by your engine to initialise, and later, activate ragdoll mode.

The idea is that we'll be creating a simplified version of our creep using physics shapes that are connected to each other using physics constraints. These constraints will be defined by you to mimic the creep's physiology, in this case, we'll be using a humanoid. Constraints let us approximate things like knees which act like a door hinge and your neck which is more like a ball and socket. These physics shapes that we create will have an approximate mapping to your creep's Ogre::Bone's. We won't attempt to map every bone to a physics object because this makes the process much more time consuming and may not actually make your game any better, of course, your requirements may vary. The bones we care about will henceforth be known as 'major bones'.

When the creep dies it will be in some un-foreseeable state with regard to its Ogre::AnimationState. We need the ability to copy the location and orientation of the creep's bone's at its time of death to our physics representation. At that point we cease to animate the model and instead apply Bullet's idea of the model to our Ogre::Bone's. We hand over control of our creep to Bullet.

Approach

  • When the creep object is instantiated we'll create physics objects for the major bones but we won't add them to Bullet's PhysicsWorld just yet. This maps to a function called 'initRagdoll()'
  • initRagdoll() also records each major bone's initial position and orientation as well as each physics object's orientation and position. Recording the intial state of everything is important because when we want to set the physics state to replicate the Ogre::AnimationState (and vice versa) we'll be dealing with relative rotations.
  • It's a lot easier to setup Physics shapes for your model when it's in a T-pose because the initial state will be done using code instead of a nice GUI editor. Hopefully your model has it's binding pose as a T-pose or your modeller has at least given you an animation that sets the creep in such a state.
  • There will be a function named copyModelStateToRagdoll() which is called once at time of death. Its job is to set the physics shapes to match the current position of your major bones as defined by your Ogre::AnimationState.
  • There will be a function named copyRagdollStateToModel() which is called every frame while the model is ragdolling.
  • There will be a function named startRagdolling() which calls copyModelStateToRagdoll(), sets your major bones to be manually controlled, disables any active animations and finally adds your physics shapes and constraints into the physics world.
  • There will be a function named removeRagoll() which will clean up all the physics objects when your object is eventually destroyed.
  • In copyRagdollStateToModel() we never actually set a bone's position, instead we set the model's scenenode to be that of the root bone. This is because Ogre uses your model's bounding box to decide if it should be culled from the render. If we had the situation where your scenenode was out of the camera's view but the bone's weren't then the model would disappear! As all the bones are still set to derive their position from their parents then we actually save ourselves some work by using this method.

Procedure


The first step is to figure out which bones you want to use as your major bones. The assumption is that your artist has given you .mesh and .skeleton file with no other information. To identify the bones you care about use 'Ogre Meshy' or explore the XML of the supplied files.

Here's what our model looks like in meshy

Image

And here's the hard way of doing things

[areay@arrakis legionary]$ OgreXMLConverter legionary.skeleton
[areay@arrakis legionary]$ grep 'boneparent' legionary.skeleton.xml 
        <boneparent bone="Bind_Hips" parent="Bind_Root" />
        <boneparent bone="Bind_LeftUpLeg" parent="Bind_Hips" />
        <boneparent bone="Bind_LeftLeg" parent="Bind_LeftUpLeg" />
        <boneparent bone="Bind_LeftFoot" parent="Bind_LeftLeg" />
        <boneparent bone="Bind_LeftToeBase" parent="Bind_LeftFoot" />
        <boneparent bone="Bind_RightUpLeg" parent="Bind_Hips" />
        <boneparent bone="Bind_RightLeg" parent="Bind_RightUpLeg" />
        <boneparent bone="Bind_RightFoot" parent="Bind_RightLeg" />
        <boneparent bone="Bind_RightToeBase" parent="Bind_RightFoot" />
        <boneparent bone="Bind_Spine" parent="Bind_Root" />
        <boneparent bone="Bind_Spine1" parent="Bind_Spine" />
        <boneparent bone="Bind_Spine2" parent="Bind_Spine1" />
        <boneparent bone="Bind_Neck" parent="Bind_Spine2" />
        <boneparent bone="Bind_Head" parent="Bind_Neck" />
        <boneparent bone="Bind_LeftShoulder" parent="Bind_Spine2" />
        <boneparent bone="Bind_LeftArm" parent="Bind_LeftShoulder" />
        <boneparent bone="Bind_LeftForeArm" parent="Bind_LeftArm" />
        <boneparent bone="Bind_LeftHand" parent="Bind_LeftForeArm" />
        <boneparent bone="Bind_RightShoulder" parent="Bind_Spine2" />
        <boneparent bone="Bind_RightArm" parent="Bind_RightShoulder" />
        <boneparent bone="Bind_RightForeArm" parent="Bind_RightArm" />
        <boneparent bone="Bind_RightHand" parent="Bind_RightForeArm" />
        
        */many more omitted*/


So this is pretty obvious, we have a bone with no parent 'Bind_Root' which we'll term our 'root bone' and a bunch of other bones. We'll use discretion here, we don't really care about shoulders or hands and although there are 3 bones for the spine we'll just use one physics object to cover all three of them.

In our creep's class header we'll define enumerations for our physics objects and physics constraints, containers for our initial values and physics objects, a boolean to decide if we're ragdolling or not and an offset which will discussed later

enum
	{
		BODYPART_HIPS =0,
		BODYPART_SPINE,
		BODYPART_HEAD,

		BODYPART_LEFT_UPPER_LEG,
		BODYPART_LEFT_LOWER_LEG,

		BODYPART_RIGHT_UPPER_LEG,
		BODYPART_RIGHT_LOWER_LEG,

		BODYPART_LEFT_UPPER_ARM,
		BODYPART_LEFT_LOWER_ARM,

		BODYPART_RIGHT_UPPER_ARM,
		BODYPART_RIGHT_LOWER_ARM,

		BODYPART_GUN,

		BODYPART_COUNT
	};

	enum
	{
		JOINT_PELVIS_SPINE = 0,
		JOINT_SPINE_HEAD,

		JOINT_LEFT_HIP,
		JOINT_LEFT_KNEE,

		JOINT_RIGHT_HIP,
		JOINT_RIGHT_KNEE,

		JOINT_LEFT_SHOULDER,
		JOINT_LEFT_ELBOW,

		JOINT_RIGHT_SHOULDER,
		JOINT_RIGHT_ELBOW,

		JOINT_GUN,

		JOINT_COUNT
	};

	Ogre::SkeletonInstance *m_pSkeleton;

	btCollisionShape* m_shapes[BODYPART_COUNT];
	btRigidBody* m_bodies[BODYPART_COUNT];
	btTypedConstraint* m_joints[JOINT_COUNT];

	Ogre::Bone *m_Bones[BODYPART_COUNT];
	Ogre::Quaternion m_BoneInitialOrientation[BODYPART_COUNT];
	Ogre::Vector3 m_BoneInitialPosition[BODYPART_COUNT];

	Ogre::Vector3 m_BodyInitialPosition[BODYPART_COUNT];
	Ogre::Quaternion m_BodyInitialOrientation[BODYPART_COUNT];

	bool m_bIsRagdolling;
        Ogre::Vector3 m_RagdollOffset;


Here's our implementation

void HumanCreep::initRagdoll()
{
	btScalar pi(3.14159);
	btScalar pi_2(1.57079);
	btScalar pi_4(0.78539);

	m_Bones[BODYPART_HIPS] = m_pSkeleton->getBone("Bind_Root");
	m_Bones[BODYPART_SPINE] = m_pSkeleton->getBone("Bind_Spine1");
	m_Bones[BODYPART_HEAD] = m_pSkeleton->getBone("Bind_Head");
	m_Bones[BODYPART_LEFT_UPPER_LEG] =  m_pSkeleton->getBone("Bind_RightUpLeg");
	m_Bones[BODYPART_LEFT_LOWER_LEG] =  m_pSkeleton->getBone("Bind_RightLeg");
	m_Bones[BODYPART_RIGHT_UPPER_LEG] = m_pSkeleton->getBone("Bind_LeftUpLeg");
	m_Bones[BODYPART_RIGHT_LOWER_LEG] = m_pSkeleton->getBone("Bind_LeftLeg");
	m_Bones[BODYPART_LEFT_UPPER_ARM] =  m_pSkeleton->getBone("Bind_RightArm");
	m_Bones[BODYPART_LEFT_LOWER_ARM] =  m_pSkeleton->getBone("Bind_RightForeArm");
	m_Bones[BODYPART_RIGHT_UPPER_ARM] = m_pSkeleton->getBone("Bind_LeftArm");
	m_Bones[BODYPART_RIGHT_LOWER_ARM] = m_pSkeleton->getBone("Bind_LeftForeArm");
	m_Bones[BODYPART_GUN] = m_pSkeleton->getBone("Bind_RightHand");

	Ogre::AnimationState *animState = m_pEntity->getAnimationState("tPose");
	animState->setEnabled(true);
	animState->setLoop(false);
	animState->setTimePosition(100.f);
	m_pEntity->_updateAnimation(); //critical! read this functions comments!

	// set bones to manually controlled and get their initial orientations too
	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		m_BoneInitialOrientation[i] = m_Bones[i]->_getDerivedOrientation();
		m_BoneInitialPosition[i] = m_Bones[i]->_getDerivedPosition();
	}

	animState->setEnabled(false);

	// Setup the geometry
	m_shapes[BODYPART_HIPS] = new btCapsuleShape(btScalar(0.2), btScalar(0.05));
	m_shapes[BODYPART_SPINE] = new btCapsuleShape(btScalar(0.2), btScalar(0.05));
	m_shapes[BODYPART_HEAD] = new btCapsuleShape(btScalar(0.1), btScalar(0.1));
	m_shapes[BODYPART_LEFT_UPPER_LEG] = new btCapsuleShape(btScalar(0.1), btScalar(0.2));
	m_shapes[BODYPART_LEFT_LOWER_LEG] = new btCapsuleShape(btScalar(0.1), btScalar(0.35));
	m_shapes[BODYPART_RIGHT_UPPER_LEG] = new btCapsuleShape(btScalar(0.1), btScalar(0.2));
	m_shapes[BODYPART_RIGHT_LOWER_LEG] = new btCapsuleShape(btScalar(0.1), btScalar(0.35));
	m_shapes[BODYPART_LEFT_UPPER_ARM] = new btCapsuleShape(btScalar(0.1), btScalar(0.15));
	m_shapes[BODYPART_LEFT_LOWER_ARM] = new btCapsuleShape(btScalar(0.1), btScalar(0.12));
	m_shapes[BODYPART_RIGHT_UPPER_ARM] = new btCapsuleShape(btScalar(0.1), btScalar(0.15));
	m_shapes[BODYPART_RIGHT_LOWER_ARM] = new btCapsuleShape(btScalar(0.1), btScalar(0.12));
	m_shapes[BODYPART_GUN] = new btCapsuleShape(btScalar(0.1), btScalar(0.6));

	// Setup all the rigid bodies
	btTransform offset; offset.setIdentity();
	offset.setOrigin(btVector3(0,0,0));

	btTransform transform;
	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(0.95f), btScalar(0.)));
	m_bodies[BODYPART_HIPS] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_HIPS]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(1.3), btScalar(0.)));
	m_bodies[BODYPART_SPINE] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_SPINE]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(1.7), btScalar(0.35)));
	m_bodies[BODYPART_HEAD] = localCreateRigidBody(btScalar(1), offset*transform, m_shapes[BODYPART_HEAD]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.15), btScalar(0.65), btScalar(0.)));
	m_bodies[BODYPART_LEFT_UPPER_LEG] = localCreateRigidBody(btScalar(1), offset*transform, m_shapes[BODYPART_LEFT_UPPER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.16), btScalar(0.25), btScalar(0.)));
	m_bodies[BODYPART_LEFT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.15), btScalar(0.65), btScalar(0.)));
	m_bodies[BODYPART_RIGHT_UPPER_LEG] = localCreateRigidBody(btScalar(1), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.16), btScalar(0.25), btScalar(0.)));
	m_bodies[BODYPART_RIGHT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.3), btScalar(1.25), btScalar(0.1)));
	transform.getBasis().setEulerZYX(0,0,pi_2);
	m_bodies[BODYPART_LEFT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.6), btScalar(1.25), btScalar(0.1)));
	transform.getBasis().setEulerZYX(0,0,pi_2);
	m_bodies[BODYPART_LEFT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.3), btScalar(1.25), btScalar(0.1)));
	transform.getBasis().setEulerZYX(0,0,-pi_2);
	m_bodies[BODYPART_RIGHT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.6), btScalar(1.25), btScalar(0.1)));
	transform.getBasis().setEulerZYX(0,0,-pi_2);
	m_bodies[BODYPART_RIGHT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-1.2), btScalar(1.25), btScalar(0.1)));
	transform.getBasis().setEulerZYX(0,0,pi_2);
	m_bodies[BODYPART_GUN] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_GUN]);

	// Setup some damping on the m_bodies
	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		m_bodies[i]->setDamping(0.05, 0.85);
		m_bodies[i]->setDeactivationTime(3.0);
		m_bodies[i]->setSleepingThresholds(5.6, 5.5);
		m_bodies[i]->setContactProcessingThreshold(0.25f);
		m_bodies[i]->setCcdMotionThreshold(0.05f);
		m_bodies[i]->setCcdSweptSphereRadius(0.06f);
		m_BodyInitialOrientation[i] = BtOgre::Convert::toOgre(m_bodies[i]->getOrientation());
		m_BodyInitialPosition[i] = BtOgre::Convert::toOgre(m_bodies[i]->getCenterOfMassPosition());
	}

	// Now setup the constraints
	btHingeConstraint* hingeC;
	btConeTwistConstraint* coneC;

	btTransform localA, localB;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.15), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.15), btScalar(0.)));
	hingeC =  new btHingeConstraint(*m_bodies[BODYPART_HIPS], *m_bodies[BODYPART_SPINE], localA, localB);
	hingeC->setLimit(btScalar(-pi_4 ), btScalar(pi_2));
	m_joints[JOINT_PELVIS_SPINE] = hingeC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,0,-pi_2); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.2), btScalar(0.15)));
	localB.getBasis().setEulerZYX(0,0,-pi_2); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.1), btScalar(0.0)));
	coneC = new btConeTwistConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_HEAD], localA, localB);
	coneC->setLimit(pi_4, pi_4, pi_4);
	m_joints[JOINT_SPINE_HEAD] = coneC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,0,pi_4*5); localA.setOrigin(btVector3(btScalar(-0.05), btScalar(-0.1), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,0,pi_4*5); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.1), btScalar(0.)));
	coneC = new btConeTwistConstraint(*m_bodies[BODYPART_HIPS], *m_bodies[BODYPART_LEFT_UPPER_LEG], localA, localB);
	coneC->setLimit(pi_4 / 2.0f, pi_4 / 2.0f, 0);
	m_joints[JOINT_LEFT_HIP] = coneC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185), btScalar(0.)));
	hingeC =  new btHingeConstraint(*m_bodies[BODYPART_LEFT_UPPER_LEG], *m_bodies[BODYPART_LEFT_LOWER_LEG], localA, localB);
	hingeC->setLimit(btScalar(0), btScalar(pi_2));
	m_joints[JOINT_LEFT_KNEE] = hingeC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,0,-pi_4); localA.setOrigin(btVector3(btScalar(0.05), btScalar(-0.10), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,0,-pi_4); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.1), btScalar(0.)));
	coneC = new btConeTwistConstraint(*m_bodies[BODYPART_HIPS], *m_bodies[BODYPART_RIGHT_UPPER_LEG], localA, localB);
	coneC->setLimit(pi_4 / 2.0f, pi_4 / 2.0f, 0);
	m_joints[JOINT_RIGHT_HIP] = coneC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185), btScalar(0.)));
	hingeC =  new btHingeConstraint(*m_bodies[BODYPART_RIGHT_UPPER_LEG], *m_bodies[BODYPART_RIGHT_LOWER_LEG], localA, localB);
	hingeC->setLimit(btScalar(0), btScalar(pi_2));
	m_joints[JOINT_RIGHT_KNEE] = hingeC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,0,pi); localA.setOrigin(btVector3(btScalar(-0.15), btScalar(-0.1), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,0,pi_2); localB.setOrigin(btVector3(btScalar(-0.1), btScalar(0.1), btScalar(0.)));
	coneC = new btConeTwistConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_LEFT_UPPER_ARM], localA, localB);
	coneC->setLimit(pi_4, pi_4, 0);
	m_joints[JOINT_LEFT_SHOULDER] = coneC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14), btScalar(0.)));
	hingeC =  new btHingeConstraint(*m_bodies[BODYPART_LEFT_UPPER_ARM], *m_bodies[BODYPART_LEFT_LOWER_ARM], localA, localB);
	hingeC->setLimit(btScalar(0), btScalar(pi_2));
	m_joints[JOINT_LEFT_ELBOW] = hingeC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,0,0); localA.setOrigin(btVector3(btScalar(0.15), btScalar(-0.1), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,0,pi_2); localB.setOrigin(btVector3(btScalar(0.1), btScalar(0.1), btScalar(0.)));
	coneC = new btConeTwistConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_RIGHT_UPPER_ARM], localA, localB);
	coneC->setLimit(pi_4, pi_4, 0);
	m_joints[JOINT_RIGHT_SHOULDER] = coneC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14), btScalar(0.)));
	hingeC =  new btHingeConstraint(*m_bodies[BODYPART_RIGHT_UPPER_ARM], *m_bodies[BODYPART_RIGHT_LOWER_ARM], localA, localB);
	hingeC->setLimit(btScalar(0), btScalar(pi_2));
	m_joints[JOINT_RIGHT_ELBOW] = hingeC;

	localA.setIdentity(); localB.setIdentity();
	localA.getBasis().setEulerZYX(0,-pi_2,0); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.2), btScalar(0.)));
	localB.getBasis().setEulerZYX(0,-pi_2,0); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.3), btScalar(-0.2)));
	coneC =  new btConeTwistConstraint(*m_bodies[BODYPART_LEFT_LOWER_ARM], *m_bodies[BODYPART_GUN], localA, localB);
	coneC->setLimit(pi_4, pi_4, 0);
	m_joints[JOINT_GUN] = coneC;
}


void HumanCreep::copyModelStateToRagdoll()
{
	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		btTransform &t = m_bodies[i]->getWorldTransform();

		t.setRotation(BtOgre::Convert::toBullet(m_pModelNode->_getDerivedOrientation() *
				m_Bones[i]->_getDerivedOrientation() *
				m_BoneInitialOrientation[i].Inverse()) * t.getRotation());

		t.setOrigin(BtOgre::Convert::toBullet(m_pModelNode->_getDerivedPosition()  +
				(m_pModelNode->_getDerivedOrientation() *
				m_Bones[i]->_getDerivedPosition()) * m_Scale));
	}
}

void HumanCreep::copyRagdollStateToModel()
{
	Ogre::Vector3 dest = BtOgre::Convert::toOgre(m_bodies[0]->getWorldTransform().getOrigin()) - m_RagdollOffset;
	m_pModelNode->_setDerivedPosition(dest);

	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		m_Bones[i]->setOrientation(m_pModelNode->_getDerivedOrientation().Inverse() *
				(BtOgre::Convert::toOgre(m_bodies[i]->getOrientation())) *
				m_BodyInitialOrientation[i].Inverse() *
				m_BoneInitialOrientation[i]);
	}
}

void HumanCreep::removeRagdoll()
{
	m_bAreRagdollBodiesValid = false;
	// Remove all constraints
	for ( int i = 0; i < JOINT_COUNT; ++i)
	{
		m_pPhysicsWorld->removeConstraint(m_joints[i]);
		delete m_joints[i]; m_joints[i] = 0;
	}

	// Remove all bodies and shapes
	for ( int i = 0; i < BODYPART_COUNT; ++i)
	{
		m_pPhysicsWorld->removeRigidBody(m_bodies[i]);

		delete m_bodies[i]->getMotionState();

		delete m_bodies[i]; m_bodies[i] = 0;
		delete m_shapes[i]; m_shapes[i] = 0;
	}
}

void HumanCreep::startRagdolling()
{
	copyModelStateToRagdoll();
	m_RagdollOffset = m_pModelNode->_getDerivedOrientation() * m_Bones[0]->getPosition() * m_Scale;

	m_bIsRagdolling = true;
	// set bones to manually controlled and get their initial orientations too
	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		Ogre::Quaternion quat = m_Bones[i]->_getDerivedOrientation();
		m_Bones[i]->setManuallyControlled(true);
		m_Bones[i]->setInheritOrientation(false);
		m_Bones[i]->setOrientation(quat);
		m_pPhysicsWorld->addRigidBody(m_bodies[i]);
	}

	for (int i = 0; i < JOINT_COUNT; ++i)
	{
		m_pGameStatePlay->m_pPhysicsWorld->addConstraint(m_joints[i], true);
	}
	//destroy any existing physics body
	if (m_pPhysicsRigidBody != NULL)
	{
		m_pGameStatePlay->destroyPhysicsBody(m_pPhysicsRigidBody);
		m_pPhysicsRigidBody = NULL;
	}

	//We don't want the model to just fall down as if it were standing still when it died, it should appear to continue moving in the direction it was when it was killed.
	// In addition to this we have been supplied with a 'death vector' from the killing blow that will hurry the model onwards.
	m_bodies[BODYPART_HEAD]->applyCentralImpulse(btVector3(BtOgre::Convert::toBullet(getHeading() * 10 + 10 * m_DeathVector)));
	m_bodies[BODYPART_SPINE]->applyCentralImpulse(btVector3(BtOgre::Convert::toBullet(getHeading() * 20 + 10 * m_DeathVector)));
	m_bodies[BODYPART_HIPS]->applyCentralImpulse(btVector3(BtOgre::Convert::toBullet(getHeading() * 15 + 10 * m_DeathVector)));

	m_LastBloodPos = m_pModelNode->_getDerivedPosition();
}

btRigidBody* HumanCreep::localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
{
	btVector3 localInertia(0,0,0);
	shape->calculateLocalInertia(mass,localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);

	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia);
	btRigidBody* body = new btRigidBody(rbInfo);
	body->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);

	return body;
}

void HumanCreep::update(Ogre::Real timeSinceLastFrameSeconds)
{
	if (m_bIsRagdolling)
	{
		copyRagdollStateToModel();
	}
}


Here's how the physics shapes map to the model

Image

And here's the whole thing from a work-in-progress:

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.