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; }
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); }
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; }
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; }
void PhysicsBridge::ResetBall(Ball* ball) { btVector3 startPos = fallMotionState->m_startWorldTrans.getOrigin(); dynamicsWorld->removeRigidBody(fallRigidBody); delete fallRigidBody->getMotionState(); delete fallRigidBody; fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), startPos)); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); fallRigidBody = new btRigidBody(fallRigidBodyCI); dynamicsWorld->addRigidBody(fallRigidBody); }
void physics::Mesh::buildMesh() { shape = new btBvhTriangleMeshShape(mesh, true, true); btDefaultMotionState* fallMotionState = // new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(-scale/2,0,-scale/2))); new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0))); //fallMotionState->getWorldTransform(trans); //trans.setRotation(btQuaternion(0,1,0, 3.f*M_PI)); //fallMotionState->setWorldTransform(trans); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(0,fallMotionState,shape,btVector3(0,0,0)); body = new btRigidBody(fallRigidBodyCI); //body->setDamping(.98, .95); }
void PhysicsBridge::Initialize(Level* level, Ball* ball) { heightMap = level->GetHeighMapData(); // 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, GRAVITY, 0)); //HeightMap m_HeightStickWidth = level->GetWidth(); //Bredd på kartan // must be (2^N) + 1 m_HeightStickLeangth = level->GetLength(); //Längd på kartan // must be (2^N) + 1 m_HeightMapData = heightMap;// getRawHeightfieldData(m_model, m_type, m_minHeight, m_maxHeight); m_HeightScale = 1;//Höjd skala m_MinHeight = -255;// m_MaxHeight = 255;// m_UpAxis = 1; // // start with Y-axis as "up" m_HeightDataType = PHY_FLOAT;// m_FlipQuadEdges = false; heightmapShape = new Heightfield(m_HeightStickWidth, m_HeightStickLeangth, m_HeightMapData, m_HeightScale, m_MinHeight, m_MaxHeight, m_UpAxis, m_HeightDataType, m_FlipQuadEdges); heightmapShape->setLocalScaling(btVector3(level->GetScale(), level->GetMaxHeight(), level->GetScale())); heightmapMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); btRigidBody::btRigidBodyConstructionInfo heightmapRigidBodyCI(0, heightmapMotionState, heightmapShape, btVector3(0, 0, 0)); heightmapRigidBody = new btRigidBody(heightmapRigidBodyCI); dynamicsWorld->addRigidBody(heightmapRigidBody); // Ball fallShape = new btSphereShape(1); //fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 5, 0))); v3 ballStartPos; ball->GetPosition(ballStartPos); fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(ballStartPos.x, ballStartPos.y, ballStartPos.z))); mass = 2; fallInertia = btVector3(9, 9, 9); //fallShape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); fallRigidBody = new btRigidBody(fallRigidBodyCI); dynamicsWorld->addRigidBody(fallRigidBody); fallRigidBody->setRollingFriction(0.02); }
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]); } }
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; }
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); };
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; }
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); }
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); }
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; }
Leaf::Leaf(double m, double a, double dens, double air, const btVector3& pos, const btVector3& flu, const btVector3& angleVel) { mass = m; area = a; density = dens; airCoeff = air; position = pos; flutter = flu; angVel = angleVel; rotation = btVector3(rand() % 720 - 360, rand() % 720 - 360, rand() % 720 - 360); rotation = normVec(rotation); fallShape = new btSphereShape(1); fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(rotation, 1), btVector3(position))); fallInertia = btVector3(0, 0, 0); fallShape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); leafBody = new btRigidBody(fallRigidBodyCI); leafBody->setLinearVelocity(btVector3(0, 0, 0)); }
bool ROC::Collision::Create(int f_type, const glm::vec3 &f_size, float f_mass) { if(!m_rigidBody) { btClamp(f_type, static_cast<int>(CT_Sphere), static_cast<int>(CT_Cone)); btVector3 l_inertia; btCollisionShape *l_shape = nullptr; switch(f_type) { case CT_Sphere: l_shape = new btSphereShape(f_size.x); break; case CT_Box: l_shape = new btBoxShape(btVector3(f_size.x, f_size.y, f_size.z)); break; case CT_Cylinder: l_shape = new btCylinderShape(btVector3(f_size.x, f_size.y, f_size.z)); break; case CT_Capsule: l_shape = new btCapsuleShape(f_size.x, f_size.y); break; case CT_Cone: l_shape = new btConeShape(f_size.x, f_size.y); break; } if(l_shape) { l_shape->calculateLocalInertia(f_mass, l_inertia); btTransform l_transform; l_transform.setIdentity(); btDefaultMotionState *l_fallMotionState = new btDefaultMotionState(l_transform); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(f_mass, l_fallMotionState, l_shape, l_inertia); m_rigidBody = new btRigidBody(fallRigidBodyCI); m_rigidBody->setUserPointer(this); } } return (m_rigidBody != nullptr); }
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); }
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); } }
/* 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; } } }
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; }
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(); }
void RudePhysicsMesh::Load(RudeMesh *modelmesh, float mass) { CPVRTPODScene *model = modelmesh->GetModel(); m_data = new btTriangleIndexVertexArray(); for(int i = 0; i < model->nNumNode; i++) { SPODNode *node = &model->pNode[i]; SPODMesh *mesh = &model->pMesh[node->nIdx]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; unsigned char *indices = (unsigned char*) mesh->sFaces.pData; btIndexedMesh btmesh; btmesh.m_numTriangles = mesh->nNumFaces; btmesh.m_triangleIndexBase = indices; btmesh.m_triangleIndexStride = 6; btmesh.m_numVertices = mesh->nNumVertex; btmesh.m_vertexBase = mesh->pInterleaved + (long)mesh->sVertex.pData; btmesh.m_vertexStride = mesh->sVertex.nStride; /* for(int k = 0; k < btmesh.m_numVertices; k++) { float *base = (float *) (btmesh.m_vertexBase + btmesh.m_vertexStride * k); printf("vert: %f %f %f\n", base[0], base[1], base[2]); } */ RUDE_REPORT("Loading %s (%d tris, %d verts)\n", node->pszName, btmesh.m_numTriangles, btmesh.m_numVertices); m_data->addIndexedMesh(btmesh, PHY_SHORT); int subpart = m_data->getNumSubParts() - 1; m_subPartMappings[subpart] = i; } m_shape = new btBvhTriangleMeshShape(m_data, false); btVector3 inertia(0,0,0); if(mass > 0.0f) inertia = btVector3(4,4,4); // m_shape->calculateLocalInertia(mass,inertia); m_motionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0))); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, m_motionState, m_shape, inertia); m_rigidBody = new btRigidBody(fallRigidBodyCI); RudePhysics::GetInstance()->AddObject(this); }
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); }
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; }
int main() { // Specify the dynamic AABB tree broadphase algorithm to be used to work out what objects // to test collision for. btBroadphaseInterface* broadphase = new btDbvtBroadphase(); // The collision configuration allows you to fine tune the algorithms used // for the full (not broadphase) collision detection. Here be dragons! btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); // We also need a "solver". This is what causes the objects to interact // properly, taking into account gravity, game logic supplied forces, // collisions, and hinge constraints. It does a good job as long as you // don't push it to extremes, and is one of the bottlenecks in any high // performance simulation. There are parallel versions available for some // threading models. btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; // Now, we can finally instantiate the dynamics world. btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Set the gravity. We have chosen the Y axis to be "up". dynamicsWorld->setGravity(btVector3(0, -10, 0)); // In this demonstration, we will place a ground plane running through // the origin. btCollisionShape* groundShape = new btStaticPlaneShape( btVector3(0, 1, 0), 1); // The shape that we will let fall from the sky is a sphere with a radius // of 1 metre. btCollisionShape* fallShape = new btSphereShape(1); // Instantiate the ground. Its orientation is the identity, Bullet quaternions // are specified in x,y,z,w form. The position is 1 metre below the ground, // which compensates the 1m offset we had to put into the shape itself. btDefaultMotionState* groundMotionState = new btDefaultMotionState( btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); // The first and last parameters of the following constructor are the mass and // inertia of the ground. Since the ground is static, we represent this by // filling these values with zeros. Bullet considers passing a mass of zero // equivalent to making a body with infinite mass - it is immovable. btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); // Add the ground to the world. dynamicsWorld->addRigidBody(groundRigidBody); // Adding the falling sphere is very similar. We will place it 50m above the // ground. btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0))); // Since it's dynamic we will give it a mass of 1kg. I can't remember how to // calculate the inertia of a sphere, but that doesn't matter because Bullet // provides a utility function. btScalar mass = 1; btVector3 fallInertia(0, 0, 0); fallShape->calculateLocalInertia(mass, fallInertia); // Construct the rigid body just like before, and add it to the world. btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI); dynamicsWorld->addRigidBody(fallRigidBody); // This is where the fun begins. Step the simulation 300 times, at an interval // of 60hz. This will give the sphere enough time to hit the ground under the // influence of gravity. Each step, we will print out its height above the // ground. 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; } // Clean up behind ourselves like good little programmers. Note that this is // INCORRECT. We should be using unique_ptr<T> or shared_ptr<T> since we don't // know if any of the above functions throw an exception. 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; }
void Object::Load(){ if (!isStatic){ btTransform trans; trans.setFromOpenGLMatrix(glm::value_ptr(position)); btDefaultMotionState* motState = new btDefaultMotionState(trans); btScalar mass = 1; btVector3 fallInertia(0, 0, 0); shape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, motState, shape, fallInertia); rigidBody = new btRigidBody(fallRigidBodyCI); rigidBody->setFriction(1.35f); if (isGhost){ rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | rigidBody->CF_NO_CONTACT_RESPONSE); } world->addRigidBody(rigidBody); } else{ btTransform trans; trans.setFromOpenGLMatrix(glm::value_ptr(position)); btDefaultMotionState* motState = new btDefaultMotionState(trans); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, motState, shape, btVector3(0, 0, 0)); rigidBody = new btRigidBody(groundRigidBodyCI); rigidBody->setFriction(1.35f); if (isGhost){ rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | rigidBody->CF_NO_CONTACT_RESPONSE); } world->addRigidBody(rigidBody); } shader = LoadShaders(vertexName, "geometry-shader[basic].txt", fragmentName); cameraUniform = shader->uniform("camera"); posNormUniform = shader->uniform("normalPos"); texUniform = shader->uniform("tex"); disUniform = shader->uniform("dis"); normUniform = shader->uniform("norm"); posUniform = shader->uniform("position"); normal = LoadTexture(LoadBmp(normalName)); texture = LoadTexture(LoadBmp(textureName)); displacement = LoadTexture(LoadBmp(displacementName)); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*vertices.size(), &vertices.front(), GL_STATIC_DRAW); glEnableVertexAttribArray(shader->attrib("vert_VS_in")); glVertexAttribPointer(shader->attrib("vert_VS_in"), 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), NULL); glEnableVertexAttribArray(shader->attrib("frag_VS_in")); glVertexAttribPointer(shader->attrib("frag_VS_in"), 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(shader->attrib("normal_VS_in")); glVertexAttribPointer(shader->attrib("normal_VS_in"), 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*)(5 * sizeof(GLfloat))); glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Index)*indices.size(), &indices.front(), GL_STATIC_DRAW); glBindVertexArray(0); }
int main( int argc, char* args[] ) { //SDL //Initialize all SDL subsystems if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) { return 1; } //Set up the screen screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE ); //If there was an error in setting up the screen if( screen == NULL ) { return 1; } //Set the window caption SDL_WM_SetCaption( "Hello World", NULL ); //Load the images message = load_image( "data/hello.bmp" ); background = load_image( "data/background.bmp" ); sphere = load_image("data/Circle.bmp"); //SDL //Physics //=> World Creation // Specify the dynamic AABB tree broadphase algorithm to be used to work out what objects // to test collision for. btBroadphaseInterface* broadphase = new btDbvtBroadphase(); // The collision configuration allows you to fine tune the algorithms used // for the full (not broadphase) collision detection. Here be dragons! btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); // We also need a "solver". This is what causes the objects to interact // properly, taking into account gravity, game logic supplied forces, // collisions, and hinge constraints. It does a good job as long as you // don't push it to extremes, and is one of the bottlenecks in any high // performance simulation. There are parallel versions available for some // threading models. btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; // Now, we can finally instantiate the dynamics world. btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Set the gravity. We have chosen the Y axis to be "up". dynamicsWorld->setGravity(btVector3(0, -10, 0)); //=> World Creation //=> Ground Creation // In this demonstration, we will place a ground plane running through // the origin. btCollisionShape* groundShape = new btStaticPlaneShape( btVector3(0, 1, 0), 1); // Instantiate the ground. Its orientation is the identity, Bullet quaternions // are specified in x,y,z,w form. The position is 1 metre below the ground, // which compensates the 1m offset we had to put into the shape itself. btDefaultMotionState* groundMotionState = new btDefaultMotionState( btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); // The first and last parameters of the following constructor are the mass and // inertia of the ground. Since the ground is static, we represent this by // filling these values with zeros. Bullet considers passing a mass of zero // equivalent to making a body with infinite mass - it is immovable. btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); //=> Ground Creation //=> Sphere Creation // The shape that we will let fall from the sky is a sphere with a radius // of 1 metre. btCollisionShape* fallShape = new btSphereShape(1); // Adding the falling sphere is very similar. We will place it 50m above the // ground. btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0))); // Since it's dynamic we will give it a mass of 1kg. I can't remember how to // calculate the inertia of a sphere, but that doesn't matter because Bullet // provides a utility function. btScalar mass = 1; btVector3 fallInertia(0, 0, 0); fallShape->calculateLocalInertia(mass, fallInertia); // Construct the rigid body just like before, and add it to the world. btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI); //=> Sphere Creation // Add the ground and sphere to the world. dynamicsWorld->addRigidBody(fallRigidBody); dynamicsWorld->addRigidBody(groundRigidBody); //Physics bool go = true; while (go){ SDL_Event incomingEvent; while (SDL_PollEvent(&incomingEvent)) { switch (incomingEvent.type) { case SDL_QUIT: go = false; break; } } //Logic //Physics dynamicsWorld->stepSimulation(1 / 60.f, 10); btTransform trans; fallRigidBody->getMotionState()->getWorldTransform(trans); //std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl; //Physics //SDL //Clear screen SDL_FillRect(screen, NULL, 0x000000); //Apply the background to the screen apply_surface(0, 0, background, screen); apply_surface(320, 0, background, screen); apply_surface(0, 240, background, screen); apply_surface(320, 240, background, screen); //Apply the message to the screen //apply_surface(180, 140, message, screen); apply_surface(50, -(trans.getOrigin().getY()), sphere, screen); //apply_surface(50, 50, sphere, screen); std::cout << "X: " << trans.getOrigin().getX() << " Y: " << trans.getOrigin().getY() << std::endl; //SDL //Update SDL_Flip(screen); //Wait 2 seconds SDL_Delay( 50 ); } //Free the surfaces SDL_FreeSurface( message ); SDL_FreeSurface( background ); //Quit SDL SDL_Quit(); return 0; }