Exemplo n.º 1
0
void PhysicalBodyConvexHull::updateBody()
{

    if (_vertices)
        _collShape.reset( new btConvexHullShape((btScalar*)_vertices, _vertexCount, sizeof(Vertex)) );//32);
    else if (_verticesvec)
        _collShape.reset( new btConvexHullShape((btScalar*)_verticesvec, _vertexCount, sizeof(glm::vec3)) );//32);

    /*
    _collShape = new btConvexHullShape;

    for (int i = 0; i < _vertexCount; i++)
    {
        btVector3 point(btVector3(_vertices[i].Position[0], _vertices[i].Position[1], _vertices[i].Position[2]));

        dynamic_cast<btConvexHullShape>(_collShape->addPoint(btVector3(0,0,0)));
    }
    */

    btVector3 inertia(0, 0, 0);
    _collShape->calculateLocalInertia(_mass, inertia);

    _motionState.reset( new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), _position)) );

    btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(_mass, _motionState.get(), _collShape.get(), inertia);
    _rigidBody.reset( new btRigidBody(rigidBodyCI) );
}
Exemplo n.º 2
0
void ObjectMotionState::updateBodyMassProperties() {
    float mass = getMass();
    btVector3 inertia(0.0f, 0.0f, 0.0f);
    _body->getCollisionShape()->calculateLocalInertia(mass, inertia);
    _body->setMassProps(mass, inertia);
    _body->updateInertiaTensor();
}
void PhysicsBodyComponent::SetMass(btScalar mass) {
    btVector3 inertia(0, 0, 0);
    if(mass != 0.0f)
        mCollisionShape->calculateLocalInertia(mass, inertia);
    mBody->setMassProps(mass, inertia);
    mMass = mass;
}
Exemplo n.º 4
0
void dgBody::ApplyImpulsesAtPoint (dgInt32 count, dgInt32 strideInBytes, const dgFloat32* const impulseArray, const dgFloat32* const pointArray)
{
	dgInt32 stride = strideInBytes / sizeof (dgFloat32);

	dgMatrix inertia (CalculateInertiaMatrix());

	dgVector impulse (m_veloc.Scale3 (m_mass.m_w));
	dgVector angularImpulse (inertia.RotateVector (m_omega));

	dgVector com (m_globalCentreOfMass);
	for (dgInt32 i = 0; i < count; i ++) {
		dgInt32 index = i * stride;
		dgVector r (pointArray[index], pointArray[index + 1], pointArray[index + 2], dgFloat32 (0.0f));
		dgVector L (impulseArray[index], impulseArray[index + 1], impulseArray[index + 2], dgFloat32 (0.0f));
		dgVector Q ((r - com) * L);

		impulse += L;
		angularImpulse += Q;
	}

	dgMatrix invInertia (CalculateInvInertiaMatrix());
	m_veloc = impulse.Scale3(m_invMass.m_w);
	m_omega = invInertia.RotateVector(angularImpulse);

	m_sleeping	= false;
	m_equilibrium = false;
	Unfreeze ();
}
Exemplo n.º 5
0
bool Player::init()
{
	camera_.init();
	input_ = InputManager::get();
	physics_world_ = PhysicsWorld::get();

	float mass = 50.0;

	btTransform t;
	t.setIdentity();
	t.setOrigin( glmVec3_btVec3(pos_) );
	motion_state_ = new btDefaultMotionState( t );

	btCapsuleShape* capsule_shape = new btCapsuleShape( RADIUS, HEIGHT );
    btVector3 inertia( 0, 0, 0 );
    capsule_shape->calculateLocalInertia( mass, inertia );
	btRigidBody::btRigidBodyConstructionInfo info( mass, motion_state_, capsule_shape, inertia );
	info.m_friction = 5.0f;

	capsule_ = new btRigidBody( info );
	capsule_->setActivationState( DISABLE_DEACTIVATION );
	capsule_->setAngularFactor( 0.0f ); // Prevent rotation
	physics_world_->world()->addRigidBody( capsule_ );

	return true;
}
Exemplo n.º 6
0
static int gCreateRigidBody (lua_State *L)
{
	int argc = lua_gettop(L);
	if (argc==5)
	{

		btTransform startTransform;
		startTransform.setIdentity();


		if (!lua_isuserdata(L,1))
		{
			std::cerr << "error: first argument to b3CreateRigidbody should be world";
			return 0;
		}
		btDiscreteDynamicsWorld* world = (btDiscreteDynamicsWorld*) lua_touserdata(L,1);
		if (world != sLuaDemo->m_dynamicsWorld)
		{
			std::cerr << "error: first argument expected to be a world";
			return 0;
		}

		if (!lua_isuserdata(L,2))
		{
			std::cerr << "error: second argument to b3CreateRigidbody should be collision shape";
			return 0;
		}

		btScalar mass = lua_tonumber(L,3);

		luaL_checktype(L,4, LUA_TTABLE);

		btVector3 pos = getLuaVectorArg(L,4);

		btQuaternion orn = getLuaQuaternionArg(L,5);

		btCollisionShape* colShape = (btCollisionShape* )lua_touserdata(L,2);
		//expect userdata = sLuaDemo->m_dynamicsWorld

		btVector3 inertia(0,0,0);
		if (mass)
		{
			colShape->calculateLocalInertia(mass,inertia);
		}


		btRigidBody* body = new btRigidBody(mass,0,colShape,inertia);
		body->getWorldTransform().setOrigin(pos);
		body->getWorldTransform().setRotation(orn);

		world->addRigidBody(body);
		
		lua_pushlightuserdata (L, body);
		return 1;
	} else
	{
		std::cerr << "Error: invalid number of arguments to createRigidBody, expected 5 (world,shape,mass,pos,orn) but got " << argc;
	}
	return 0;
}
Exemplo n.º 7
0
void ScrollView::update(float dt)
{
	if (m_isScrolling)
	{
		const auto& _containerSize = m_container->getContentSize();
		m_containerLocation.x = m_container->getPositionX();
		m_containerLocation.y = _contentSize.height - (_containerSize.height + m_container->getPositionY());
	}

	//执行惯性
	if (m_isInertia)
	{
		inertia(dt);
	}

	if (m_isScrolling)
	{
		didScroll();
		if (m_didScrollCallfunc)
			m_didScrollCallfunc(this);
	}

	if (m_isDrag)
	{
		m_dragDuration += dt;
	}
}
Exemplo n.º 8
0
const Vector &
beam2d02::getResistingForceIncInertia()
{	
    this->getResistingForce();     
    
    if (M != 0.0) {
      const Vector &end1Accel = theNodes[0]->getTrialAccel();
      const Vector &end2Accel = theNodes[1]->getTrialAccel();    
      Vector inertia(6);
      rForce(0) += M*end1Accel(0);
      rForce(1) += M*end1Accel(1);
      rForce(3) += M*end2Accel(0);
      rForce(4) += M*end2Accel(1);

      // add rayleigh damping forces
      if (alphaM != 0.0 || betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0)
	rForce += this->getRayleighDampingForces();

    } else {

      // add rayleigh damping forces
      if (betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0)
	rForce += this->getRayleighDampingForces();

    }

    return rForce;    
}
Exemplo n.º 9
0
dgMatrix dgBody::CalculateLocalInertiaMatrix () const
{
	dgMatrix inertia (dgGetIdentityMatrix());
	inertia[0][0] = m_mass.m_x;
	inertia[1][1] = m_mass.m_y;
	inertia[2][2] = m_mass.m_z;
	return inertia;
}
void PhysicsBodyComponent::onInitialize() {
    if(! mNode->hasComponent(mMeshComponentName)) {
        Logger::get().error("Node " + mNode->getName() + " has no Component named " +
                            mMeshComponentName + " which is required to create the" +
                            " PhysicsBodyComponent " + mName);
        exit(1);
    }

    auto mesh_component = mNode->findComponent<MeshComponent>(mMeshComponentName);

    BtOgre::StaticMeshToShapeConverter converter(mesh_component->getOgreEntity());
    
    // TODO: CollisionShapes should likely be stored at a central place.
    // Perhaps the PhysicsManager is a good place. It would save a lot of memory
    // for many bodies with the same CollisionShape.
    if(mCollisionShapeType == BOX) {
        Ogre::Vector3 size = mesh_component->getOgreEntity()->getBoundingBox().getSize();
        size /= 2.0;

        mCollisionShape = new btBoxShape(BtOgre::Convert::toBullet(size));
        //mCollisionShape = converter.createBox();
    }
    else if(mCollisionShapeType == CONVEX)
        mCollisionShape = converter.createConvex();
    else if(mCollisionShapeType == SPHERE) {
        mCollisionShape = new btSphereShape(mesh_component->getOgreEntity()->getBoundingRadius());
    }
    else if(mCollisionShapeType == CYLINDER) {
        Ogre::Vector3 size = mesh_component->getOgreEntity()->getBoundingBox().getSize();
        size /= 2.0;
        mCollisionShape = new btCylinderShape(BtOgre::Convert::toBullet(size));
    }
    else if(mCollisionShapeType == TRIMESH)
        mCollisionShape = converter.createTrimesh();

    mCollisionShape->setLocalScaling(BtOgre::Convert::toBullet(this->getNode()->getScale()));
    btVector3 inertia(0, 0, 0);
    //Only the rigidbody's mass doesn't equal to zero is dynamic or some odd phenomenon may appear.
    if(mMass != 0.0f)
        mCollisionShape->calculateLocalInertia(mMass, inertia);

    btDefaultMotionState* state = new btDefaultMotionState(
        btTransform(BtOgre::Convert::toBullet(getNode()->getRotation(Node::SCENE)),
        BtOgre::Convert::toBullet(getNode()->getPosition(Node::SCENE))));

    //Here's the most tricky part. You need to give it 5.0 as its temporary mass.
    //Or you will find your player character keeps falling down no matter there's a ground.
    //Its real mass will be set in OnEnable().
    mBody = new btRigidBody(5.0, state, mCollisionShape, inertia);

    std::cout << mCollisionShape->getLocalScaling().getY() << std::endl;

    // Store pointer to this PhysicsBodyComponent for later retrieval (for
    // collisions, for instance)
    mBody->setFriction(1.0);
    mBody->setUserPointer((void *)(this));
}
Exemplo n.º 11
0
 void RigidCompoundObject::addChild(RigidObject* obj, bool passOwnership) {
   SceneObject::addChild(obj,passOwnership);
   btCompoundShape *shape = static_cast<btCompoundShape*>(getCollisionObject()->getCollisionShape());
   shape->addChildShape(icl2bullet_scaled_mat(obj->getTransformation()),obj->getCollisionObject()->getCollisionShape());
   shape->recalculateLocalAabb();
   btVector3 inertia(0,0,0);
   float mass = getMass();
   shape->calculateLocalInertia(mass, inertia);
   getRigidBody()->setMassProps(mass,inertia);
 }
Exemplo n.º 12
0
 void RigidCompoundObject::removeAllChildren() {
   btCompoundShape *shape = static_cast<btCompoundShape*>(getCollisionObject()->getCollisionShape());
   while(shape->getNumChildShapes()) shape->removeChildShapeByIndex(0);
   shape->recalculateLocalAabb();
   btVector3 inertia(0,0,0);
   float mass = getMass();
   shape->calculateLocalInertia(mass, inertia);
   getRigidBody()->setMassProps(mass,inertia);
   SceneObject::removeAllChildren();
 }
Exemplo n.º 13
0
 void RigidCompoundObject::removeChild(RigidObject* obj) {
   btCompoundShape *shape = static_cast<btCompoundShape*>(getCollisionObject()->getCollisionShape());
   shape->removeChildShape(obj->getCollisionObject()->getCollisionShape());
   shape->recalculateLocalAabb();
   btVector3 inertia(0,0,0);
   float mass = getMass();
   shape->calculateLocalInertia(mass, inertia);
   getRigidBody()->setMassProps(mass,inertia);
   SceneObject::removeChild(obj);
 }
Exemplo n.º 14
0
void bmodObject::setMass(float mass) {
	g_bt_dynamicsWorld->removeRigidBody(rigidBody);

	btVector3 inertia(0, 0, 0);
	shape->calculateLocalInertia(mass, inertia);
	rigidBody->setMassProps(mass, inertia);
	rigidBody->updateInertiaTensor();
	rigidBody->activate();

	g_bt_dynamicsWorld->addRigidBody(rigidBody);
}
Exemplo n.º 15
0
btRigidBody* create_rigid_body(float mass, Node* node,
                               btCollisionShape* shape) {
    btMotionState* motion_state = new NodeMotionState(node);

    btVector3 inertia(0, 0, 0);
    shape->calculateLocalInertia(mass, inertia);

    btRigidBody::btRigidBodyConstructionInfo rbci(mass, motion_state, shape,
                                                  inertia);

    return new btRigidBody(rbci);
}
Exemplo n.º 16
0
 RigidCompoundObject::RigidCompoundObject(float x, float y, float z, float mass){
   btCompoundShape *shape = new btCompoundShape();
   btTransform T;
   T.setIdentity();
   T.setOrigin(btVector3(icl2bullet(x),icl2bullet(y),icl2bullet(z)));
   MotionState* motion = new MotionState(T, (RigidObject*)this);
   btVector3 inertia(1,1,1);
   btRigidBody::btRigidBodyConstructionInfo ci(mass,motion,shape,inertia);
   ci.m_linearSleepingThreshold *= METER_TO_BULLET_UNIT;
   ci.m_angularSleepingThreshold *= METER_TO_BULLET_UNIT;
   setPhysicalObject(new btRigidBody(ci));
 }
Exemplo n.º 17
0
btRigidBody *physics_system_t::create_rigid_cube(float radius, float mass)
{
    btCollisionShape *shape = new btBoxShape(btVector3(radius, radius, radius));
    btDefaultMotionState *motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
    btVector3 inertia(0, 0, 0);
    shape->calculateLocalInertia(mass, inertia);

    btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState, shape, inertia);
    btRigidBody *rigidBody = new btRigidBody(rigidBodyCI);

    return rigidBody;
}
	DG_INLINE void GetInertia()
	{
            dgFloat32 mass = m_body->GetMass().m_w;
		    dgAssert(mass < dgFloat32(1.0e10f));
		    dgMatrix inertia(m_body->CalculateInertiaMatrix());
		    for (dgInt32 i = 0; i < 3; i++) {
			    m_bodyMass[i][i] = mass;
			    for (dgInt32 j = 0; j < 3; j++) {
				    m_bodyMass[i + 3][j + 3] = inertia[i][j];
			    }
		    }
		}
Exemplo n.º 19
0
mat33 randomInertiaMatrix() {
    // generate random valid inertia matrix by first getting valid components
    // along major axes and then rotating by random amount
    vec3 principal = randomInertiaPrincipal();
    mat33 rot(transformX(randomFloat(-BT_ID_PI, BT_ID_PI)) * transformY(randomFloat(-BT_ID_PI, BT_ID_PI)) *
              transformZ(randomFloat(-BT_ID_PI, BT_ID_PI)));
    mat33 inertia;
    inertia(0, 0) = principal(0);
    inertia(0, 1) = 0;
    inertia(0, 2) = 0;
    inertia(1, 0) = 0;
    inertia(1, 1) = principal(1);
    inertia(1, 2) = 0;
    inertia(2, 0) = 0;
    inertia(2, 1) = 0;
    inertia(2, 2) = principal(2);
    return rot * inertia * rot.transpose();
}
Exemplo n.º 20
0
btRigidBody* BasicDemo::localCreateRigidBody(btScalar mass,const btTransform& startTrans,btCollisionShape* colShape)
{
btVector3 inertia(0,0,0);
if (mass)
	colShape->calculateLocalInertia(mass,inertia);
	btRigidBody::btRigidBodyConstructionInfo rbci(mass,0,colShape,inertia);
	rbci.m_startWorldTransform = startTrans;

btRigidBody* body = new btRigidBody(rbci);
	m_dynamicsWorld->addRigidBody(body);
return body;

}
MT_Vector3 KX_BulletPhysicsController::GetLocalInertia()
{
	MT_Vector3 inertia(0.f, 0.f, 0.f);
	btVector3 inv_inertia;
	if (GetRigidBody()) {
		inv_inertia = GetRigidBody()->getInvInertiaDiagLocal();
		if (!btFuzzyZero(inv_inertia.getX()) &&
		        !btFuzzyZero(inv_inertia.getY()) &&
		        !btFuzzyZero(inv_inertia.getZ()))
			inertia = MT_Vector3(1.f/inv_inertia.getX(), 1.f/inv_inertia.getY(), 1.f/inv_inertia.getZ());
	}
	return inertia;
}
Exemplo n.º 22
0
void btBone::init(btScalar length,
                  btScalar radius,
                  btScalar radiusArticulation,
                  btScalar density,
                  const btTransform &transform) {

    btScalar friction = 0.7;

    // shape
    this->shape = new btCompoundShape(true); 

    // Adding the sphere to the shape !
    sphereShape = new btSphereShape(radiusArticulation);
    btTransform articulationTransform;
    articulationTransform.setIdentity();
    articulationTransform.setOrigin(btVector3(0,length*0.5 + radiusArticulation, 0));
    shape->addChildShape(articulationTransform, sphereShape);

    // adding the cylinder to the shape
    cylinderShape = new btCylinderShape(btVector3(radius,length*0.5,radius));
    btTransform cylinderTransform; cylinderTransform.setIdentity();
    shape->addChildShape(cylinderTransform, cylinderShape);

    // body
    btScalar vol = SIMD_PI*radius*radius*length + 4/3. * SIMD_PI * radiusArticulation * radiusArticulation * radiusArticulation;
    btScalar mass = vol*density;
    btVector3 localInertia(0,0,0);
    shape->calculateLocalInertia(mass,localInertia);

    btTransform principal;
    principal.setIdentity();
    btVector3 inertia(0,0,0);

    // Masse de l'os, masse de la fixation
    //tScalar massBone = SIMD_PI*radius*radius*length*density;
    //btScalar massSphere =  4/3. * SIMD_PI * radiusArticulation * radiusArticulation * radiusArticulation * density;
    //btScalar childMasses[2] = {massSphere,massBone};
    // TODO Use this information to shift object inside the compound
    // Set the shift in the rigid objets
    // And set the shift in all childs fixations
    // And parent constraint of bone
    // ARG, lot of todo to get the center of gravity work properly
    //shape->calculatePrincipalAxisTransform(childMasses, principal, inertia);

    // motion state

    motionState = new btDefaultMotionState(transform);

    this->rigidBody = new btRigidBody(mass,motionState,shape,localInertia);
    this->rigidBody->setFriction(friction);
}
Exemplo n.º 23
0
bmodObject::bmodObject(const char * model, float mass) {
	if(!getModelShape(model, &shape)) {
		MF_Log("BAD model! (%s)", model);
		shape = new btEmptyShape();
	}

	btVector3 inertia(0, 0, 0);
	shape->calculateLocalInertia(mass, inertia);
	bmodMotionState* objectMotionState = new bmodMotionState(this);
	btRigidBody::btRigidBodyConstructionInfo objectRigidBodyCI(mass, objectMotionState, shape, inertia);
	rigidBody = new btRigidBody(objectRigidBodyCI);

	g_bt_dynamicsWorld->addRigidBody(rigidBody);
}
	static void AddFracturedEntity(DemoEntityManager* const scene, DemoMesh* const visualMesh, NewtonCollision* const collision, const FractureEffect& fractureEffect, const dVector& location)
	{
		dQuaternion rotation;
		SimpleFracturedEffectEntity* const entity = new SimpleFracturedEffectEntity(visualMesh, fractureEffect);
		entity->SetMatrix(*scene, rotation, location);
		entity->InterpolateMatrix(*scene, 1.0f);
		scene->Append(entity);

		dVector origin(0.0f);
		dVector inertia(0.0f);
		NewtonConvexCollisionCalculateInertialMatrix(collision, &inertia[0], &origin[0]);

		dFloat mass = 10.0f;
		int materialId = 0;

		//create the rigid body
		dMatrix matrix(dGetIdentityMatrix());
		matrix.m_posit = location;

		NewtonWorld* const world = scene->GetNewton();
		NewtonBody* const rigidBody = NewtonCreateDynamicBody(world, collision, &matrix[0][0]);

		entity->m_myBody = rigidBody;
		entity->m_myMassInverse = 1.0f / mass;

		// set the correct center of gravity for this body
		//NewtonBodySetCentreOfMass (rigidBody, &origin[0]);

		// set the mass matrix
		NewtonBodySetMassProperties(rigidBody, mass, collision);

		// save the pointer to the graphic object with the body.
		NewtonBodySetUserData(rigidBody, entity);

		// assign the wood id
		NewtonBodySetMaterialGroupID(rigidBody, materialId);

		//  set continuous collision mode
		//	NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode);

		// set a destructor for this rigid body
		NewtonBodySetDestructorCallback(rigidBody, PhysicsBodyDestructor);

		// set the transform call back function
		NewtonBodySetTransformCallback(rigidBody, DemoEntity::TransformCallback);

		// set the force and torque call back function
		NewtonBodySetForceAndTorqueCallback(rigidBody, PhysicsApplyGravityForce);
	}
Exemplo n.º 25
0
World::World(const char* path_to_script) {
	script = new Script(path_to_script);
	btTriangleIndexVertexArray* tiva;
	mesh = new Mesh(script->GetString("mesh"), tiva);
	texture = new Texture(script->GetString("texture"));

	//btCollisionShape* collisionShape = new btBvhTriangleMeshShape(tiva, false);
	btCollisionShape* collisionShape = new btStaticPlaneShape(btVector3(0, 0, 0), 1);
	btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
	btScalar mass = 0;
	btVector3 inertia(0, 0, 0);
	collisionShape->calculateLocalInertia(mass, inertia);
	btRigidBody::btRigidBodyConstructionInfo bodyCI(mass, motionState, collisionShape, inertia);
	body = new btRigidBody(bodyCI);
}
Exemplo n.º 26
0
void dgBody::ApplyImpulsePair (const dgVector& linearImpulseIn, const dgVector& angularImpulseIn)
{
	dgMatrix inertia (CalculateInertiaMatrix());
	dgMatrix invInertia (CalculateInvInertiaMatrix());

	dgVector linearImpulse (m_veloc.Scale3 (m_mass.m_w) + linearImpulseIn);
	dgVector angularImpulse (inertia.RotateVector (m_omega) + angularImpulseIn);

	m_veloc = linearImpulse.Scale3(m_invMass.m_w);
	m_omega = invInertia.RotateVector(angularImpulse);

	m_sleeping	= false;
	m_equilibrium = false;
	Unfreeze ();
}
Exemplo n.º 27
0
    RigidCylinderObject::RigidCylinderObject(float x, float y, float z, float r, float h, float mass){
      so = addCylinder(0, 0, 0, r, r, h, 16);

      btCylinderShape *shape = new btCylinderShapeZ(btVector3(icl2bullet(r * 0.5),icl2bullet(r * 0.5),icl2bullet(h * 0.5)));
      btTransform T;
      T.setIdentity();
      T.setOrigin(btVector3(icl2bullet(x),icl2bullet(y),icl2bullet(z)));
      MotionState* motion = new MotionState(T, (RigidObject*)this);
      btVector3 inertia(0,0,0);
      shape->calculateLocalInertia(mass, inertia);
      btRigidBody::btRigidBodyConstructionInfo ci(mass,motion,shape,inertia);
      ci.m_linearSleepingThreshold *= METER_TO_BULLET_UNIT;
      ci.m_angularSleepingThreshold *= METER_TO_BULLET_UNIT;
      setPhysicalObject(new btRigidBody(ci));
    }
Exemplo n.º 28
0
void MyCharacterController::updateShapeIfNecessary() {
    if (_pendingFlags & PENDING_FLAG_UPDATE_SHAPE) {
        _pendingFlags &= ~ PENDING_FLAG_UPDATE_SHAPE;

        // compute new dimensions from avatar's bounding box
        float x = _boxScale.x;
        float z = _boxScale.z;
        _radius = 0.5f * sqrtf(0.5f * (x * x + z * z));
        _halfHeight = 0.5f * _boxScale.y - _radius;
        float MIN_HALF_HEIGHT = 0.1f;
        if (_halfHeight < MIN_HALF_HEIGHT) {
            _halfHeight = MIN_HALF_HEIGHT;
        }
        // NOTE: _shapeLocalOffset is already computed

        if (_radius > 0.0f) {
            // HACK: use some simple mass property defaults for now
            float mass = 100.0f;
            btVector3 inertia(30.0f, 8.0f, 30.0f);

            // create RigidBody if it doesn't exist
            if (!_rigidBody) {
                btCollisionShape* shape = new btCapsuleShape(_radius, 2.0f * _halfHeight);
                _rigidBody = new btRigidBody(mass, nullptr, shape, inertia);
            } else {
                btCollisionShape* shape = _rigidBody->getCollisionShape();
                if (shape) {
                    delete shape;
                }
                shape = new btCapsuleShape(_radius, 2.0f * _halfHeight);
                _rigidBody->setCollisionShape(shape);
            }

            _rigidBody->setSleepingThresholds(0.0f, 0.0f);
            _rigidBody->setAngularFactor(0.0f);
            _rigidBody->setWorldTransform(btTransform(glmToBullet(_avatar->getOrientation()),
                                                      glmToBullet(_avatar->getPosition())));
            if (_isHovering) {
                _rigidBody->setGravity(btVector3(0.0f, 0.0f, 0.0f));
            } else {
                _rigidBody->setGravity(DEFAULT_GRAVITY * _currentUp);
            }
            //_rigidBody->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
        } else {
            // TODO: handle this failure case
        }
    }
}
void DynamicCharacterController::updateShapeIfNecessary() {
    if (_pendingFlags & PENDING_FLAG_UPDATE_SHAPE) {
        // make sure there is NO pending removal from simulation at this point
        // (don't want to delete _rigidBody out from under the simulation)
        assert(!(_pendingFlags & PENDING_FLAG_REMOVE_FROM_SIMULATION));
        _pendingFlags &= ~ PENDING_FLAG_UPDATE_SHAPE;
        // delete shape and RigidBody
        delete _rigidBody;
        _rigidBody = nullptr;
        delete _shape;
        _shape = nullptr;

        // compute new dimensions from avatar's bounding box
        float x = _boxScale.x;
        float z = _boxScale.z;
        _radius = 0.5f * sqrtf(0.5f * (x * x + z * z));
        _halfHeight = 0.5f * _boxScale.y - _radius;
        float MIN_HALF_HEIGHT = 0.1f;
        if (_halfHeight < MIN_HALF_HEIGHT) {
            _halfHeight = MIN_HALF_HEIGHT;
        }
        // NOTE: _shapeLocalOffset is already computed

        if (_radius > 0.0f) {
            // create new shape
            _shape = new btCapsuleShape(_radius, 2.0f * _halfHeight);

            // HACK: use some simple mass property defaults for now
            float mass = 100.0f;
            btVector3 inertia(30.0f, 8.0f, 30.0f);

            // create new body
            _rigidBody = new btRigidBody(mass, nullptr, _shape, inertia);
            _rigidBody->setSleepingThresholds(0.0f, 0.0f);
            _rigidBody->setAngularFactor(0.0f);
            _rigidBody->setWorldTransform(btTransform(glmToBullet(_avatarData->getOrientation()),
                                                      glmToBullet(_avatarData->getPosition())));
            if (_isHovering) {
                _rigidBody->setGravity(btVector3(0.0f, 0.0f, 0.0f));
            } else {
                _rigidBody->setGravity(DEFAULT_GRAVITY * _currentUp);
            }
            //_rigidBody->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
        } else {
            // TODO: handle this failure case
        }
    }
}
Exemplo n.º 30
0
btRigidBody * createBTBox( osg::MatrixTransform * box,
                          osg::Vec3 center )
{
    btCollisionShape * collision = osgbCollision::btBoxCollisionShapeFromOSG( box );

    osgbDynamics::MotionState * motion = new osgbDynamics::MotionState();
    motion->setTransform( box );
    motion->setParentTransform( osg::Matrix::translate( center ) );

    btScalar mass( 0.0 );
    btVector3 inertia( 0, 0, 0 );
    btRigidBody::btRigidBodyConstructionInfo rb( mass, motion, collision, inertia );
    btRigidBody * body = new btRigidBody( rb );

    return( body );
}