Пример #1
0
int main(){
	// Build the broadphase
	btBroadphaseInterface* broadphase = new btDbvtBroadphase();

	// Set up the collision configuration and dispatcher
	btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
	btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);

	// The actual physics solver
	btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver();

	// The world
	btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
	dynamicsWorld->setGravity(btVector3(0, -9.8, 0));

	// Do everything else here
	btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);
	btCollisionShape* fallShape = new btSphereShape(1);

	btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0,-1,0)));

	btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0,0,0));
	btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);

	dynamicsWorld->addRigidBody(groundRigidBody);

	btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0,50,0)));
	btScalar mass = 1;
	btVector3 fallInertia(0,0,0);
	fallShape->calculateLocalInertia(mass, fallInertia);

	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
	btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
	dynamicsWorld->addRigidBody(fallRigidBody);


	for(int i = 0; i < 10; i++){
		dynamicsWorld->stepSimulation(1.0f/60.0f, 10);

		btTransform trans;
		fallRigidBody->getMotionState()->getWorldTransform(trans);
		std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl;
	}






	// Clean up behind ourselves
	delete dynamicsWorld;
	delete solver;
	delete dispatcher;
	delete collisionConfiguration;
	delete broadphase;

	std::cout << "Pewty pewt" << std::endl;

	return 0;
}
Пример #2
0
void PhysicObject::createPhysObject() {
	btDefaultMotionState* fallMotionState =
			new btDefaultMotionState(btTransform(btQuaternion((initialOrientation.y*GRAD_TO_RAD_COEF), (initialOrientation.x*GRAD_TO_RAD_COEF), (initialOrientation.z*GRAD_TO_RAD_COEF)),btVector3(initialPosition.x, initialPosition.y, initialPosition.z)));
	btVector3 fallInertia(0,0,0);
	collisionShape->getCollisionShape()->calculateLocalInertia(mass, fallInertia);
	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, collisionShape->getCollisionShape(), fallInertia);
	rigidBody = new btRigidBody(fallRigidBodyCI);
	setAngularFactor(angularFactor);
	setLinearFactor(linearFactor);
	setLinearVelocity(linearVelocity);
	rigidBody->setFriction(friction);
	rigidBody->setRestitution(restitution);
	setAngularVelocity(angularVelocity);
	rigidBody->setDamping(linearDumping, angularDumping);
	if (_isTrigger) {
		rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
	} else
	if (_isKinematic) {
		rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
	}

	rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
	rigidBody->setUserPointer(this);

	if (!isEnableDeactivation())
		rigidBody->setActivationState(DISABLE_DEACTIVATION);
	Game::instance->dynamicsWorld->addRigidBody(rigidBody);
}
Пример #3
0
	bool PhysicsSystem::AddRigidBody(CollisionBody* collision_body) {
		eid entity_id = collision_body->entity_id;
		
		RemoveRigidBody(entity_id);

		if (!collision_body->shape) {
			return false;
		}

		btVector3 fallInertia(0, 0, 0);
		if (collision_body->mass > 0.0) {
			if (collision_body->shape) {
				collision_body->shape->calculateLocalInertia(collision_body->mass, fallInertia);
			}
		}

		btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(collision_body->mass,
			&collision_body->motion_state, collision_body->shape.get(), fallInertia);
		auto body = new btRigidBody(fallRigidBodyCI);

		if (!body) {
			return false;
		}

		this->bodies[entity_id] = body;

		body->setUserPointer(collision_body);
		return true;
	}
Пример #4
0
void Humanoid::InstantiateAtom()
{
	//a single cuboid girder to cover this cell
	Ogre::SceneManager& sceneManager = GetSceneManager();
	m_pAtomEntity = sceneManager.createEntity("human_" + num2string(m_AtomID), "ninja.mesh");
	m_pAtomEntitySceneNode->attachObject(m_pAtomEntity);
	m_pAtomEntitySceneNode->scale(0.004f, 0.004f, 0.004f);
	m_pAtomEntitySceneNode->setPosition(0, -0.4f, 0);
	
	//create physics collider
	btVector3 halfExtents = btVector3(0.15f, 0.4f, 0.1f);
	m_pCollisionShape = new btBoxShape(halfExtents);
	btDefaultMotionState* startMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), OGRE2BT(m_pAtomEntitySceneNode->_getDerivedPosition())));
	btScalar mass = 100.f;
	btVector3 fallInertia(0,0,0);
	m_pCollisionShape->calculateLocalInertia(mass,fallInertia);
	btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, startMotionState, m_pCollisionShape, fallInertia);
	m_pRigidBody = new btRigidBody(rigidBodyCI);
	m_pRigidBody->setUserPointer(this);
	m_pRigidBody->setAngularFactor(0);
	
	InitCollisionShapeDebugDraw(Ogre::ColourValue::Green);

	//todo: is this working?
	//m_pRigidBody->setCollisionFlags(m_pRigidBody->CF_NO_CONTACT_RESPONSE);

	//add new rigid body to world
	btDiscreteDynamicsWorld& dynamicsWorld = GetDynamicsWorld();
	dynamicsWorld.addRigidBody(m_pRigidBody, COLLISION_MOB, COLLISION_STRUCTURE|COLLISION_OBJ|COLLISION_MOB);
	
	Mob::InstantiateAtom();
}
Пример #5
0
void World::addObject(){
  btCollisionShape* fallShape = new btBoxShape(btVector3(5,5,5));

  btQuaternion quat(0,0,0,1);
  quat.setEuler(0,0,0);

  btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(quat,btVector3(0,50.0f,0)));
  btScalar mass = 1.0f;
  btVector3 fallInertia(0,0,0);
  fallShape->calculateLocalInertia(mass,fallInertia);

  btRigidBody::btRigidBodyConstructionInfo info(mass,fallMotionState,fallShape,fallInertia);
  info.m_restitution = 0.5f;
  info.m_friction = 0.5f;

  std::shared_ptr<btRigidBody> body(new btRigidBody(info));
  dynamics_world_->addRigidBody(body.get());
  body->setUserPointer(new Object);
  objects_.push_back(body);

  // fall_rigid_body_->applyTorqueImpulse(btVector3(1.0f,1.0f,0)); //Just to try and get it to rotate

  // btTransform tr;
  // tr.setIdentity();
  // tr.setOrigin(btVector3(0,100,0));
  // 
  // btQuaternion quat;
  // quat.setEuler(0,1.57,1.57);
  // tr.setRotation(quat);
  // 
  // fall_rigid_body_->setCenterOfMassTransform(tr);
}
Пример #6
0
   void BulletPhysicsObject::initialize()
   {
      _shape = new btBoxShape(btVector3(mScale.x / 2.0f, mScale.y / 2.0f, mScale.z / 2.0f));

      if ( mStatic )
      {
         btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(0, NULL, _shape);
         _rigidBody = new btRigidBody(fallRigidBodyCI);
         _rigidBody->setUserIndex(1);
         _rigidBody->setUserPointer(this);
         _rigidBody->setAngularFactor(btVector3(0,0,0));
         _rigidBody->setWorldTransform(btTransform(btQuaternion(0, 0, 0, 1), btVector3(mPosition.x, mPosition.y, mPosition.z)));
      } else {
         _motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(mPosition.x, mPosition.y, mPosition.z)));
         btScalar mass = 1.0f;
         btVector3 fallInertia(0, 0, 0);
         _shape->calculateLocalInertia(mass, fallInertia);

         btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, _motionState, _shape, fallInertia);
         _rigidBody = new btRigidBody(fallRigidBodyCI);
         _rigidBody->setUserIndex(1);
         _rigidBody->setUserPointer(this);
         //_rigidBody->setAngularFactor(btVector3(0,1,0));
      }

      //_rigidBody->setCollisionFlags( btCollisionObject::CF_KINEMATIC_OBJECT );
      //_rigidBody->setActivationState( DISABLE_DEACTIVATION );
      initialized = true;
   }
Пример #7
0
void PhysicObject::refreshInertia() {
	if (collisionShape == NULL || rigidBody == NULL)
		return;
	btVector3 fallInertia(0,0,0);
	collisionShape->getCollisionShape()->calculateLocalInertia(mass, fallInertia);
	rigidBody->setMassProps(mass, fallInertia);
}
Пример #8
0
void CollisionBody::CreateRigidBody(glm::vec3 passPos, float fXdis, float fYdis, float fZdis)
{

    CollisionShape = new btBoxShape(btVector3(fXdis, fYdis, fZdis));
    MotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(passPos.x,passPos.y,passPos.z)));
    btScalar mass = 0;
    btVector3 fallInertia(1,1,1);
    CollisionShape->calculateLocalInertia(mass,fallInertia);
    btRigidBody::btRigidBodyConstructionInfo ShapeRigidBodyCI(mass,MotionState,CollisionShape,fallInertia);
    ThisRigidBody = new btRigidBody(ShapeRigidBodyCI);
    CollisionWorldSingleton::Instance()->AddRigidBody(ThisRigidBody);

}
Пример #9
0
BulletObject::BulletObject(btScalar mass, btCollisionShape *cs, const btTransform &initTrans, bool isKinematic_) : isKinematic(isKinematic_) {
    motionState.reset(new MotionState(*this, initTrans));
    collisionShape.reset(cs);

    btVector3 fallInertia(0, 0, 0);
    if (!isKinematic)
        collisionShape->calculateLocalInertia(mass, fallInertia);
    CI ci(mass, cs, fallInertia);
    ci.m_motionState = motionState.get();

    rigidBody.reset(new btRigidBody(ci));
    rigidBody->setActivationState(DISABLE_DEACTIVATION);
}
Пример #10
0
void AppClass::InitVariables(void)
{
	//Set the camera at a position other than the default
	m_pCameraMngr->SetPositionTargetAndView(vector3(0.0f, 10.0f, 25.0f), vector3(0.0f, 0.0f, 0.0f), REAXISY);

	std::vector<vector3> vVectors;
	m_nCubes = 100;
	for (int n = 0; n < m_nCubes; n++)
	{
		vVectors.push_back(vector3(0.0f, 2 * n + 2, -0.1 * n));
		m_pMeshMngr->LoadModel("Sorted\\Polycube.obj", "Cube", false, glm::translate(matrix4(1.0f), vVectors[n]));
	}

	//Setup world, Broadphase, collision configuration, solver
	broadphase = new btDbvtBroadphase();
	collisionConfiguration = new btDefaultCollisionConfiguration();
	dispatcher = new btCollisionDispatcher(collisionConfiguration);
	solver = new btSequentialImpulseConstraintSolver;
	dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
	dynamicsWorld->setGravity(btVector3(0, -10, 0));

	//Ground
	groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);
	groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
	btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
	groundRigidBody = new btRigidBody(groundRigidBodyCI);
	dynamicsWorld->addRigidBody(groundRigidBody);

	//Cube
	fallShape = new btBoxShape(btVector3(0.5, 0.5, 0.5));
	btScalar mass = 1;
	btVector3 fallInertia(0, 0, 0);
	fallShape->calculateLocalInertia(mass, fallInertia);
	for (int n = 0; n < m_nCubes; n++)
	{
		fallMotionState.push_back(
			new btDefaultMotionState(
				btTransform(
					btQuaternion(0, 0, 0, 1),
					btVector3(
						vVectors[n].x,
						vVectors[n].y,
						vVectors[n].z)))
			);
		btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState[n], fallShape, fallInertia);
		fallRigidBody.push_back(new btRigidBody(fallRigidBodyCI));
		dynamicsWorld->addRigidBody(fallRigidBody[n]);
	}
}
Пример #11
0
void MPhysicsWorld::addBody(Primitiva* cub)
{
    //dynamic body
    btCollisionShape* fallShape = new btBoxShape(btVector3(1,1,1));

    //btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(3,0,-10)));
    MMotionState* fallMotionState = new MMotionState(cub);

    btScalar mass = 1;
    btVector3 fallInertia(0,0,0);
    fallShape->calculateLocalInertia(mass,fallInertia);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
    fallRigidBody = new btRigidBody(fallRigidBodyCI);
    m_pDynamicsWorld->addRigidBody(fallRigidBody);

};
Пример #12
0
btRigidBody* makeCube(btDiscreteDynamicsWorld* dynamicsWorld, btScalar mass, btScalar d, btVector3 pos, btScalar coe = COE){
    
    btCollisionShape* cubeShape = new btBoxShape(btVector3(d, d, d)); // create a r radius sphere shape
    btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), pos)); // position it at right place, no rotation
    btVector3 fallInertia(0, 0, 0);
    cubeShape->calculateLocalInertia(mass, fallInertia); // calculate the inertia
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, cubeShape, fallInertia); // rigid body params
    btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI); // create the rigid body
    
    fallRigidBody->setRestitution(coe);
    fallRigidBody->setLinearVelocity(btVector3(50, 0, 0));
    dynamicsWorld->addRigidBody(fallRigidBody);
    
    return fallRigidBody;

}
Пример #13
0
Simulation::Simulation() {
	random_device rd;
	mt19937 gen(rd());
	normal_distribution<> d(0, 1);
	colWas = false;
	minY = -999;
	center = glm::vec3(0, 0, 0);

	broadphase = new btDbvtBroadphase();
	collisionConfiguration = new btDefaultCollisionConfiguration();
	dispatcher = new btCollisionDispatcher(collisionConfiguration);
	solver = new btSequentialImpulseConstraintSolver;

	dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
	dynamicsWorld->setGravity(btVector3(0, -10, 0));

	groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
	//fallShape = new btSphereShape(1);

	fallShape = 0;
	getMesh();

	groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
	btRigidBody::btRigidBodyConstructionInfo
		groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
	//groundRigidBodyCI.m_restitution = 0;
	groundRigidBodyCI.m_friction = 3;
	groundRigidBodyCI.m_restitution = 0.8;
	groundRigidBodyCI.m_rollingFriction = ROLFR;
	groundRigidBody = new btRigidBody(groundRigidBodyCI);
	dynamicsWorld->addRigidBody(groundRigidBody);

	btScalar mass = 1;
	btVector3 fallInertia(0, 0, 0);
	fallShape->calculateLocalInertia(mass, fallInertia);
	fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), /*btVector3(N*0.5, N*0.5, (double)(N*0.5))*/btVector3(0,0,0)));

	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
	//fallRigidBodyCI.m_restitution = 0;
	fallRigidBodyCI.m_friction = 3;
	fallRigidBodyCI.m_restitution = 0.8;
	fallRigidBodyCI.m_rollingFriction = ROLFR;
	fallRigidBody = new btRigidBody(fallRigidBodyCI);
	fallRigidBody->setActivationState(DISABLE_DEACTIVATION);
	dynamicsWorld->addRigidBody(fallRigidBody);
	time = 0;
}
Пример #14
0
void GOBox::createRigidBody()//std::map< btCollisionObject*, GameObj*> * map)
{
	btCollisionShape* fallShape = new btBoxShape(btVector3(this->getWidth()/2, this->getHeight()/2, this->getDepth()/2));
	btDefaultMotionState* fallMotionState =
		new btDefaultMotionState(btTransform(btQuaternion(this->getqX(), this->getqY(), this->getqZ(), this->getqW()), btVector3(this->getX(), this->getY(), this->getZ())));
	btScalar mass = this->getMass();
	btVector3 fallInertia(0, 0, 0);
	fallShape->calculateLocalInertia(mass, fallInertia);
	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
	fallRigidBodyCI.m_friction = 0.0f;
	fallRigidBodyCI.m_restitution = 0.0f;
	fallRigidBodyCI.m_linearDamping = 0.2f;
	fallRigidBodyCI.m_angularDamping = 0.1f;
	btRigidBody* rb = new btRigidBody(fallRigidBodyCI);
	//map->insert(std::pair<btCollisionObject*, GameObj*> (rb, this));
	rb->setUserPointer(this);
	this->setRigidBody(rb);
}
Пример #15
0
btRigidBody* BulletWrapper::utilAddFingerSphere(const EigenTypes::Vector3f& position, float radius, bool visible)
{
  m_BodyDatas.resize(m_BodyDatas.size() + 1);
  BodyData& bodyData = m_BodyDatas.back();

  bodyData.m_SharedShape.reset(new btSphereShape(radius));

  btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(position.x(), position.y(), position.z())));
  btScalar mass = 1;
  btVector3 fallInertia(0, 0, 0);
  bodyData.m_SharedShape->calculateLocalInertia(mass, fallInertia);
  btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, bodyData.m_SharedShape.get(), fallInertia);
  bodyData.m_ShapeType = SHAPE_TYPE_SPHERE;
  bodyData.m_Visible = visible;
  bodyData.m_Body = new btRigidBody(fallRigidBodyCI);
  bodyData.m_Body->setActivationState(DISABLE_DEACTIVATION);
  m_DynamicsWorld->addRigidBody(bodyData.m_Body, COLLISION_GROUP_HAND, COLLISION_GROUP_DYNAMIC);
  return bodyData.m_Body;
}
Пример #16
0
void BulletWrapper::utilAddCube(const EigenTypes::Vector3f& position, const EigenTypes::Vector3f& halfExtents)
{
  m_BodyDatas.resize(m_BodyDatas.size() + 1);
  BodyData& bodyData = m_BodyDatas.back();

  bodyData.m_SharedShape.reset(new btBoxShape(ToBullet(halfExtents)));

  btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(position.x(), position.y(), position.z())));

  btScalar mass = 1;
  btVector3 fallInertia(0, 0, 0);
  bodyData.m_SharedShape->calculateLocalInertia(mass, fallInertia);
  btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, bodyData.m_SharedShape.get(), fallInertia);
  bodyData.m_Body = new btRigidBody(fallRigidBodyCI);
  bodyData.m_ShapeType = SHAPE_TYPE_BOX;
  bodyData.m_Visible = true;
  bodyData.m_Body->setActivationState(DISABLE_DEACTIVATION);
  m_DynamicsWorld->addRigidBody(bodyData.m_Body, COLLISION_GROUP_DYNAMIC, COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_HAND);
}
Пример #17
0
void btSphere::init(btScalar radius, btScalar density, const btTransform &transform)
{
    this->density = density;
//    this->size = size;
//    this->initialPosition = position;
//    this->initiaEulerlRotation = EulerRotation;

    // shape
    this->shape = new btSphereShape(radius);

    // rotation with euler method :) (warning order Z-Y-X)
    this->motionState = new btDefaultMotionState(transform);

    // body
    btScalar mass = computeMass();
    btVector3 fallInertia(0,0,0);
    this->shape->calculateLocalInertia(mass,fallInertia);
    this->rigidBody = new btRigidBody(mass,this->motionState,this->shape,fallInertia);

    origin = new RigidBodyOrigin(RigidBodyOrigin::BASIC_SHAPE,(QObject *)this);
    rigidBody->setUserPointer(origin);
}
Пример #18
0
void MainCharacter::setup()
{
    physicsHandler = PhysicsHandler::getInstance();
    //	aLoader.load(ofToDataPath("3DAssets/vrouwAnimeTest2.dae"));
    aLoader.load(ofToDataPath("3DAssets/girlStop.dae"));
    aLoader.addAnimation(ofToDataPath("3DAssets/girlWalk.dae"));

    charMesh  = *aLoader.boneMeshes[0];
    charMesh.setPos(0.0,0.001,0.0);
    charMesh.material.loadDiffuse("3DAssets/vrouwFinal.png");
    walkDirRot =0;
    rotSpeed =2;
    //walkDir.set(-0.085,0,0.996);
    //charPos.set(98.99,77.23,189.178);

    walkDir.set(-0.085,0,0.996);
    charPos.set(0.00,0.00,0.00);

    walkspeed =15;
    isMoving =false;
    lastDown =-1;
    rightIsDown =false;
    leftIsDown =false;
    walkSlerp=0;

    btScalar mass = 1;
    btVector3 fallInertia(0.0,0.0,0.0);
    capsuleShape = new btCapsuleShape(1,3.6);
    capsuleMotionState =new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0.2,1.8+2+100,0.2)));
    capsuleShape->calculateLocalInertia(mass,fallInertia);
    btRigidBody::btRigidBodyConstructionInfo capsuleRigidBodyCI(mass,capsuleMotionState,capsuleShape,fallInertia);
    capsuleRigidBody = new btRigidBody(capsuleRigidBodyCI);
    capsuleRigidBody->setSleepingThresholds(0.0, 0.0);
    capsuleRigidBody->setAngularFactor(0.0);

    physicsHandler->capsuleRigidBody  =capsuleRigidBody;
    physicsHandler->dynamicsWorld->addRigidBody(capsuleRigidBody);

}
Пример #19
0
void EntityPhysic::setPhysic()
{
	//shape=setShape();
	if(shape!=NULL)
	{
		//m_collisionShapes.push_back(fallShape2);

		// LOGI("AEA::setPhysic1:,%f,%f",pos->x(),pos->y());

		//rotate=btVector3(0, 1.5f, 0);

		btTransform startTransform;
		startTransform.setIdentity();
		startTransform.setFromOpenGLMatrix(matrix);
		//startTransform.setOrigin(*pos);
		//startTransform.setRotation(btQuaternion(0,rotate.y(),0,1));
		//LOGI("AEA::setPhysic2");
		btDefaultMotionState* fallMotionState =
				new btDefaultMotionState(startTransform);
		//LOGI("AEA::setPhysic3");
		//restitution=1.5f;
		//mass = 20.0f;
		btVector3 fallInertia(0,0,0);
		shape->calculateLocalInertia(mass,fallInertia);
		btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,shape,fallInertia);
		body = new btRigidBody(fallRigidBodyCI);
		//LOGI("AEA::setPhysic3.5");
		//move_RigidBodys.push_back(fallRigidBody);
		body->setRestitution(restitution);
		const btVector3 v(0,0,0);
		body->setLinearVelocity(v);//*velocity
		//body->setAngularVelocity(btVector3(0,15,10));
		LOGI("AEA::setPhysic4");
		physic->dynamicsWorld->addRigidBody(body);
	}
}
Пример #20
0
void physics_system_t::init()
{
    // Build the broadphase
    broadphase = new btDbvtBroadphase();
 
    // Set up the collision configuration and dispatcher
    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);
 
    // The actual physics solver
    solver = new btSequentialImpulseConstraintSolver;
 
    // The world.
    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0, -10, 0));

    groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
    fallShape = new btSphereShape(1);

    groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
    btRigidBody::btRigidBodyConstructionInfo
    groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
    groundRigidBody = new btRigidBody(groundRigidBodyCI);

    //dynamicsWorld->addRigidBody(groundRigidBody);

    fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0)));

    btScalar mass = 1;
    btVector3 fallInertia(0, 0, 0);
    fallShape->calculateLocalInertia(mass,fallInertia);

    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
    fallRigidBody = new btRigidBody(fallRigidBodyCI);
    //dynamicsWorld->addRigidBody(fallRigidBody);
}
Пример #21
0
	std::set<eid> PhysicsSystem::Update(const double delta, const GameState& state) {
		std::set<eid> updated_entities;
		ProcessCommandQueue();
		EventQueue<MouseBtnEvent>::ProcessEventQueue();
		EventQueue<EntityCreated>::ProcessEventQueue();
		EventQueue<EntityDestroyed>::ProcessEventQueue();

		for (auto itr = CollisionBodyMap::Begin(); itr != CollisionBodyMap::End(); ++itr) {
			eid entity_id = itr->first;
			CollisionBody* collidable = itr->second;
			glm::vec3 position(0.0);
			if (state.positions.find(entity_id) != state.positions.end()) {
				auto pos = state.positions.at(entity_id).value;
				if (std::isfinite(pos.x) && std::isfinite(pos.x) && std::isfinite(pos.x)) {
					position = pos;
				}
			}
			glm::quat orientation;
			if (state.orientations.find(entity_id) != state.orientations.end()) {
				auto ori = state.orientations.at(entity_id).value;
				if (std::isfinite(ori.x) && std::isfinite(ori.x) && std::isfinite(ori.x) && std::isfinite(ori.w)) {
					orientation = ori;
				}
			}

			collidable->motion_state.transform.getBasis().setRotation(btQuaternion(orientation.x, orientation.y, orientation.z, orientation.w));
			collidable->motion_state.transform.setOrigin(btVector3(position.x, position.y, position.z));

			btRigidBody* body = this->bodies[entity_id];
			if (!body) {
				continue;
			}
			this->dynamicsWorld->removeRigidBody(body);
			if (collidable->mass != body->getInvMass()) {
				btVector3 fallInertia(0, 0, 0);
				collidable->shape->calculateLocalInertia(collidable->mass, fallInertia);
				body->setMassProps(collidable->mass, fallInertia);
				body->updateInertiaTensor();
				body->clearForces();
			}

			if (collidable->disable_deactivation) {
				body->forceActivationState(DISABLE_DEACTIVATION);
			}
			else if (body->getActivationState() == DISABLE_DEACTIVATION) {
				body->forceActivationState(ACTIVE_TAG);
			}

			if (collidable->disable_rotation) {
				body->setAngularFactor(btVector3(0.0, 0, 0.0));
			}
			body->setWorldTransform(collidable->motion_state.transform);
			this->dynamicsWorld->addRigidBody(body);

			if (state.velocties.find(entity_id) != state.velocties.end()) {
				const Velocity& vel = state.velocties.at(entity_id);
				if (std::isfinite(vel.linear.x) && std::isfinite(vel.linear.x) && std::isfinite(vel.linear.x)) {
					body->setLinearVelocity(vel.GetLinear() + btVector3(0.0, 1.0, 0.0) + body->getGravity());
				}
				if (std::isfinite(vel.angular.x) && std::isfinite(vel.angular.x) && std::isfinite(vel.angular.x)) {
					body->setAngularVelocity(vel.GetAngular());
				}
			}
		}

		this->dynamicsWorld->stepSimulation(delta, 10);

		for (auto itr = CollisionBodyMap::Begin(); itr != CollisionBodyMap::End(); ++itr) {
			auto entity_id = itr->first;
			if (itr->second->motion_state.transform_updated) {
				updated_entities.insert(entity_id);
				itr->second->motion_state.transform_updated = false;
			}
		}
		return std::move(updated_entities);
	}
Пример #22
0
		osg::Group * createWorld() {
        
            setupPerformanceStatistics();
            
            //getPhysics()->setUseFixedTimeSteps(false);
            //getPhysics()->setMaxSubSteps(5);
            
            getPhysics()->addPerformanceStatistics(this);
            
            cefix::log::setInfoLevel(osg::ALWAYS);
		
			getMainWindow()->getCamera()->setClearColor(osg::Vec4(0.2, 0.2, 0.2, 1.0));
		
			// statistics
			if (0) {
				enablePerformanceStatistics(true);
				get2DLayer()->addChild(getPerformanceStatisticsGroup());
			}
			
			setUseOptimizerFlag(false);
			
			osg::Group* g = new osg::Group();
			
			{
				//btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);
				cefixbt::StaticPlaneShape* groundShape = new cefixbt::StaticPlaneShape(osg::Vec3(0,0,1),0);
				cefixbt::MotionState* groundMotionState = new cefixbt::MotionState( btTransform(btQuaternion(0,0,0,1),btVector3(-250,-250,-1)) );
				
				btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
				osg::ref_ptr<cefixbt::RigidBody>  groundRigidBody = new cefixbt::RigidBody(groundRigidBodyCI);
                groundRigidBody->setContactCallback(new GroundContactCallback());
                
				addRigidBody(groundRigidBody);
				
				osg::Geode* groundgeode = new osg::Geode();
				groundgeode->addDrawable(new cefix::LineGridGeometry(osg::Vec3(500,500,0)));
				groundMotionState->addChild(groundgeode);
				g->addChild(groundMotionState);

			}
			
			for (unsigned int i = 0; i < 00; ++i) {
				cefixbt::SphereShape* fallShape = new cefixbt::SphereShape(1);
				cefixbt::MotionState* fallMotionState =  new cefixbt::MotionState( btTransform(btQuaternion(0,0,0,1),btVector3(cefix::in_between(-5,5), cefix::in_between(-5,5), cefix::in_between(50,500))) );
			
				btScalar mass = cefix::in_between(1,10);
				btVector3 fallInertia(0,0,0);
				fallShape->calculateLocalInertia(mass,fallInertia);
				
				btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
				osg::ref_ptr<cefixbt::RigidBody>  fallRigidBody = new cefixbt::RigidBody(fallRigidBodyCI);
			
				addRigidBody(fallRigidBody);
			
				osg::Geode* fallgeode = new osg::Geode();
				osg::ShapeDrawable* drawable = new osg::ShapeDrawable(fallShape);
				drawable->setColor(osg::Vec4(cefix::randomf(1.0),cefix::randomf(1.0),cefix::randomf(1.0),1.0));
				fallgeode->addDrawable(drawable);
				fallMotionState->addChild(fallgeode);
				g->addChild(fallMotionState);
			}
			
			std::vector<osg::ref_ptr<cefixbt::RigidBody> > boxes;
			for (unsigned int i = 0; i < 00; ++i) {
				cefixbt::BoxShape* fallShape = new cefixbt::BoxShape(osg::Vec3(1,1,1));
				cefixbt::MotionState* fallMotionState =  new cefixbt::MotionState( btTransform(btQuaternion(0,0,0,1),btVector3(cefix::in_between(-5,5), cefix::in_between(-5,5), cefix::in_between(50,500))) );
			
				btScalar mass = cefix::in_between(1,10);
				btVector3 fallInertia(0,0,0);
				fallShape->calculateLocalInertia(mass,fallInertia);
			
				btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
				osg::ref_ptr<cefixbt::RigidBody>  fallRigidBody = new cefixbt::RigidBody(fallRigidBodyCI);
			
				addRigidBody(fallRigidBody);
			
						
				osg::Geode* fallgeode = new osg::Geode();
				osg::ShapeDrawable* drawable = new osg::ShapeDrawable(fallShape);
				drawable->setColor(osg::Vec4(cefix::randomf(1.0),cefix::randomf(1.0),cefix::randomf(1.0),1.0));
				fallgeode->addDrawable(drawable);
				fallMotionState->addChild(fallgeode);
				g->addChild(fallMotionState);
				boxes.push_back(fallRigidBody);
			}
			
			
			
			if (1) {
				osg::Node* node = osgDB::readNodeFile("w.obj");
				osgUtil::Optimizer o;
				o.optimize(node);
				cefixbt::ConvexHullShape* fallShape = new cefixbt::ConvexHullShape(node, false);
				//cefixbt::ConvexTriangleMeshShape* fallShape = new cefixbt::ConvexTriangleMeshShape(node, false);
				osg::ref_ptr<cefixbt::RigidBody>  last(NULL), current(NULL);
				for (unsigned int i = 0; i < 10; ++i) {
					cefixbt::MotionState* fallMotionState =  new cefixbt::MotionState( btTransform(btQuaternion(0,0,0,1),btVector3(cefix::in_between(-50,50), cefix::in_between(-50,50), cefix::in_between(50,50))) );
				
					btScalar mass = cefix::in_between(1,10);
					btVector3 fallInertia(0,0,0);
					fallShape->calculateLocalInertia(mass,fallInertia);
				
					btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
					osg::ref_ptr<cefixbt::RigidBody>  fallRigidBody = new cefixbt::RigidBody(fallRigidBodyCI);
				
					fallRigidBody->setDamping(0.4, 0.4);
					
					addRigidBody(fallRigidBody);
				
                    
					fallMotionState->addChild(node);
					fallMotionState->setUserData(new cefixbt::RigidBodyDraggable(fallRigidBody, this));
					g->addChild(fallMotionState);
					last = current;
					current = fallRigidBody;
					_rigidBodies.push_back(current);
                    
					if (last && current) {
						const int mode(0);
						switch (mode) {
						case -1:
							break;
						case 0:
							{
								cefixbt::Point2PointConstraint* constraint = new cefixbt::Point2PointConstraint(last, current, osg::Vec3(7, 7, 0), osg::Vec3(-7, 0 , 0));
								addConstraint(constraint);
							}
							break;
						case 1:
							{
								cefixbt::Generic6DofConstraint* constraint = new cefixbt::Generic6DofConstraint(
									last, 
									current, 
									osg::Matrix::translate(osg::Vec3(5, 0, 0)), 
									osg::Matrix::translate(osg::Vec3(-15, 0 , 0)),
									true
								);
								constraint->setLinearLowerLimit(btVector3(0.0f, 0.0f, 0.0f));
								constraint->setLinearUpperLimit(btVector3(3.0f, 0.0f, 0.0f));

								constraint->setAngularLowerLimit(btVector3(0,0,0));
								constraint->setAngularUpperLimit(btVector3(0.2,0,0));
								addConstraint(constraint);
							}
							break;						
						
						case 2:
							{
								cefixbt::Generic6DofSpringConstraint* constraint = new cefixbt::Generic6DofSpringConstraint(
									last, 
									current, 
									osg::Matrix::translate(osg::Vec3(5, 0, 0)), 
									osg::Matrix::translate(osg::Vec3(-15, 0 , 0)),
									true
								);
								constraint->setLinearLowerLimit(btVector3(-1.0f, -1.0f, -1.0f));
								constraint->setLinearUpperLimit(btVector3(1.0f, 1.0f, 1.0f));

								constraint->setAngularLowerLimit(btVector3(-0.5,0,0));
								constraint->setAngularUpperLimit(btVector3(0.5,0.0,0));
								for(unsigned int i=0; i < 6; ++i) {
									constraint->enableSpring(i, true);
									constraint->setStiffness(i, 0.01);
									constraint->setDamping (i, 0.01);
								}
								
								addConstraint(constraint);
							}
                        
                        
						}
					}
				}
				
				
			}
			osg::Group* world = new osg::Group();
			world->addChild(g);
			_scene = g;	
			
            // debug-world
			if (1) {
				_debugNode = getDebugDrawNode(
                    /*cefixbt::DebugPhysicsDrawer::DBG_DrawAabb | */
                    cefixbt::DebugPhysicsDrawer::DBG_DrawConstraints | 
                    cefixbt::DebugPhysicsDrawer::DBG_DrawConstraintLimits |
                    cefixbt::DebugPhysicsDrawer::DBG_DrawFeaturesText |
                    cefixbt::DebugPhysicsDrawer::DBG_DrawContactPoints |
                    cefixbt::DebugPhysicsDrawer::DBG_NoDeactivation |
                    cefixbt::DebugPhysicsDrawer::DBG_NoHelpText |
                    cefixbt::DebugPhysicsDrawer::DBG_DrawText |
                    cefixbt::DebugPhysicsDrawer::DBG_ProfileTimings |
                    cefixbt::DebugPhysicsDrawer::DBG_DrawWireframe
                );
                world->addChild(_debugNode);
                _debugNode->setNodeMask(0x0);
			}			
			return world;
		}
/*!
  This function is recursive and first called for the root of the tree (the
  head of the creature). In this function, the strength of the joints are
  determined by the masses of the connected BodyTrees if they are not
  explicitly set.
  \param body is the BodyTree from which to setup the rigidbody used by Bullet
  in the simulation.
  \param position is the position of where in the physics world to put the
  current body. 
*/
btRigidBody* BulletCreature::AddBody(BodyTree body, btVector3 position) {
  //shape
  btVector3 dim = btVector3(body.box_dim.x,body.box_dim.y,body.box_dim.z);
  btCollisionShape* shape = new btBoxShape(dim);

  btVector3 fallInertia(0,0,0);
  float mass = body.GetMass();
  shape->calculateLocalInertia(mass,fallInertia);

  // Material
  Material current_material = body.material;

  //body
  btTransform offset;
  offset.setIdentity();
  offset.setOrigin(position);

  btMotionState* motion_state;

  motion_state = new btDefaultMotionState(offset);

  btRigidBody::btRigidBodyConstructionInfo rigid_body(mass,motion_state,shape,fallInertia);
  btRigidBody* current_body = new btRigidBody(rigid_body);
  
  current_body->setFriction(body.friction);

  // Add data
  m_bodies_.push_back(current_body);
  materials_.push_back(current_material);
  mass_.push_back(mass);
  m_shapes_.push_back(shape);

  //add children
  Joint joint;
  btTransform localA, localB;
  for(int i=0; i<body.body_list.size(); i++) {
    //child position
    joint = body.body_list[i].root_joint;
    Vec3 c = joint.connection_root - joint.connection_branch;
    btVector3 child_offset(c.x,c.y,c.z);
    //body
    btRigidBody* child_body = AddBody(body.body_list[i],position+child_offset);
    //joint
    localA.setIdentity();
    localB.setIdentity();
    Vec3 h = joint.hinge_orientation;
    localA.getBasis().setEulerZYX(h.x,h.y,h.z);
    localB.getBasis().setEulerZYX(h.x,h.y,h.z);
    Vec3 a = joint.connection_root;
    Vec3 b = joint.connection_branch;
    localA.setOrigin(btVector3(a.x,a.y,a.z));
    localB.setOrigin(btVector3(b.x,b.y,b.z));
    btHingeConstraint* hinge = new btHingeConstraint(*(current_body), *(child_body), localA, localB);
    m_joints_.push_back(hinge);

    // For now just proportional to the mass of the bodies,
    // seems to be what works best for most creatures.
    float strength = (body.body_list[i].root_joint.strength < 0) ?
          body.GetMass() + body.body_list[i].GetMass() :
          body.body_list[i].root_joint.strength;

    joint_strength_.push_back(strength);
    m_joints_.back()->setLimit(
            btScalar(joint.lower_limit),
            btScalar(joint.upper_limit),
            0.9, // Softness = 0.9 default
            0.3, // Bias factor = 0.3 default
            1.0); // Relaxation factor = 1.0 default
  }
  return current_body;
}
LevelObject * LevelObject::CreateCube()
{
    EngineMesh * mesh = new EngineMesh();
    {
        shared_ptr<PackContentHeader> pch = PackList::SharedInstance()->FindObject("SCMarineMeshFull");
        if(pch)
        {
            char* buffer = (char*)malloc(pch->_size);
            pch->_pack->ReadObjectFromPack(buffer, pch);
            mesh->LoadFromBuffer(buffer, pch->_size);
            free(buffer);
        }
    }

    
    TextureMaterial *material = new TextureMaterial();
    Texture * texture = new Texture();
    {
        shared_ptr<PackContentHeader> pch = PackList::SharedInstance()->FindObject("SCMarineTextureDiffuse");
        if(pch)
        { 
            char* buffer = (char*)malloc(pch->_size);
            pch->_pack->ReadObjectFromPack(buffer, pch);
            texture->LoadFromBuffer(buffer, pch->_size);
            free(buffer);
            material->SetTexture(texture);
        }
    }
    
    
    btCollisionShape *shape = NULL;
    {
        shared_ptr<PackContentHeader> pch = PackList::SharedInstance()->FindObject("WoodenCrate10CollisionMesh");
        if(pch)
        {
            CollisionMesh* cm = new CollisionMesh();
            char* buffer = (char*)malloc(pch->_size);
            pch->_pack->ReadObjectFromPack(buffer, pch);
            cm->LoadFromBuffer(buffer, pch->_size);
            free(buffer);
            
            shape = btCollisionShapeFromCollisionMesh(cm);
            delete cm;
        }
        
        if (!shape)
            shape = new btBoxShape(btVector3(0.5, 0.5, 0.5));
    }
	btVector3 fallInertia(0,0,0);
    shape->calculateLocalInertia(10, fallInertia);
    
    
    btDefaultMotionState *motionState = new btDefaultMotionState();
    btTransform t;
    t.setRotation(btQuaternion(btVector3(1, 0, 0), 0));
    motionState->setWorldTransform(t);
    
    btRigidBody::btRigidBodyConstructionInfo info(10, motionState, shape, fallInertia);
    btRigidBody *body = new btRigidBody(info);
    body->setCollisionFlags(0);
    body->setRestitution(0.01);
    ObjectBehaviourModel *obmm = new PhysicObjectBehaviuorModel(body);
    
    RenderObject *renderObject = new UnAnimRenderObject(mesh);
    
    
    LevelObject * result = new LevelObject(renderObject, obmm, material);
    return result;
}
Пример #25
0
BoundingBox::BoundingBox(btDiscreteDynamicsWorld* worldN)
{
	world = worldN;
	layer = 0;
	parent = NULL;

	Vertex fill = { { -0.5f*METER, -0.5f*METER, -0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill);
	Vertex fill1 = { { 0.5f*METER, -0.5f*METER, 0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill1);
	Vertex fill2 = { { -0.5f*METER, -0.5f*METER, 0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill2);
	Vertex fill3 = { { 0.5f*METER, -0.5f*METER, -0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill3);

	Vertex fill4 = { { -0.5f*METER, 0.5f*METER, -0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill4);
	Vertex fill5 = { { 0.5f*METER, 0.5f*METER, 0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill5);
	Vertex fill6 = { { -0.5f*METER, 0.5f*METER, 0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill6);
	Vertex fill7 = { { 0.5f*METER, 0.5f*METER, -0.5f*METER }, { 1.0f, 0.0f, 0.0f } };
	GetVertices().push_back(fill7);

	Index iFill1 = { glm::uvec3(0, 1, 2) };
	GetIndices().push_back(iFill1);
	Index iFill2 = { glm::uvec3(0, 3, 1) };
	GetIndices().push_back(iFill2);
	Index iFill3 = { glm::uvec3(4, 6, 5) };
	GetIndices().push_back(iFill3);
	Index iFill4 = { glm::uvec3(4, 5, 7) };
	GetIndices().push_back(iFill4);
	Index iFill5 = { glm::uvec3(0, 2, 6) };
	GetIndices().push_back(iFill5);
	Index iFill6 = { glm::uvec3(0, 6, 4) };
	GetIndices().push_back(iFill6);
	Index iFill7 = { glm::uvec3(1, 3, 7) };
	GetIndices().push_back(iFill7);
	Index iFill8 = { glm::uvec3(1, 7, 5) };
	GetIndices().push_back(iFill8);
	Index iFill9 = { glm::uvec3(0, 4, 7) };
	GetIndices().push_back(iFill9);
	Index iFill10 = { glm::uvec3(0, 7, 3) };
	GetIndices().push_back(iFill10);
	Index iFill11 = { glm::uvec3(1, 5, 6) };
	GetIndices().push_back(iFill11);
	Index iFill12 = { glm::uvec3(1, 6, 2) };
	GetIndices().push_back(iFill12);


	shape = new btBoxShape(btVector3(0.5f * METER, 0.5f * METER, 0.5f * METER));

	btDefaultMotionState* fallMotionState =
		new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50*METER, 0)));
	btScalar mass = 1;
	btVector3 fallInertia(0, 0, 0);
	shape->calculateLocalInertia(mass, fallInertia);
	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, shape, fallInertia);
	rigidBody = new btRigidBody(fallRigidBodyCI);
	world->addRigidBody(rigidBody);

	

	Load();
}
Пример #26
0
Mesh Simulation::step(mat4x4 &matrix) {
	random_device rd;
	mt19937 gen(rd());
	normal_distribution<> d(0, 1);

	btTransform transLast, trans;
	fallRigidBody->getMotionState()->getWorldTransform(transLast);
	dynamicsWorld->stepSimulation(1.0 / FPS);
	fallRigidBody->getMotionState()->getWorldTransform(trans);

	//if (!((uint)time%10))
	//	cout << trans.getOrigin().getX() << " " << trans.getOrigin().getY() << " " << trans.getOrigin().getZ() << endl;

	dynamicsWorld->removeRigidBody(fallRigidBody);

	Mesh mesh = getMesh();
	fallRigidBody->setCollisionShape(fallShape);
	//fallRigidBody->applyImpulse(btVector3(0, 1, 0), btVector3(0, 0, 0));

	double rTime = time-warmup;
	if (FPS == 20)
		rTime = time-66;

	colWas = false;
	MyContactResultCallback callback(this);
	dynamicsWorld->contactPairTest(fallRigidBody, groundRigidBody, callback);

	double yDiff = trans.getOrigin().y() - transLast.getOrigin().y();
	if (colWas && yDiff>0 && rTime>0) {
		if (!colBefore) {
			//cout << "up! " << chrono::system_clock::now().time_since_epoch().count() << endl;
			glm::vec3 pos(minPos.x(), minPos.y(), minPos.z());
			pos = glm::normalize(pos);
			pos *= -yDiff*1000;
			//cout << pos.x << " " << pos.y << " " << pos.z << endl;

			fallRigidBody->applyForce(btVector3(0, yDiff*500, 0), minPos);
			colBefore = true;
		}
	}
	else
		colBefore = false;

	btScalar mass = 1;
	btVector3 fallInertia(0, 0, 0);
	fallShape->calculateLocalInertia(mass, fallInertia);
	fallRigidBody->setMassProps(1, fallInertia);
	fallRigidBody->updateInertiaTensor();

	/*if (rTime>0)
		fallRigidBody->setRollingFriction(-0.5);*/
	dynamicsWorld->addRigidBody(fallRigidBody);
	if (rTime>0) {
		dynamicsWorld->removeRigidBody(groundRigidBody);
		//groundRigidBody->setRollingFriction(0.2);
		dynamicsWorld->addRigidBody(groundRigidBody);
	}
	if (rTime==0) {
		basePos = getPos();
	}

	time++;

	/*btVector3 posV = trans.getOrigin();//fallRigidBody->getCenterOfMassPosition();
	btQuaternion quat = trans.getRotation();//fallRigidBody->getOrientation();
	vec3 tVec(posV.x(), posV.y(), posV.z());

	glm::quat quaternion(quat.x(), quat.y(), quat.z(), quat.w());
	matrix = mat4_cast(quaternion);
	matrix = translate(matrix, tVec);*/
	trans.getOpenGLMatrix(value_ptr(matrix));
	lastMatrix = matrix;

	return mesh;

	/*btSoftBodyWorldInfo m_softBodyWorldInfo;
	btSoftBody softBody(&m_softBodyWorldInfo);

	softBody.*/
}
Пример #27
0
	JNIEXPORT void Java_org_bulletSamples_physics_CollisionShape_NsetMass( JNIEnv* env, jobject self, jint idRigidBody, jfloat mass )
	{
		btVector3 fallInertia(0,0,0);
		//((btRigidBody*)btObjects::get(idRigidBody))->getCollisionShape()->calculateLocalInertia(mass, fallInertia)
		((btRigidBody*)btObjects::get(idRigidBody))->setMassProps(mass, fallInertia);
	}
Пример #28
0
void initPhysics()
{
	// Inicializacion del motor de fisica
    btBroadphaseInterface* broadphase = new btDbvtBroadphase();
 
    btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
 
    btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
 
    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,-10,0));
 
	// Definimos plano del suelo - Cuerpo rigido estatico (masa=0)

    btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);// parametros: normal {x,y,z} , espesor o altura
     
	btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0))); 
	//los 2 vectores representan la orientacion (x,y,z,w) y traslacion (x,y,z) del objeto suelo,
	// traslacion es (0,-1,0) para compensar el espesor que es 1, asi el lado superior del piso queda en Y=0

    btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
    btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
    dynamicsWorld->addRigidBody(groundRigidBody);

	// Definicion de las cajas

	btCollisionShape* cajaShape = new  btBoxShape(btVector3(tamanioCaja/2.0,tamanioCaja/2.0,tamanioCaja/2.0));
	// Las dimensiones del BoxShape se definen como la mitad del lado en (X,Y,Z) o distancia del centro al borde en cada coordenada
	btScalar mass = 1;
	btVector3 fallInertia(0,0,0);
	cajaShape->calculateLocalInertia(mass,fallInertia);

	btTransform startTransform;
	startTransform.setIdentity();
	
	int cantRows=4;
	int cantCols=4;
	float separacion=0.3f;

	int col=0;	int row=0;	int altura=0; 

	for (int k=0;k<totalCajas;k++){

		if (col>3)	{col=0;row++;} // esto es para apilar las cajas
		else 	{col++;}
		if (row>3) {row=0;col=0;altura++;}
		
		// defino la posicion inicial de la caja
		float posX=((col-cantCols/2)*(tamanioCaja+separacion));
		float posY=1.0f+altura*(tamanioCaja+separacion);
		float posZ=(row-cantRows/2)*(tamanioCaja+separacion);

		// aplico transformacion inicial
		startTransform.setOrigin(btVector3(btScalar(posX),btScalar(posY),btScalar(posZ)));
			
		btDefaultMotionState* fallMotionState = new btDefaultMotionState(startTransform);
		btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,cajaShape,fallInertia);

		cajasRB[k] = new btRigidBody(fallRigidBodyCI);// creo el cuerpo rigido
		
		cajasRB[k]->setFriction(btScalar(0.1)); // defino factor de friccion
		dynamicsWorld->addRigidBody(cajasRB[k]); // agrego la caja a la simulacion
	}
	// Defino Esfera
	
	btCollisionShape* esferaShape = new  btSphereShape(radioEsfera);
	mass = 10;
	esferaShape->calculateLocalInertia(mass,fallInertia);

	startTransform.setIdentity(); 
	startTransform.setOrigin(btVector3(btScalar(posicionEsferaRB[0]),btScalar(posicionEsferaRB[1]),btScalar(posicionEsferaRB[2])));
	btDefaultMotionState* esferaMotionState = new btDefaultMotionState(startTransform);

	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI2(mass,esferaMotionState,esferaShape,fallInertia);
    esferaRB = new btRigidBody(fallRigidBodyCI2);
	// lo defino  como Kinetic Rigid Body
	
	esferaRB->setCollisionFlags( esferaRB->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
	esferaRB->setActivationState(DISABLE_DEACTIVATION);
	
	dynamicsWorld->addRigidBody(esferaRB);

	// Defino Cubo
	
	btCollisionShape* cuboShape = new  btBoxShape(btVector3(5.0,5.0,5.0));
	mass = 10;
	cuboShape->calculateLocalInertia(mass,fallInertia);

	startTransform.setIdentity(); 
	startTransform.setOrigin(btVector3(btScalar(40),btScalar(20),btScalar(0)));
	btDefaultMotionState* cuboMotionState = new btDefaultMotionState(startTransform);

	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI3(mass,cuboMotionState,cuboShape,fallInertia);
    cuboRB = new btRigidBody(fallRigidBodyCI3);
	cuboRB->setFriction(0.5);
	dynamicsWorld->addRigidBody(cuboRB);
	
 }
Пример #29
0
/*
	Retrieves a DynamicObject from the game library.
	Returns null if no object was found that matches name.
*/
DynamicObject * GameLibrary::getDynamicObject(string name) {
	// see if an instance of the object exists in dynamicObjects map.
	// if not load it in from memory, create it, and put it in the map.

	unordered_map<string, DynamicObject*> ::iterator it = dynamicObjects.find(name);

	DynamicObject *dynObj;
 	if(it != dynamicObjects.end())
	{
		//element found;
		dynObj = it->second;

		// create a clone of it.
		return dynObj->clone(this->mSceneManager);

	} else {
		// element was not found.
		// load it in and create instance 

		std::string fileName = "../TeamProject/GameData/DynamicObjects/" + name +".json";
		FILE* pFile = fopen(fileName.c_str(), "rb");
		
		if (pFile != NULL) {
			char buffer[65536];
			rapidjson::FileReadStream is(pFile, buffer, sizeof(buffer));
			rapidjson::Document document;
			document.ParseStream<0, rapidjson::UTF8<>, rapidjson::FileReadStream>(is);

			// File was opened successfully and parsed into JSON,
			// now we create the instance

			list<Ogre::String> meshNames;
			if (document.HasMember("meshNames")) {
				for (int i = 0; i < document["meshNames"].Size(); i++) {
					meshNames.push_back(document["meshNames"][i].GetString());
				}
			} else {
				meshNames.push_back("ERROR.MESH.mesh");
			}


			// Parse data for the construction of the rigid body

			double restitution;
			if (document.HasMember("restitution")) {
				restitution = document["restitution"].GetDouble();
			} else {
				restitution = 0.0;
			}

			int massTemp;
			if (document.HasMember("mass")) {
				massTemp = document["mass"].GetInt();
			} else {
				massTemp = 1;
			}


			// Parse scale info
			Ogre::Vector3 scale = Ogre::Vector3(1, 1, 1);
			if (document.HasMember("scale")) {
				scale = parseVector3(document["scale"]);
			} else 
			{
				scale = Ogre::Vector3(1, 1, 1);
			}

			// Needed for collisions 
			// interaction legend by diana 
			// -1 = no interaction 
			// 1 = teapots meaning they disappear (for now) 
			// 2 = tuna can (ending... for now) 
			int interaction;
			if (document.HasMember("interaction")) {
				interaction = document["interaction"].GetInt();
			} else {
				interaction = -1; // this means there's no interaction 
			}


			string collisionShape;
			if (document.HasMember("collisionShape")) {
				collisionShape = document["collisionShape"].GetString();
			} else {
				collisionShape = "btBoxShape";
			}


			
			// temp vars used for parsing collision shape size data
			btVector3 colDim3 = btVector3(1,1,1);
			btScalar colScala = 1;
			btScalar colScalb = 1;

			/* Parse the CollisionShape and its size size */
			

			// if no collision shape size is specified in the json file
			// base its size off of the dimensions of the mesh
			// For simplicity, this only works if the dynamic object has
			// one mesh. 

			Ogre::Vector3 meshDimensions;
			std::string s = std::to_string(meshNames.size()); 
			

			if (!document.HasMember("collisionShapeSize")) {

				// XXX: The collision shape auto sizing functionality is experimental
				// and needs to be tested.

				Ogre::Entity* tempEntity = mSceneManager->createEntity(meshNames.front());
				colDim3 = ogreToBulletVector3(tempEntity->getMesh()->getBounds().getHalfSize());
				colScala = tempEntity->getMesh()->getBoundingSphereRadius(); // radius
				colScalb = tempEntity->getMesh()->getBounds().getSize()[1]; // height
			
				// apply scale
				colDim3 = btVector3(colDim3[0] * scale.x, colDim3[1] * scale.y, colDim3[2] * scale.z);
				colScala = colScala * scale.x;
				colScalb = colScalb * scale.y;

			} else if(document.HasMember("collisionShapeSize")) {
				/// Note: FIgure out why it keeps going into this if block instead of the first one 
				if (document["collisionShapeSize"].Size() == 3) {
					colDim3 = ogreToBulletVector3(parseVector3(document["collisionShapeSize"]));
				}
				colScala = document["collisionShapeSize"][0].GetDouble();	
				colScalb = document["collisionShapeSize"][1].GetDouble();   
			} else {
				OutputDebugString("ERROR! Need to specify the collisionshape size!");
				// default collision shape sizes
				colDim3 = btVector3(1,1,1);
				colScala = 1;
				colScalb = 1;
			}


			
			// holds the actual collision shape of the object
			btCollisionShape *colShape;
			
			if (collisionShape.compare("btSphereShape") == 0) {
				colShape = new btSphereShape(colScala);
			} else if(collisionShape.compare("btBoxShape") == 0) {
				colShape = new btBoxShape(colDim3);
			} else if(collisionShape.compare("btCylinderShape") == 0) {
				colShape = new btCylinderShape(colDim3);
			} else if(collisionShape.compare("btCapsuleShape") == 0) {
				colShape = new btCapsuleShape(colScala, colScalb);
			} else {
				// default to box shape if no valid collision shape was found
				colShape = new btBoxShape(btVector3(1,1,1));
			}
			
			// XXX: Implement these other shapes as needed!
			/*
			else if(collisionShape.compare("btConeShape") == 0) {
				
			} else if(collisionShape.compare("btMultiSphereShape") == 0) {
				
			} else if(collisionShape.compare("btConvexHullShape") == 0) {
				
			} else if(collisionShape.compare("btConvexTriangleMeshShape") == 0) {
				
			} else if(collisionShape.compare("btCompoundShape") == 0) {
				
			}
			*/
			

			// create the rigid body

			// set position to 0,0,0 later change when placing in the game
			btDefaultMotionState* fallMotionState =
				new btDefaultMotionState( btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
			btScalar mass = (btScalar) massTemp;
			btVector3 fallInertia(0, 0, 0);
			colShape->calculateLocalInertia(mass, fallInertia);
				

			btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, colShape, fallInertia);
			fallRigidBodyCI.m_restitution = restitution;

			// Create the rigid body
			btRigidBody* tempRigidBody = new btRigidBody(fallRigidBodyCI);

			// New way
			DynamicObject *newD = new DynamicObject(meshNames, colShape, Ogre::Vector3(0,0,0), interaction, scale);

			// put it into the library
			dynamicObjects.emplace(name, newD);

			std::fclose(pFile);

			return newD->clone(this->mSceneManager);
		} else {
			// no file was found
			return NULL;
		}
	}
}
Пример #30
0
int main (void)
{

        btBroadphaseInterface* broadphase = new btDbvtBroadphase();

        btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
        btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);

        btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;

        btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);

        dynamicsWorld->setGravity(btVector3(0,-10,0));


        btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);

        btCollisionShape* fallShape = new btSphereShape(1);


        btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
        btRigidBody::btRigidBodyConstructionInfo
                groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
        btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
        dynamicsWorld->addRigidBody(groundRigidBody);


        btDefaultMotionState* fallMotionState =
                new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,50,0)));
        btScalar mass = 1;
        btVector3 fallInertia(0,0,0);
        fallShape->calculateLocalInertia(mass,fallInertia);
        btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
        btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
        dynamicsWorld->addRigidBody(fallRigidBody);


        for (int i=0 ; i<300 ; i++) {
                dynamicsWorld->stepSimulation(1/60.f,10);

                btTransform trans;
                fallRigidBody->getMotionState()->getWorldTransform(trans);

                std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl;
        }

        dynamicsWorld->removeRigidBody(fallRigidBody);
        delete fallRigidBody->getMotionState();
        delete fallRigidBody;

        dynamicsWorld->removeRigidBody(groundRigidBody);
        delete groundRigidBody->getMotionState();
        delete groundRigidBody;


        delete fallShape;

        delete groundShape;


        delete dynamicsWorld;
        delete solver;
        delete collisionConfiguration;
        delete dispatcher;
        delete broadphase;

        return 0;
}