Example #1
0
	void PhysicsMgr::start()
	{
		createEmptyDynamicsWorld();

		///create a few basic rigid bodies
		btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.), btScalar(50.), btScalar(50.)));

		m_collisionShapes.push_back(groundShape);

		btTransform groundTransform;
		groundTransform.setIdentity();
		groundTransform.setOrigin(btVector3(0, -50, 0));
		{
			btScalar mass(0.);
			createRigidBodyInternal(mass, groundTransform, groundShape, btVector4(0, 0, 1, 1));
		}
		{
			//create a few dynamic rigidbodies
			// Re-using the same collision is better for memory usage and performance

			btBoxShape* colShape = createBoxShape(btVector3(.1, .1, .1));


			//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
			m_collisionShapes.push_back(colShape);

			/// Create Dynamic Objects
			btTransform startTransform;
			startTransform.setIdentity();

			btScalar	mass(1.f);

			//rigidbody is dynamic if and only if mass is non zero, otherwise static
			bool isDynamic = (mass != 0.f);

			btVector3 localInertia(0, 0, 0);
			if (isDynamic)
				colShape->calculateLocalInertia(mass, localInertia);

			//int index = 0;
			//for (int k = 0; k < ARRAY_SIZE_Y; k++)
			//{
			//	for (int i = 0; i < ARRAY_SIZE_X; i++)
			//	{
			//		for (int j = 0; j < ARRAY_SIZE_Z; j++)
			//		{
			//			startTransform.setOrigin(btVector3(
			//				btScalar(0.2*i),
			//				btScalar(2 + .2*k),
			//				btScalar(0.2*j)));


			//			auto body = createRigidBody(mass, startTransform, colShape, btVector4(1, 0, 0, 1));
			//			body->setUserIndex(index);
			//			index++;
			//		}
			//	}
			//}
		}
	}
Example #2
0
void MultipleBoxesExample::initPhysics()
{
	m_guiHelper->setUpAxis(1);

	createEmptyDynamicsWorld();
	
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0)); 
	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}


	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance
        btBoxShape* colShape = createBoxShape(btVector3(1,1,1));
		 
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);

		
		for(int i=0;i<TOTAL_BOXES;++i) {
			startTransform.setOrigin(btVector3(
									 btScalar(0),
									 btScalar(20+i*2),
									 btScalar(0)));
			createRigidBody(mass,startTransform,colShape);		 
		}
	}

	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
Example #3
0
void clientKeyboard(unsigned char key, int x, int y)
{
	if ( key == 'R' || key == 'r' )
	{
		destroyShapes();

		g_shapesType[ 0 ] = randomShapeType( 0, 1 );
		g_shapesType[ 1 ] = randomShapeType( 0, 1 );

		( g_shapesType[ 0 ] == 0 ) ? createBoxShape( 0 ) : createSphereShape( 0 );
		( g_shapesType[ 1 ] == 0 ) ? createBoxShape( 1 ) : createSphereShape( 1 );

		g_shapesPenetrate = calcPenDepth();
	}
	else if ( key == 'Q' || key == 'q' )
	{
		destroyShapes();
	}
	else if ( key == 'T' || key == 't' )
	{
#ifdef DEBUG_ME
		SimdVector3 shapeAPos = g_convexShapesTransform[ 0 ].getOrigin();
		SimdVector3 shapeBPos = g_convexShapesTransform[ 1 ].getOrigin();

		SimdMatrix3x3 shapeARot = g_convexShapesTransform[ 0 ].getBasis();
		SimdMatrix3x3 shapeBRot = g_convexShapesTransform[ 1 ].getBasis();

		FILE* fp = 0;

		fopen_s( &fp, "shapes.txt", "w" );

		char str[ 256 ];
		sprintf_s( str, 256, "PosA: %f, %f, %f\nPosB: %f, %f, %f\n", shapeAPos.x(), shapeAPos.y(), shapeAPos.z(),
			shapeBPos.x(), shapeBPos.y(), shapeBPos.z() );
		fputs( str, fp );

		sprintf_s( str, 256, "RotA: %f, %f, %f\n%f, %f, %f\n%f, %f, %f\nRotB: %f, %f, %f\n%f, %f, %f\n%f, %f, %f\n\n",
			shapeARot.getRow( 0 ).x(), shapeARot.getRow( 0 ).y(), shapeARot.getRow( 0 ).z(),
			shapeARot.getRow( 1 ).x(), shapeARot.getRow( 1 ).y(), shapeARot.getRow( 1 ).z(),
			shapeARot.getRow( 2 ).x(), shapeARot.getRow( 2 ).y(), shapeARot.getRow( 2 ).z(),
			shapeBRot.getRow( 0 ).x(), shapeBRot.getRow( 0 ).y(), shapeBRot.getRow( 0 ).z(),
			shapeBRot.getRow( 1 ).x(), shapeBRot.getRow( 1 ).y(), shapeBRot.getRow( 1 ).z(),
			shapeBRot.getRow( 2 ).x(), shapeBRot.getRow( 2 ).y(), shapeBRot.getRow( 2 ).z());
		fputs( str, fp );

		fclose( fp );
#endif //DEBUG_ME
	}
	else if ( key == 'P' || key =='p' )
	{
		g_pauseAnim = !g_pauseAnim;
	}

	defaultKeyboard(key, x, y);
}
Example #4
0
int main(int argc,char** argv)
{
	srand( time( 0 ) );

	g_shapesType[ 0 ] = randomShapeType( 0, 1 );
	g_shapesType[ 1 ] = randomShapeType( 0, 1 );

	( g_shapesType[ 0 ] == 0 ) ? createBoxShape( 0 ) : createSphereShape( 0 );
	( g_shapesType[ 1 ] == 0 ) ? createBoxShape( 1 ) : createSphereShape( 1 );

	g_shapesPenetrate = calcPenDepth();

	return glutmain( argc, argv, screenWidth, screenHeight, "EPAPenDepthDemo" );
}
Example #5
0
b2Body* Box2DManager::addBox(PhysicsParams &param) {
	// ボディの定義
	b2BodyDef def;
	def.position.Set(param.position.x * PPM, param.position.y * PPM);
	def.angle = param.angle;
	def.type = param.type;
	if (param.angle == -1) {
		def.fixedRotation = true;
	}
	
	// シェイプの定義
	b2PolygonShape shape = createBoxShape(param.size.x * PPM, param.size.y * PPM);
	
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &shape;
	fixtureDef.density = param.density;
	fixtureDef.friction = param.friction;
	fixtureDef.restitution = param.restitution;
	fixtureDef.isSensor = param.isSensor;
	
	b2Vec2 pos(param.position.x * PPM, param.position.y * PPM);
	b2Body* body = world->CreateBody(&def);
	body->CreateFixture(&fixtureDef);
	body->ResetMassData();
	
	return body;
}
//-------------------------------------------------------------------------------------
bool OBTutorial2::processUnbufferedInput(const Ogre::FrameEvent& evt)
{
    static float mToggle = 0;

    if (mToggle>0)
        mToggle -= evt.timeSinceLastFrame;

	// create and throw a box if 'B' is pressed
	if(mKeyboard->isKeyDown(OIS::KC_B) && mToggle <=0)
	{
		Vector3 size = Vector3::ZERO;	// size of the box
		// starting position of the box
		Vector3 position = (mCamera->getDerivedPosition() + mCamera->getDerivedDirection().normalisedCopy() * 10);
 
		// create an ordinary, Ogre mesh with texture
	    Entity *entity = mSceneMgr->createEntity(
 					"Box" + StringConverter::toString(mNumEntitiesInstanced),
 					"cube.mesh");			    
		entity->setCastShadows(true);
                createBoxShape(entity, position, false);
		// we need the bounding box of the box to be able to set the size of the Bullet-box
		AxisAlignedBox boundingB = entity->getBoundingBox();
		size = boundingB.getSize(); size /= 2.0f; // only the half needed
		size *= 1.00f;	// Bullet margin is a bit bigger so we need a smaller size
 									// (Bullet 2.76 Physics SDK Manual page 18)
		entity->setMaterialName("Examples/BumpyMetal");
		SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
		node->attachObject(entity);
		node->scale(0.05f, 0.05f, 0.05f);	// the cube is too big for us
		size *= 0.05f;						// don't forget to scale down the Bullet-box too
 
		// after that create the Bullet shape with the calculated size
		/*OgreBulletCollisions::BoxCollisionShape *sceneBoxShape = new OgreBulletCollisions::BoxCollisionShape(size);
		// and the Bullet rigid body
		OgreBulletDynamics::RigidBody *defaultBody = new OgreBulletDynamics::RigidBody(
 					"defaultBoxRigid" + StringConverter::toString(mNumEntitiesInstanced), 
 					mWorld);
		defaultBody->setShape(	node,
 						sceneBoxShape,
 						0.6f,			// dynamic body restitution
 						0.6f,			// dynamic body friction
 						1.0f, 			// dynamic bodymass
 						position,		// starting position of the box
 						Quaternion(0,0,0,1));// orientation of the box
        mNumEntitiesInstanced++;				
 
		defaultBody->setLinearVelocity(
					mCamera->getDerivedDirection().normalisedCopy() * Ogre::Math::RangeRandom(0.7f,20.0f) ); // shooting speed
		// push the created objects to the dequese
		mShapes.push_back(sceneBoxShape);
		mBodies.push_back(defaultBody);		**/		
		mToggle = 0.5;
	}


    return true;
}
Example #7
0
PassOwnPtr<Shape> Shape::createShape(const LayoutSize& logicalSize, const LayoutSize& logicalRadii, WritingMode writingMode, Length margin, Length padding)
{
    FloatRect rect(0, 0, logicalSize.width(), logicalSize.height());
    FloatSize radii(logicalRadii.width(), logicalRadii.height());
    FloatRoundedRect bounds(rect, radii, radii, radii, radii);

    OwnPtr<Shape> shape = createBoxShape(bounds);
    shape->m_writingMode = writingMode;
    shape->m_margin = floatValueForLength(margin, 0);
    shape->m_padding = floatValueForLength(padding, 0);

    return shape.release();
}
void BasicExample::initPhysics()
{
	m_guiHelper->setUpAxis(1);

	createEmptyDynamicsWorld();
	//m_dynamicsWorld->setGravity(btVector3(0,0,0));
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	

	//groundShape->initializePolyhedralFeatures();
	//btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
	
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0));

	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}


	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance

		btBoxShape* colShape = createBoxShape(btVector3(.1,.1,.1));
		

		//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);


		for (int k=0;k<ARRAY_SIZE_Y;k++)
		{
			for (int i=0;i<ARRAY_SIZE_X;i++)
			{
				for(int j = 0;j<ARRAY_SIZE_Z;j++)
				{
					startTransform.setOrigin(btVector3(
										btScalar(0.2*i),
										btScalar(2+.2*k),
										btScalar(0.2*j)));

			
					createRigidBody(mass,startTransform,colShape);
					

				}
			}
		}
	}

	
	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
	
}
Example #9
0
void SimpleJointExample::initPhysics()
{
	m_guiHelper->setUpAxis(1);

	createEmptyDynamicsWorld();
	
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0)); 
	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}


	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance
        btBoxShape* colShape = createBoxShape(btVector3(1,1,1));
		 
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);


		startTransform.setOrigin(btVector3(
								 btScalar(0),
								 btScalar(10),
								 btScalar(0)));
		btRigidBody* dynamicBox = createRigidBody(mass,startTransform,colShape);	

		//create a static rigid body
		mass = 0;
		startTransform.setOrigin(btVector3(
								 btScalar(0),
								 btScalar(20),
								 btScalar(0)));
		
		btRigidBody* staticBox = createRigidBody(mass,startTransform,colShape);	

		//create a simple p2pjoint constraint
		btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*dynamicBox, *staticBox, btVector3(0,3,0), btVector3(0,0,0));
		p2p->m_setting.m_damping = 0.0625;
		p2p->m_setting.m_impulseClamp = 0.95;
		m_dynamicsWorld->addConstraint(p2p);
	}

	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
btCollisionShape* btBulletWorldImporter::convertCollisionShape(  btCollisionShapeData* shapeData  )
{
	btCollisionShape* shape = 0;

	switch (shapeData->m_shapeType)
		{
	case STATIC_PLANE_PROXYTYPE:
		{
			btStaticPlaneShapeData* planeData = (btStaticPlaneShapeData*)shapeData;
			btVector3 planeNormal,localScaling;
			planeNormal.deSerializeFloat(planeData->m_planeNormal);
			localScaling.deSerializeFloat(planeData->m_localScaling);
			shape = createPlaneShape(planeNormal,planeData->m_planeConstant);
			shape->setLocalScaling(localScaling);

			break;
		}
	case GIMPACT_SHAPE_PROXYTYPE:
		{
			btGImpactMeshShapeData* gimpactData = (btGImpactMeshShapeData*) shapeData;
			if (gimpactData->m_gimpactSubType == CONST_GIMPACT_TRIMESH_SHAPE)
			{
				btTriangleIndexVertexArray* meshInterface = createMeshInterface(gimpactData->m_meshInterface);
				btGImpactMeshShape* gimpactShape = createGimpactShape(meshInterface);
				btVector3 localScaling;
				localScaling.deSerializeFloat(gimpactData->m_localScaling);
				gimpactShape->setLocalScaling(localScaling);
				gimpactShape->setMargin(btScalar(gimpactData->m_collisionMargin));
				gimpactShape->updateBound();
				shape = gimpactShape;
			} else
			{
				printf("unsupported gimpact sub type\n");
			}
			break;
		}

		case CYLINDER_SHAPE_PROXYTYPE:
		case CAPSULE_SHAPE_PROXYTYPE:
		case BOX_SHAPE_PROXYTYPE:
		case SPHERE_SHAPE_PROXYTYPE:
		case MULTI_SPHERE_SHAPE_PROXYTYPE:
		case CONVEX_HULL_SHAPE_PROXYTYPE:
			{
				btConvexInternalShapeData* bsd = (btConvexInternalShapeData*)shapeData;
				btVector3 implicitShapeDimensions;
				implicitShapeDimensions.deSerializeFloat(bsd->m_implicitShapeDimensions);
				btVector3 localScaling;
				localScaling.deSerializeFloat(bsd->m_localScaling);
				btVector3 margin(bsd->m_collisionMargin,bsd->m_collisionMargin,bsd->m_collisionMargin);
				switch (shapeData->m_shapeType)
				{
					case BOX_SHAPE_PROXYTYPE:
						{
							shape = createBoxShape(implicitShapeDimensions/localScaling+margin);
							break;
						}
					case SPHERE_SHAPE_PROXYTYPE:
						{
							shape = createSphereShape(implicitShapeDimensions.getX());
							break;
						}
					case CAPSULE_SHAPE_PROXYTYPE:
						{
							btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData;
							switch (capData->m_upAxis)
							{
							case 0:
								{
									shape = createCapsuleShapeX(implicitShapeDimensions.getY(),2*implicitShapeDimensions.getX());
									break;
								}
							case 1:
								{
									shape = createCapsuleShapeY(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getY());
									break;
								}
							case 2:
								{
									shape = createCapsuleShapeZ(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getZ());
									break;
								}
							default:
								{
									printf("error: wrong up axis for btCapsuleShape\n");
								}

							};
							
							break;
						}
					case CYLINDER_SHAPE_PROXYTYPE:
						{
							btCylinderShapeData* cylData = (btCylinderShapeData*) shapeData;
							btVector3 halfExtents = implicitShapeDimensions+margin;
							switch (cylData->m_upAxis)
							{
							case 0:
								{
									shape = createCylinderShapeX(halfExtents.getY(),halfExtents.getX());
									break;
								}
							case 1:
								{
									shape = createCylinderShapeY(halfExtents.getX(),halfExtents.getY());
									break;
								}
							case 2:
								{
									shape = createCylinderShapeZ(halfExtents.getX(),halfExtents.getZ());
									break;
								}
							default:
								{
									printf("unknown Cylinder up axis\n");
								}

							};
							

							
							break;
						}
					case MULTI_SPHERE_SHAPE_PROXYTYPE:
						{
							btMultiSphereShapeData* mss = (btMultiSphereShapeData*)bsd;
							int numSpheres = mss->m_localPositionArraySize;

							btAlignedObjectArray<btVector3> tmpPos;
							btAlignedObjectArray<btScalar> radii;
							radii.resize(numSpheres);
							tmpPos.resize(numSpheres);
							int i;
							for ( i=0;i<numSpheres;i++)
							{
								tmpPos[i].deSerializeFloat(mss->m_localPositionArrayPtr[i].m_pos);
								radii[i] = mss->m_localPositionArrayPtr[i].m_radius;
							}
							shape = new btMultiSphereShape(&tmpPos[0],&radii[0],numSpheres);
							break;
						}
					case CONVEX_HULL_SHAPE_PROXYTYPE:
						{
						//	int sz = sizeof(btConvexHullShapeData);
						//	int sz2 = sizeof(btConvexInternalShapeData);
						//	int sz3 = sizeof(btCollisionShapeData);
							btConvexHullShapeData* convexData = (btConvexHullShapeData*)bsd;
							int numPoints = convexData->m_numUnscaledPoints;

							btAlignedObjectArray<btVector3> tmpPoints;
							tmpPoints.resize(numPoints);
							int i;
							for ( i=0;i<numPoints;i++)
							{
#ifdef BT_USE_DOUBLE_PRECISION
							if (convexData->m_unscaledPointsDoublePtr)
								tmpPoints[i].deSerialize(convexData->m_unscaledPointsDoublePtr[i]);
							if (convexData->m_unscaledPointsFloatPtr)
								tmpPoints[i].deSerializeFloat(convexData->m_unscaledPointsFloatPtr[i]);
#else
							if (convexData->m_unscaledPointsFloatPtr)
								tmpPoints[i].deSerialize(convexData->m_unscaledPointsFloatPtr[i]);
							if (convexData->m_unscaledPointsDoublePtr)
								tmpPoints[i].deSerializeDouble(convexData->m_unscaledPointsDoublePtr[i]);
#endif //BT_USE_DOUBLE_PRECISION
							}
							btConvexHullShape* hullShape = createConvexHullShape();
							for (i=0;i<numPoints;i++)
							{
								hullShape->addPoint(tmpPoints[i]);
							}
							shape = hullShape;
							break;
						}
					default:
						{
							printf("error: cannot create shape type (%d)\n",shapeData->m_shapeType);
						}
				}

				if (shape)
				{
					shape->setMargin(bsd->m_collisionMargin);
					btVector3 localScaling;
					localScaling.deSerializeFloat(bsd->m_localScaling);
					shape->setLocalScaling(localScaling);
					
				}
				break;
			}
		case TRIANGLE_MESH_SHAPE_PROXYTYPE:
		{
			btTriangleMeshShapeData* trimesh = (btTriangleMeshShapeData*)shapeData;
			btTriangleIndexVertexArray* meshInterface = createMeshInterface(trimesh->m_meshInterface);
			if (!meshInterface->getNumSubParts())
			{
				return 0;
			}

			btVector3 scaling; scaling.deSerializeFloat(trimesh->m_meshInterface.m_scaling);
			meshInterface->setScaling(scaling);


			btOptimizedBvh* bvh = 0;
#if 0
			if (trimesh->m_quantizedFloatBvh)
			{
				btOptimizedBvh** bvhPtr = m_bvhMap.find(trimesh->m_quantizedFloatBvh);
				if (bvhPtr && *bvhPtr)
				{
					bvh = *bvhPtr;
				} else
				{
					bvh = createOptimizedBvh();
					bvh->deSerializeFloat(*trimesh->m_quantizedFloatBvh);
				}
			}
			if (trimesh->m_quantizedDoubleBvh)
			{
				btOptimizedBvh** bvhPtr = m_bvhMap.find(trimesh->m_quantizedDoubleBvh);
				if (bvhPtr && *bvhPtr)
				{
					bvh = *bvhPtr;
				} else
				{
					bvh = createOptimizedBvh();
					bvh->deSerializeDouble(*trimesh->m_quantizedDoubleBvh);
				}
			}
#endif


			btBvhTriangleMeshShape* trimeshShape = createBvhTriangleMeshShape(meshInterface,bvh);
			trimeshShape->setMargin(trimesh->m_collisionMargin);
			shape = trimeshShape;

			if (trimesh->m_triangleInfoMap)
			{
				btTriangleInfoMap* map = createTriangleInfoMap();
				map->deSerialize(*trimesh->m_triangleInfoMap);
				trimeshShape->setTriangleInfoMap(map);

#ifdef USE_INTERNAL_EDGE_UTILITY
				gContactAddedCallback = btAdjustInternalEdgeContactsCallback;
#endif //USE_INTERNAL_EDGE_UTILITY

			}

			//printf("trimesh->m_collisionMargin=%f\n",trimesh->m_collisionMargin);
			break;
		}
		case COMPOUND_SHAPE_PROXYTYPE:
			{
				btCompoundShapeData* compoundData = (btCompoundShapeData*)shapeData;
				btCompoundShape* compoundShape = createCompoundShape();


				btAlignedObjectArray<btCollisionShape*> childShapes;
				for (int i=0;i<compoundData->m_numChildShapes;i++)
				{
					btCollisionShape* childShape = convertCollisionShape(compoundData->m_childShapePtr[i].m_childShape);
					if (childShape)
					{
						btTransform localTransform;
						localTransform.deSerializeFloat(compoundData->m_childShapePtr[i].m_transform);
						compoundShape->addChildShape(localTransform,childShape);
					} else
					{
						printf("error: couldn't create childShape for compoundShape\n");
					}
					
				}
				shape = compoundShape;

				break;
			}
		default:
			{
				printf("unsupported shape type (%d)\n",shapeData->m_shapeType);
			}
		}

		return shape;
	
}
Example #11
0
void InclinedPlaneExample::initPhysics()
{

	{ // create slider to change the ramp tilt
    SliderParams slider("Ramp Tilt",&gTilt);
    slider.m_minVal=0;
    slider.m_maxVal=SIMD_PI/2.0f;
    slider.m_clampToNotches = false;
    slider.m_callback = onRampInclinationChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the ramp friction
    SliderParams slider("Ramp Friction",&gRampFriction);
    slider.m_minVal=0;
    slider.m_maxVal=10;
    slider.m_clampToNotches = false;
    slider.m_callback = onRampFrictionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the ramp restitution
    SliderParams slider("Ramp Restitution",&gRampRestitution);
    slider.m_minVal=0;
    slider.m_maxVal=1;
    slider.m_clampToNotches = false;
    slider.m_callback = onRampRestitutionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the box friction
    SliderParams slider("Box Friction",&gBoxFriction);
    slider.m_minVal=0;
    slider.m_maxVal=10;
    slider.m_clampToNotches = false;
    slider.m_callback = onBoxFrictionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the box restitution
    SliderParams slider("Box Restitution",&gBoxRestitution);
    slider.m_minVal=0;
    slider.m_maxVal=1;
    slider.m_clampToNotches = false;
    slider.m_callback = onBoxRestitutionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the sphere friction
    SliderParams slider("Sphere Friction",&gSphereFriction);
    slider.m_minVal=0;
    slider.m_maxVal=10;
    slider.m_clampToNotches = false;
    slider.m_callback = onSphereFrictionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

    { // create slider to change the sphere rolling friction
    SliderParams slider("Sphere Rolling Friction",&gSphereRollingFriction);
    slider.m_minVal=0;
    slider.m_maxVal=10;
    slider.m_clampToNotches = false;
    slider.m_callback = onSphereRestitutionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

	{ // create slider to change the sphere rolling friction
    SliderParams slider("Sphere Spinning",&gSphereSpinningFriction);
    slider.m_minVal=0;
    slider.m_maxVal=2;
    slider.m_clampToNotches = false;
    slider.m_callback = onSphereRestitutionChanged;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }
	

    { // create slider to change the sphere restitution
    SliderParams slider("Sphere Restitution",&gSphereRestitution);
    slider.m_minVal=0;
    slider.m_maxVal=1;
    slider.m_clampToNotches = false;
    m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
    }

	m_guiHelper->setUpAxis(1); // set Y axis as up axis

	createEmptyDynamicsWorld();
	
	// create debug drawer
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);


	{ // create a static ground
		btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
		m_collisionShapes.push_back(groundShape);

		btTransform groundTransform;
		groundTransform.setIdentity();
		groundTransform.setOrigin(btVector3(0,-50,0));

		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}

	{ //create a static inclined plane
		btBoxShape* inclinedPlaneShape = createBoxShape(btVector3(btScalar(20.),btScalar(1.),btScalar(10.)));
		m_collisionShapes.push_back(inclinedPlaneShape);

		btTransform startTransform;
		startTransform.setIdentity();

		// position the inclined plane above ground
		startTransform.setOrigin(btVector3(
								 btScalar(0),
								 btScalar(15),
								 btScalar(0)));

		btQuaternion incline;
		incline.setRotation(btVector3(0,0,1),gTilt);
		startTransform.setRotation(incline);

		btScalar mass(0.);
		ramp = createRigidBody(mass,startTransform,inclinedPlaneShape);
		ramp->setFriction(gRampFriction);
		ramp->setRestitution(gRampRestitution);
	}


	{ //create a cube above the inclined plane
        btBoxShape* boxShape = createBoxShape(btVector3(1,1,1));
		 
		m_collisionShapes.push_back(boxShape);

		btTransform startTransform;
		startTransform.setIdentity();

		btScalar boxMass(1.f);

		startTransform.setOrigin(
			btVector3(btScalar(0), btScalar(20), btScalar(2)));

		gBox = createRigidBody(boxMass, startTransform, boxShape);
		gBox->forceActivationState(DISABLE_DEACTIVATION); // to prevent the box on the ramp from disabling
		gBox->setFriction(gBoxFriction);
		gBox->setRestitution(gBoxRestitution);
	}

	{ //create a sphere above the inclined plane
        btSphereShape* sphereShape = new btSphereShape(btScalar(1));

		m_collisionShapes.push_back(sphereShape);

		btTransform startTransform;
		startTransform.setIdentity();

		btScalar sphereMass(1.f);

		startTransform.setOrigin(
			btVector3(btScalar(0), btScalar(20), btScalar(4)));

		gSphere = createRigidBody(sphereMass, startTransform, sphereShape);
		gSphere->forceActivationState(DISABLE_DEACTIVATION); // to prevent the sphere on the ramp from disabling
		gSphere->setFriction(gSphereFriction);
		gSphere->setRestitution(gSphereRestitution);
		gSphere->setRollingFriction(gSphereRollingFriction);
		gSphere->setSpinningFriction(gSphereSpinningFriction);

	}

	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
void BasicDemoPhysicsSetup::initPhysics()
{
		///collision configuration contains default setup for memory, collision setup
	m_collisionConfiguration = new btDefaultCollisionConfiguration();
	//m_collisionConfiguration->setConvexConvexMultipointIterations();

	///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
	m_dispatcher = new	btCollisionDispatcher(m_collisionConfiguration);

	m_broadphase = new btDbvtBroadphase();

	///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
	btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
	m_solver = sol;

	m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
	
	
	m_dynamicsWorld->setGravity(btVector3(0,-10,0));

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	//groundShape->initializePolyhedralFeatures();
//	btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
	
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0));

	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}


	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance

		btBoxShape* colShape = createBoxShape(btVector3(1,1,1));
		//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);


		for (int k=0;k<ARRAY_SIZE_Y;k++)
		{
			for (int i=0;i<ARRAY_SIZE_X;i++)
			{
				for(int j = 0;j<ARRAY_SIZE_Z;j++)
				{
					startTransform.setOrigin(btVector3(
										btScalar(2.0*i),
										btScalar(20+2.0*k),
										btScalar(2.0*j)));

			
					createRigidBody(mass,startTransform,colShape);
				}
			}
		}
	}


}
void RigidBodySoftContact::initPhysics()
{
    
    
	m_guiHelper->setUpAxis(1);

	//createEmptyDynamicsWorld();
	{
		///collision configuration contains default setup for memory, collision setup
		m_collisionConfiguration = new btDefaultCollisionConfiguration();
		//m_collisionConfiguration->setConvexConvexMultipointIterations();

		///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
		m_dispatcher = new	btCollisionDispatcher(m_collisionConfiguration);

		m_broadphase = new btDbvtBroadphase();

		///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
		btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
		//btMLCPSolver* sol = new btMLCPSolver(new btSolveProjectedGaussSeidel());
		m_solver = sol;

		m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);

		m_dynamicsWorld->setGravity(btVector3(0, -10, 0));
	}
	
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);
	m_dynamicsWorld->getSolverInfo().m_erp2 = 0.f;
	m_dynamicsWorld->getSolverInfo().m_globalCfm = 0.f;
	m_dynamicsWorld->getSolverInfo().m_numIterations = 3;
	m_dynamicsWorld->getSolverInfo().m_solverMode = SOLVER_SIMD;// | SOLVER_RANDMIZE_ORDER;
	m_dynamicsWorld->getSolverInfo().m_splitImpulse = false;
	
	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	

	//groundShape->initializePolyhedralFeatures();
//	btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
	
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0));

	{
		btScalar mass(0.);
		btRigidBody* body = createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
        
        body->setContactStiffnessAndDamping(300,10);
		
	}


	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance

		//btBoxShape* colShape = createBoxShape(btVector3(1,1,1));
		

		btCollisionShape* childShape = new btSphereShape(btScalar(0.5));
		btCompoundShape* colShape = new btCompoundShape();
		colShape->addChildShape(btTransform::getIdentity(),childShape);

		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();
		
		startTransform.setRotation(btQuaternion(btVector3(1,1,1),SIMD_PI/10.));
		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);


		for (int k=0;k<ARRAY_SIZE_Y;k++)
		{
			for (int i=0;i<ARRAY_SIZE_X;i++)
			{
				for(int j = 0;j<ARRAY_SIZE_Z;j++)
				{
					startTransform.setOrigin(btVector3(
										btScalar(2.0*i+0.1),
										btScalar(3+2.0*k),
										btScalar(2.0*j)));

			
					btRigidBody* body = createRigidBody(mass,startTransform,colShape);
					//body->setAngularVelocity(btVector3(1,1,1));
					

				}
			}
		}
	}

	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
Example #14
0
int b3BulletDataExtractor::convertCollisionShape(  Bullet3SerializeBullet2::b3CollisionShapeData* shapeData  )
{
	int shapeIndex = -1;

	switch (shapeData->m_shapeType)
		{
	case STATIC_PLANE_PROXYTYPE:
		{
			Bullet3SerializeBullet2::b3StaticPlaneShapeData* planeData = (Bullet3SerializeBullet2::b3StaticPlaneShapeData*)shapeData;
			shapeIndex = createPlaneShape(planeData->m_planeNormal,planeData->m_planeConstant, planeData->m_localScaling);
			break;
		}

		case CYLINDER_SHAPE_PROXYTYPE:
		case CAPSULE_SHAPE_PROXYTYPE:
		case BOX_SHAPE_PROXYTYPE:
		case SPHERE_SHAPE_PROXYTYPE:
		case MULTI_SPHERE_SHAPE_PROXYTYPE:
		case CONVEX_HULL_SHAPE_PROXYTYPE:
			{
				Bullet3SerializeBullet2::b3ConvexInternalShapeData* bsd = (Bullet3SerializeBullet2::b3ConvexInternalShapeData*)shapeData;
				
				switch (shapeData->m_shapeType)
				{
					case BOX_SHAPE_PROXYTYPE:
						{
							shapeIndex = createBoxShape(bsd->m_implicitShapeDimensions, bsd->m_localScaling,bsd->m_collisionMargin);
							break;
						}
					case SPHERE_SHAPE_PROXYTYPE:
						{
							shapeIndex = createSphereShape(bsd->m_implicitShapeDimensions.m_floats[0],bsd->m_localScaling, bsd->m_collisionMargin);
							break;
						}
					case CONVEX_HULL_SHAPE_PROXYTYPE:
						{
							Bullet3SerializeBullet2::b3ConvexHullShapeData* convexData = (Bullet3SerializeBullet2::b3ConvexHullShapeData*)bsd;
							int numPoints = convexData->m_numUnscaledPoints;
							b3Vector3 localScaling;
							localScaling.deSerializeFloat((b3Vector3FloatData&)bsd->m_localScaling);
							b3AlignedObjectArray<b3Vector3> tmpPoints;
							int i;
							if (convexData->m_unscaledPointsFloatPtr)
							{
								for ( i=0;i<numPoints;i++)
								{
									b3Vector3 pt = b3MakeVector3(convexData->m_unscaledPointsFloatPtr[i].m_floats[0],
										convexData->m_unscaledPointsFloatPtr[i].m_floats[1],
										convexData->m_unscaledPointsFloatPtr[i].m_floats[2]);//convexData->m_unscaledPointsFloatPtr[i].m_floats[3]);
									
									tmpPoints.push_back(pt*localScaling);
								}
							}
							float unitScaling[4] = {1,1,1,1};


							int strideInBytes = sizeof(b3Vector3);
							strideInBytes = 4*sizeof(float);
							int noHeightField = 1;
							shapeIndex  = m_np.registerConvexHullShape(&tmpPoints[0].m_floats[0],strideInBytes, numPoints,&unitScaling[0]);

							printf("createConvexHull with %d vertices\n",numPoints);

							GraphicsShape* gfxShape = createGraphicsShapeFromConvexHull(&tmpPoints[0],tmpPoints.size());
							m_graphicsShapes.push_back(gfxShape);

							return shapeIndex;
							break;
						}
#if 0
					case CAPSULE_SHAPE_PROXYTYPE:
						{
							b3CapsuleShapeData* capData = (b3CapsuleShapeData*)shapeData;
							switch (capData->m_upAxis)
							{
							case 0:
								{
									shape = createCapsuleShapeX(implicitShapeDimensions.getY(),2*implicitShapeDimensions.getX());
									break;
								}
							case 1:
								{
									shape = createCapsuleShapeY(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getY());
									break;
								}
							case 2:
								{
									shape = createCapsuleShapeZ(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getZ());
									break;
								}
							default:
								{
									printf("error: wrong up axis for b3CapsuleShape\n");
								}

							};
							
							break;
						}
					case CYLINDER_SHAPE_PROXYTYPE:
						{
							b3CylinderShapeData* cylData = (b3CylinderShapeData*) shapeData;
							b3Vector3 halfExtents = implicitShapeDimensions+margin;
							switch (cylData->m_upAxis)
							{
							case 0:
								{
									shape = createCylinderShapeX(halfExtents.getY(),halfExtents.getX());
									break;
								}
							case 1:
								{
									shape = createCylinderShapeY(halfExtents.getX(),halfExtents.getY());
									break;
								}
							case 2:
								{
									shape = createCylinderShapeZ(halfExtents.getX(),halfExtents.getZ());
									break;
								}
							default:
								{
									printf("unknown Cylinder up axis\n");
								}

							};
							

							
							break;
						}
					case MULTI_SPHERE_SHAPE_PROXYTYPE:
						{
							b3MultiSphereShapeData* mss = (b3MultiSphereShapeData*)bsd;
							int numSpheres = mss->m_localPositionArraySize;
							int i;
							for ( i=0;i<numSpheres;i++)
							{
								tmpPos[i].deSerializeFloat(mss->m_localPositionArrayPtr[i].m_pos);
								radii[i] = mss->m_localPositionArrayPtr[i].m_radius;
							}
							shape = new b3MultiSphereShape(&tmpPos[0],&radii[0],numSpheres);
							break;
						}
			
#endif

					default:
						{
							printf("error: cannot create shape type (%d)\n",shapeData->m_shapeType);
						}
				}

				break;
			}

		case TRIANGLE_MESH_SHAPE_PROXYTYPE:
		{
			Bullet3SerializeBullet2::b3TriangleMeshShapeData* trimesh = (Bullet3SerializeBullet2::b3TriangleMeshShapeData*)shapeData;
			printf("numparts = %d\n",trimesh->m_meshInterface.m_numMeshParts);
			if (trimesh->m_meshInterface.m_numMeshParts)
			{
				for (int i=0;i<trimesh->m_meshInterface.m_numMeshParts;i++)
				{
					Bullet3SerializeBullet2::b3MeshPartData& dat = trimesh->m_meshInterface.m_meshPartsPtr[i];
					printf("numtris = %d, numverts = %d\n", dat.m_numTriangles,dat.m_numVertices);//,dat.m_vertices3f,dat.m_3indices16
					printf("scaling = %f,%f,%f\n", trimesh->m_meshInterface.m_scaling.m_floats[0],trimesh->m_meshInterface.m_scaling.m_floats[1],trimesh->m_meshInterface.m_scaling.m_floats[2]);
					//	dat.
					//dat.

				}
					
				///trimesh->m_meshInterface.m_meshPartsPtr
				//trimesh->m_meshInterface.m_scaling
			}
			//trimesh->m_meshInterface
			//b3TriangleIndexVertexArray* meshInterface = createMeshInterface(trimesh->m_meshInterface);
			

			//scaling
			//b3Vector3 scaling; scaling.deSerializeFloat(trimesh->m_meshInterface.m_scaling);
			//meshInterface->setScaling(scaling);

			//printf("trimesh->m_collisionMargin=%f\n",trimesh->m_collisionMargin);
			break;
		}

#if 0
		case COMPOUND_SHAPE_PROXYTYPE:
			{
				b3CompoundShapeData* compoundData = (b3CompoundShapeData*)shapeData;
				b3CompoundShape* compoundShape = createCompoundShape();


				b3AlignedObjectArray<b3CollisionShape*> childShapes;
				for (int i=0;i<compoundData->m_numChildShapes;i++)
				{
					b3CollisionShape* childShape = convertCollisionShape(compoundData->m_childShapePtr[i].m_childShape);
					if (childShape)
					{
						b3Transform localTransform;
						localTransform.deSerializeFloat(compoundData->m_childShapePtr[i].m_transform);
						compoundShape->addChildShape(localTransform,childShape);
					} else
					{
						printf("error: couldn't create childShape for compoundShape\n");
					}
					
				}
				shape = compoundShape;

				break;
			}

			case GIMPACT_SHAPE_PROXYTYPE:
		{
			b3GImpactMeshShapeData* gimpactData = (b3GImpactMeshShapeData*) shapeData;
			if (gimpactData->m_gimpactSubType == CONST_GIMPACT_TRIMESH_SHAPE)
			{
				b3TriangleIndexVertexArray* meshInterface = createMeshInterface(gimpactData->m_meshInterface);
				b3GImpactMeshShape* gimpactShape = createGimpactShape(meshInterface);
				b3Vector3 localScaling;
				localScaling.deSerializeFloat(gimpactData->m_localScaling);
				gimpactShape->setLocalScaling(localScaling);
				gimpactShape->setMargin(b3Scalar(gimpactData->m_collisionMargin));
				gimpactShape->updateBound();
				shape = gimpactShape;
			} else
			{
				printf("unsupported gimpact sub type\n");
			}
			break;
		}
		case SOFTBODY_SHAPE_PROXYTYPE:
			{
				return 0;
			}
#endif 
		default:
			{
				printf("unsupported shape type (%d)\n",shapeData->m_shapeType);
			}
		}

		return shapeIndex;
	
}
hkpRigidBody* DestructibleBridgeUtil::createAirplane(const AirplaneData& data)
{

	//
	// create all necessary shapes that make up our airplane
	//
	hkArray<hkpShape*> shapes;
	{
		// create airplane's body
		{
			hkpBoxShape* bodyShape = createBoxShape(AIRPLANE_BODY_WIDTH, AIRPLANE_BODY_HEIGHT, AIRPLANE_BODY_LENGTH, data.m_wingSpan);
			createConvexTranslateShapeAndAddToArray(bodyShape, 0.0f, 0.0f, 0.0f, data.m_wingSpan, shapes);
			bodyShape->removeReference();
		}

		// create airplane's left and right wing
		{
			hkpBoxShape* wingShape = createBoxShape(AIRPLANE_WING_LENGTH, AIRPLANE_WING_HEIGHT, AIRPLANE_WING_WIDTH, data.m_wingSpan);
			createConvexTranslateShapeAndAddToArray(wingShape, -AIRPLANE_WING_LENGTH * 0.5f, (AIRPLANE_BODY_HEIGHT+AIRPLANE_WING_HEIGHT) * 0.5f, AIRPLANE_BODY_LENGTH / 6.0f, data.m_wingSpan, shapes);
			createConvexTranslateShapeAndAddToArray(wingShape,  AIRPLANE_WING_LENGTH * 0.5f, (AIRPLANE_BODY_HEIGHT+AIRPLANE_WING_HEIGHT) * 0.5f, AIRPLANE_BODY_LENGTH / 6.0f, data.m_wingSpan, shapes);
			wingShape->removeReference();
		}

		// create airplane's tail wing
		{
			hkpBoxShape* tailWingShape = createBoxShape(AIRPLANE_TAIL_WIDTH, AIRPLANE_TAIL_HEIGHT, AIRPLANE_TAIL_LENGTH, data.m_wingSpan);
			createConvexTranslateShapeAndAddToArray(tailWingShape, 0.0f, (AIRPLANE_BODY_HEIGHT+AIRPLANE_WING_HEIGHT) * 0.5f, -AIRPLANE_BODY_LENGTH * 0.5f, data.m_wingSpan, shapes);
			tailWingShape->removeReference();
		}

		// create airplane's rudder
		{
			hkpBoxShape* rudderShape = createBoxShape(AIRPLANE_RUDDER_WIDTH, AIRPLANE_RUDDER_HEIGHT, AIRPLANE_RUDDER_LENGTH, data.m_wingSpan);
			createConvexTranslateShapeAndAddToArray(rudderShape, 0.0f, (AIRPLANE_BODY_HEIGHT+AIRPLANE_RUDDER_HEIGHT) * 0.5f, -AIRPLANE_BODY_LENGTH * 0.5f, data.m_wingSpan, shapes);
			rudderShape->removeReference();
		}

		// create the bombs
		{
			hkpBoxShape* bombShape = createBoxShape(AIRPLANE_BOMB_WIDTH, AIRPLANE_BOMB_HEIGHT, AIRPLANE_BOMB_LENGTH, data.m_wingSpan);

			{
				hkReal distance = (AIRPLANE_WING_LENGTH*2.0f) / AIRPLANE_NUM_BOMBS;
				hkReal posX = AIRPLANE_WING_LENGTH-AIRPLANE_BOMB_WIDTH;
				{
					for (int i=0; i<AIRPLANE_NUM_BOMBS; i++)
					{
						createConvexTranslateShapeAndAddToArray(bombShape, posX, (AIRPLANE_BODY_HEIGHT-AIRPLANE_BOMB_HEIGHT) * 0.5f, AIRPLANE_BODY_LENGTH / 6.0f, data.m_wingSpan, shapes);
						posX -= distance;
					}
				}
			}

			bombShape->removeReference();
		}
	}

	//
	// create the complete shape for the airplane
	//
	hkpShape* airplaneShape;
	{
#if defined(USE_MOPP_FOR_AIRPLANE)
		hkpListShape* listShape = new hkpListShape(shapes.begin(), shapes.getSize());

		hkpMoppCompilerInput mci;
		mci.m_enableChunkSubdivision = true;

		hkpMoppCode* code = hkpMoppUtility::buildCode( listShape , mci);
		airplaneShape = new hkpMoppBvTreeShape(listShape, code);
		listShape->removeReference();
#elif defined(USE_CONVEX_LIST_SHAPE_FOR_AIRPLANE)
		airplaneShape = new hkpConvexListShape( (const hkpConvexShape*const*)shapes.begin(), shapes.getSize());
#else // if defined(USE_LIST_SHAPE_FOR_AIRPLANE)
		airplaneShape = new hkpListShape(shapes.begin(), shapes.getSize());
#endif

		{
			for (int i=0; i<shapes.getSize(); i++)
			{
				shapes[i]->removeReference();
			}
		}
	}

	//
	// create airplane
	//
	hkVector4 airplaneDirection;
	hkpRigidBody* airplane;
	{
		hkpRigidBodyCinfo planeInfo;
		{
			planeInfo.m_shape			= airplaneShape;
			planeInfo.m_position		= data.m_position;
			planeInfo.m_motionType		= hkpMotion::MOTION_DYNAMIC;
			planeInfo.m_friction		= 0.5f;
			planeInfo.m_qualityType		= HK_COLLIDABLE_QUALITY_MOVING;
			planeInfo.m_angularDamping	= 0.7f;
			hkpInertiaTensorComputer::setShapeVolumeMassProperties(airplaneShape, data.m_mass, planeInfo);
		}

		airplaneDirection = data.m_destination;
		airplaneDirection.sub4(data.m_position);
		airplaneDirection.normalize3();

		hkRotation rotation;
		{
			hkVector4 upVector(0.0f, 1.0f, 0.0f);
			hkVector4Util::buildOrthonormal(airplaneDirection, upVector, rotation);
			rotation.getColumn(2).setNeg4(rotation.getColumn(2));
			hkAlgorithm::swap16(rotation.getColumn(0), rotation.getColumn(2));
		}
		planeInfo.m_rotation.setAndNormalize(rotation);

		airplane = new hkpRigidBody(planeInfo);

		airplaneShape->removeReference();
	}

	//
	// push airplane
	//
	{
		hkVector4 velocityVec;
		velocityVec.setMul4( data.m_velocity, airplaneDirection );
		airplane->setLinearVelocity( velocityVec );
	}

	return airplane;
}
//-------------------------------------------------------------------------------------
void OBTutorial2::createScene(void)
{

    mCamera->setPosition(Vector3(0,18,70));
    mCamera->lookAt(Vector3(0,0,-300));
    mCamera->setNearClipDistance(5);

    mSceneMgr->setAmbientLight(Ogre::ColourValue(0.9, 0.9, 0.9));


    // Start Bullet
    mWorld = new btDiscreteDynamicsWorld(mDispatcher,  // gravity vector for Bullet
                                mBroadphase, mSolver, mCollisionConfiguration );
 
    // add Debug info display tool
 	//debugDrawer = new OgreBulletCollisions::DebugDrawer();
 	//debugDrawer->setDrawWireframe(true);	// we want to see the Bullet containers
 
 	//mWorld->setDebugDrawer(debugDrawer);
 	//mWorld->setShowDebugShapes(true);		// enable it if you want to see the Bullet containers
 	//SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode("debugDrawer", Ogre::Vector3::ZERO);
 	//node->attachObject(static_cast <SimpleRenderable *> (debugDrawer));
 
    // Define a floor plane mesh
 	Entity *ent;
    Plane p;
    p.normal = Vector3(0,1,0); p.d = 0;
    MeshManager::getSingleton().createPlane("FloorPlane", 
                          ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
                          p, 200000, 200000, 20, 20, true, 1, 9000, 9000, 
                          Vector3::UNIT_Z);
    // Create an entity (the floor)
    ent = mSceneMgr->createEntity("floor", "FloorPlane");
 	ent->setMaterialName("Examples/BumpyMetal");
    mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent);
 
 	// add collision detection to it
 	btCollisionShape *Shape;
 	Shape = new btStaticPlaneShape(toBulletVector(Ogre::Vector3(0,1,0)), 0); // (normal vector, distance)
 	// a body is needed for the shape
        MyMotionState * defaultMotionState = new MyMotionState(btTransform(btQuaternion(btScalar(0),btScalar(0),btScalar(0),btScalar(1))), ent->getParentSceneNode());
        btRigidBody *defaultBody = new btRigidBody(btScalar(1), defaultMotionState, Shape);
 	btRigidBody *defaultPlaneBody = new btRigidBody(btScalar(0), defaultMotionState, Shape);
 	//defaultPlaneBody->setStaticShape(Shape, 0.1, 0.8);// (shape, restitution, friction)
 	// push the created objects to the deques
 	mShapes.push_back(Shape);
 	mBodies.push_back(defaultPlaneBody);


 	// create an cube mesh
 	Entity *entity = mSceneMgr->createEntity(
 					"Box" + StringConverter::toString(mNumEntitiesInstanced),
 					"cube.mesh");			    
 	entity->setMaterialName("Examples/BumpyMetal");
       Ogre::SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
 	node->attachObject(entity);
 	node->scale(0.05f, 0.05f, 0.05f);	// the cube is too big for us
	createBoxShape(entity, Ogre::Vector3(0.0,0.0,0.0), false);


}
Example #17
0
void BridgeExample::initPhysics()
{
	m_guiHelper->setUpAxis(1);

	createEmptyDynamicsWorld();
	
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	if (m_dynamicsWorld->getDebugDrawer())
		m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0)); 
	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}

	//create two fixed boxes to hold the planks



	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance
		btScalar plankWidth = 0.4;
		btScalar plankHeight = 0.2;
		btScalar plankBreadth = 1;
		btScalar plankOffset = plankWidth; //distance between two planks
		btScalar bridgeWidth = plankWidth*TOTAL_PLANKS + plankOffset*(TOTAL_PLANKS-1);
		btScalar bridgeHeight = 5;
		btScalar halfBridgeWidth = bridgeWidth*0.5f;

        btBoxShape* colShape = createBoxShape(btVector3(plankWidth,plankHeight,plankBreadth));
		 
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);

		//create a set of boxes to represent bridge 
		btAlignedObjectArray<btRigidBody*> boxes;
		int lastBoxIndex = TOTAL_PLANKS-1;
		for(int i=0;i<TOTAL_PLANKS;++i) {
			float t =   float(i)/lastBoxIndex;
			t = -(t*2-1.0f) * halfBridgeWidth;
			startTransform.setOrigin(btVector3(									 
									 btScalar(t),
									 bridgeHeight,
									 btScalar(0)
									 )
									 );
			boxes.push_back(createRigidBody((i==0 || i==lastBoxIndex)?0:mass,startTransform,colShape));		  
		} 
		 
		
		//add N-1 spring constraints
		for(int i=0;i<TOTAL_PLANKS-1;++i) {
			btRigidBody* b1 = boxes[i];
			btRigidBody* b2 = boxes[i+1];
			 
			btPoint2PointConstraint* leftSpring = new btPoint2PointConstraint(*b1, *b2, btVector3(-0.5,0,-0.5), btVector3(0.5,0,-0.5));
			m_dynamicsWorld->addConstraint(leftSpring);
			 
			btPoint2PointConstraint* rightSpring = new btPoint2PointConstraint(*b1, *b2, btVector3(-0.5,0,0.5), btVector3(0.5,0,0.5));
			m_dynamicsWorld->addConstraint(rightSpring);
		}
	}

	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
void RigidBodyFromObjExample::initPhysics()
{
	m_guiHelper->setUpAxis(1);

	createEmptyDynamicsWorld();
	
	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

	//if (m_dynamicsWorld->getDebugDrawer())
	//	m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);

	///create a few basic rigid bodies
	btBoxShape* groundShape = createBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
	m_collisionShapes.push_back(groundShape);

	btTransform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(btVector3(0,-50,0)); 
	{
		btScalar mass(0.);
		createRigidBody(mass,groundTransform,groundShape, btVector4(0,0,1,1));
	}

	//load our obj mesh
	const char* fileName = "teddy.obj";//sphere8.obj";//sponza_closed.obj";//sphere8.obj";
    char relativeFileName[1024];
    if (b3ResourcePath::findResourcePath(fileName, relativeFileName, 1024))
    {
		char pathPrefix[1024];
		b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
	}
	
	GLInstanceGraphicsShape* glmesh = LoadMeshFromObj(relativeFileName, "");
	printf("[INFO] Obj loaded: Extracted %d verticed from obj file [%s]\n", glmesh->m_numvertices, fileName);

	const GLInstanceVertex& v = glmesh->m_vertices->at(0);
	btConvexHullShape* shape = new btConvexHullShape((const btScalar*)(&(v.xyzw[0])), glmesh->m_numvertices, sizeof(GLInstanceVertex));

	float scaling[4] = {0.1,0.1,0.1,1};
	
	btVector3 localScaling(scaling[0],scaling[1],scaling[2]);
	shape->setLocalScaling(localScaling);
	    
    if (m_options & OptimizeConvexObj)
    {
        shape->optimizeConvexHull();
    }

    if (m_options & ComputePolyhedralFeatures)
    {
        shape->initializePolyhedralFeatures();    
    }
	
	
	
	//shape->setMargin(0.001);
	m_collisionShapes.push_back(shape);

	btTransform startTransform;
	startTransform.setIdentity();

	btScalar	mass(1.f);
	bool isDynamic = (mass != 0.f);
	btVector3 localInertia(0,0,0);
	if (isDynamic)
		shape->calculateLocalInertia(mass,localInertia);

	float color[4] = {1,1,1,1};
	float orn[4] = {0,0,0,1};
	float pos[4] = {0,3,0,0};
	btVector3 position(pos[0],pos[1],pos[2]);
	startTransform.setOrigin(position);
        btRigidBody* body = createRigidBody(mass,startTransform,shape);


	
	bool useConvexHullForRendering = ((m_options & ObjUseConvexHullForRendering)!=0);
    
	    
	if (!useConvexHullForRendering)
    {
		int shapeId = m_guiHelper->registerGraphicsShape(&glmesh->m_vertices->at(0).xyzw[0], 
																		glmesh->m_numvertices, 
																		&glmesh->m_indices->at(0), 
																		glmesh->m_numIndices,
																		B3_GL_TRIANGLES, -1);
		shape->setUserIndex(shapeId);
		int renderInstance = m_guiHelper->registerGraphicsInstance(shapeId,pos,orn,color,scaling);
		body->setUserIndex(renderInstance);
    }
    
	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
Example #19
0
		void						phyMgr::parseUserText(const wcs& node_name, const SPtr<z3D::SG::SNode>& node, const wcs& user_text)
		{
			Config* cfg = Config::fromWCS(user_text);
			if(cfg->exists(L"collision_shape"))
			{
				wcs shape_name = cfg->getWString(L"collision_shape");
				REAL mass = cfg->getFloat(L"mass");
				int32_t compound = cfg->getInt32(L"compound");

				if(shape_name == L"box")
				{
					if(compound)
					{
						SPtr<phyShape> shape = createCompoundWrappedBoxShape(node->local_bound().extent(), node->local_bound().center());
						SPtr<phyBody> body = createBody(node, shape, Mat4::identity, mass, false);
						addBody(body);

						node->setPhyBody(body);
					}
					else
					{
						SPtr<phyShape> shape = createBoxShape(node->local_bound().extent());
						SPtr<phyBody> body = createBody(node, shape, Mat4::translation(Vec3(node->local_bound().center())), mass, false);
						addBody(body);

						node->setPhyBody(body);
					}
				}
				else if(shape_name == L"sphere")
				{
					Vec3 ext = node->local_bound().extent();
					SPtr<phyShape> shape = createSphereShape((ext[0] + ext[1] + ext[2]) / 3);
					SPtr<phyBody> body = createBody(node, shape, Mat4::translation(Vec3(node->local_bound().center())), mass, false);
					addBody(body);

					node->setPhyBody(body);
				}
				else if(shape_name == L"mesh")
				{
					if(node->type_info()->kind_of(z3D::SG::SMeshNode::type_info_static()))
					{
						SPtr<phyShape> shape = createMeshShape(node.cast<z3D::SG::SMeshNode>()->mesh());
						SPtr<phyBody> body = createBody(node, shape, Mat4::identity, mass, true);
						addBody(body);

						node->setPhyBody(body);
					}
				}
				else if(shape_name == L"convex_hull")
				{
					if(node->type_info()->kind_of(z3D::SG::SMeshNode::type_info_static()))
					{
						Vec3 offset;
						REAL computed_mass;
						Mat3 inertia_tensor;
						SPtr<phyShape> shape = createConvexHullShape(node.cast<z3D::SG::SMeshNode>()->mesh(), offset, computed_mass, inertia_tensor);
						SPtr<phyBody> body = createBody(node, shape, Mat4::translation(offset), mass, mass / computed_mass * Vec3(inertia_tensor[0][0], inertia_tensor[1][1], inertia_tensor[2][2]));

						addBody(body);

						node->setPhyBody(body);
					}
				}
				else if(shape_name == L"convex_decomp")
				{
					if(node->type_info()->kind_of(z3D::SG::SMeshNode::type_info_static()))
					{
						Vec3 offset;
						REAL computed_mass;
						Mat3 inertia_tensor;
						SPtr<phyShape> shape = createDecompConvexHullShape(node.cast<z3D::SG::SMeshNode>()->mesh(), offset, computed_mass, inertia_tensor);
						SPtr<phyBody> body = createBody(node, shape, Mat4::translation(offset), mass, mass / computed_mass * Vec3(inertia_tensor[0][0], inertia_tensor[1][1], inertia_tensor[2][2]));

						addBody(body);

						node->setPhyBody(body);
					}
				}
			}
			delete cfg;
		}