コード例 #1
0
void Ragdoll_experiment::initializeBodies() {
    ground = createGround();
    ragDoll = createRagdoll();
    
    ground->setFriction(GROUND_FRICTION);
    ground->setRestitution(GROUND_RESTITUTION);
}
コード例 #2
0
ファイル: DemoKeeper.cpp プロジェクト: MyGUI/mygui
	void DemoKeeper::createScene()
	{
		base::BaseDemoManager::createScene();
		std::string controllerCategory = MyGUI::ControllerManager::getInstance().getCategoryName();
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerRandomSelected>(controllerCategory);
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerRandomProgress>(controllerCategory);
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerSmoothProgress>(controllerCategory);
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerSmoothCaption>(controllerCategory);

		std::string resourceCategory = MyGUI::ResourceManager::getInstance().getCategoryName();
		MyGUI::FactoryManager::getInstance().registerFactory<ResourceDevice>(resourceCategory);

		std::string layerCategory = MyGUI::LayerManager::getInstance().getCategoryName();
		MyGUI::FactoryManager::getInstance().registerFactory<MyGUI::RTTLayer>(layerCategory);

		createGround();
		createObject();

		setupCamera();

		MyGUI::ResourceManager::getInstance().load("Resources.xml");

		mCommandManager = new CommandManager();
		mMonitorPanel = new MonitorPanel();
		mKeyboardPanel = new KeyboardPanel();
	}
コード例 #3
0
ファイル: Stage.cpp プロジェクト: leomarques/Dickbox
Stage::Stage()
{
    world = new World();
    freeDraw = new FreeDraw();
    customBox = new CustomBox();
    customPolygon = new CustomPolygon();
    customCircle = new CustomCircle();

    debugDrawOn = false;
    smallBodiesOn = false;
    cursorOn = true;
    autoDumpOn = false;
    bmpDrawOn = true;
    cleanModeOn = false;

    dt = gtime;

    bodyType = Random;
    gravity.x = 0.0f;
    gravity.y = -10.0f;

    bodiesSize = RANDBODYSIZE;
    bodiesRadius = RANDHALFSIZE;

    setMouseLock(false);

    createGround();
}
コード例 #4
0
ファイル: LiquidScene.cpp プロジェクト: kosakasakas/2DPhys
bool LiquidScene::init() {
    if ( !Layer::init() ) {
        return false;
    }
    
    srand((unsigned) time(NULL));
    
    createPhysWorld();
    createGround();
    createParticle();
    
    // デバック表示用
    initDebugDraw();
    initTouchEventListener();
    
    Size window = Director::getInstance()->getWinSize();
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 + 33, 33));
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 - 33, 33));
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 + 33 + 66, 33));
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 - 33 - 66, 33));
    
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 + 33 + 66, 33 + 66));
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 - 33 - 66, 33 + 66));
    
    
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 + 33 + 66, 33 + 66 + 66));
    drawBox2dSpriteAt(createBox2DSpriteData(SpriteType::Box), Point(window.width/2.0 - 33 - 66, 33 + 66 + 66));
    
    
    scheduleUpdate();
    
    return true;
}
コード例 #5
0
ファイル: AppEscape.cpp プロジェクト: MrMoose/NTRTsim
tgWorld *createWorld() {
    const tgWorld::Config config(98.1); // gravity, cm/sec^2  Use this to adjust length scale of world.
    // NB: by changing the setting below from 981 to 98.1, we've
    // scaled the world length scale to decimeters not cm.

    tgBoxGround* ground = createGround();
    return new tgWorld(config, ground);
}
コード例 #6
0
    void Game::init()
    {
        window.setFramerateLimit(60),

        createGround(400.f, 500.f);
        groundTexture.loadFromFile("assets/ground.png");

        boxTexture.loadFromFile("assets/box.png");

    }
コード例 #7
0
ファイル: sample.cpp プロジェクト: gamepattisiere/laboratory
AddRemoveBodiesDemo::AddRemoveBodiesDemo(hkDemoEnvironment* env)
:	hkDefaultPhysicsDemo(env),
	m_frameCount(0),
	m_currentBody(0)
{
	for( int i = 0; i < NUM_BODIES; i++ )
	{
		m_bodies[i] = HK_NULL;		
	}	

	//
	// Setup the camera
	//
	{
		hkVector4 from(0.0f, 30.0f, 50.0f);
		hkVector4 to  (0.0f,  0.0f,  0.0f);
		hkVector4 up  (0.0f,  1.0f,  0.0f);
		setupDefaultCameras(env, from, to, up);

		float lightDir[] = { -1, -0.5f , -0.25f};
		float lightAabbMin[] = { -15, -15, -15};
		float lightAabbMax[] = { 15, 15, 15};
		setLightAndFixedShadow(lightDir, lightAabbMin, lightAabbMax );
	}


	//
	// Setup and create the hkpWorld
	//
	{
		hkpWorldCinfo info;
		info.m_gravity = hkVector4(0.0f, -9.8f, 0.0f);
		info.setBroadPhaseWorldSize(1000.0f);
		info.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_8ITERS_MEDIUM);
		info.m_collisionTolerance = 0.01f; 
		
		m_world = new hkpWorld( info );
		m_world->lock();

		setupGraphics();		
	}

	// Register the single agent required (a hkpBoxBoxAgent)
	{
		hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher());
	}

	// Create the rigid bodies
	createBodies();

	// Create the ground
	createGround();

	m_world->unlock();
}
コード例 #8
0
ファイル: Visualize.cpp プロジェクト: ezhangle/HavokDemos
void Visualize::initPhysicWorld() {
	m_transform.setIdentity();

	//Make a new physics world
	m_world = new hkpWorld(hkpWorldCinfo());

	//Register all collision agents
	hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher());

	createGround();
	addDynamicBody();
}
コード例 #9
0
ファイル: level.cpp プロジェクト: ktingey/portfolio
Level::Level()
{

    b2Vec2 Gravity(0.f, 9.8f);
    World = new b2World(Gravity);
    createGround(400.f, 500.f);

    QTimer* timer = new QTimer(this);
    timer->setInterval(60);

    connect(timer, SIGNAL(timeout()), this, SLOT(step()));
    timer->start();

    //boxScene = new QGraphicsScene();
}
コード例 #10
0
ファイル: RagdollDemo.cpp プロジェクト: DanielNappa/bullet3
void	RagDollDemo::initPhysics()
{
	Bullet2RigidBodyDemo::initPhysics();
	int cubeShapeId = m_glApp->registerCubeShape();
	
	createGround(cubeShapeId);
	
	btVector3 offset(0,3,0);
	
	RagDoll* doll = new RagDoll(this->m_dynamicsWorld,offset,m_glApp);
	offset.setValue(0,6,0);
	doll = new RagDoll(this->m_dynamicsWorld,offset,m_glApp);

	m_glApp->m_instancingRenderer->writeTransforms();

}
コード例 #11
0
void	FeatherstoneDemo1::initPhysics()
{

	Bullet2MultiBodyDemo::initPhysics();

	createGround();

	btMultiBodySettings settings;
	settings.m_isFixedBase = false;
	settings.m_basePosition.setValue(0,10,0);
	settings.m_numLinks = 10;
	btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);


	m_glApp->m_instancingRenderer->writeTransforms();
}
コード例 #12
0
ファイル: 3.2.cpp プロジェクト: lc4t/OtherFiles
void RenderScene(GLenum mode)
{
	glMatrixMode(GL_MODELVIEW);
	if(flag_light == 1)
	{
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
	}
	else
	{
		glDisable(GL_LIGHTING);
		glDisable(GL_LIGHT0);
	}
	glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.5);
	glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0);
	glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
	glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
	glTranslatef(0.0,  - 2 * height, 0.0);
	glFrontFace(GL_CW);
	glScalef(1.0f,  -1.0f, 1.0f);

	glTranslatef(2 * movex / wide_screen, 2 * movey / height_screen, 2 * movez / wide_screen);
	glLightfv(GL_LIGHT0, GL_POSITION, light_postion);
	glTranslatef( -2 * movex / wide_screen,  -2 * movey / height_screen,  -2 * movez / wide_screen);

	createWall();
	createCeiling();
	createFurnishings();

	glScalef(1.0f,  -1.0f, 1.0f);
	glTranslatef(0.0, 2 * height, 0.0);
	glFrontFace(GL_CCW);

	glDisable(GL_LIGHTING);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	createGround();

	glDisable(GL_BLEND);
	glEnable(GL_LIGHTING);

	draw(mode);

}
コード例 #13
0
void	FeatherstoneDemo2::initPhysics()
{
	Bullet2MultiBodyDemo::initPhysics();

	createGround();

/*	btMultiBodySettings settings;
	settings.m_isFixedBase = false;
	settings.m_basePosition.setValue(0,20,0);
	settings.m_numLinks = 3;
	settings.m_usePrismatic = true;
	btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);
*/
	btVector3 offset(0,2,0);
	RagDoll2* doll = new RagDoll2(m_dynamicsWorld,offset,m_glApp);

	
	m_glApp->m_instancingRenderer->writeTransforms();
}
コード例 #14
0
ファイル: 3.2.cpp プロジェクト: lc4t/OtherFiles
void draw(GLenum mode)
{
	glMatrixMode(GL_MODELVIEW);
	if(flag_light == 1)
	{
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
	}
	else
	{
		glDisable(GL_LIGHTING);
		glDisable(GL_LIGHT0);
	}

	createLightAndProxy(mode);
	createWall();
	createGround();
	// createCeiling();
	createFurnishings();
}
コード例 #15
0
ファイル: DemoKeeper.cpp プロジェクト: sskoruppa/Glove_Code
	void DemoKeeper::createScene()
	{
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerRandomSelected>("Controller");
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerRandomProgress>("Controller");
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerSmoothProgress>("Controller");
		MyGUI::FactoryManager::getInstance().registerFactory<ControllerSmoothCaption>("Controller");
		MyGUI::FactoryManager::getInstance().registerFactory<ResourceDevice>("Resource");
		MyGUI::FactoryManager::getInstance().registerFactory<MyGUI::RTTLayer>("Layer");

		createGround();
		createObject();

		setupCamera();

		getGUI()->load("rtt_data.xml");

		mCommandManager = new CommandManager();
		mMonitorPanel = new MonitorPanel();
		mKeyboardPanel = new KeyboardPanel();
	}
コード例 #16
0
ファイル: ofxGameEng.cpp プロジェクト: Joelone/ofxGame
ofxGameEng& ofxGameEng::loadXml(string filePath = "config.xml"){
	ofxXmlSettings XML;
	//cout << "Reading game engine configuration file " << filePath;
	if (XML.loadFile(filePath)){
		//cout << " [ OK ]" << endl;
		
		init();
		
		if ( XML.tagExists("world:gravity"))
			setGravity(XML.getValue("world:gravity:x",0), 
					   XML.getValue("world:gravity:y",10) );
		
		setFPS(XML.getValue("world:fps",30));
		
		bool bGrabbing = XML.getValue("world:grabbing",0);
		if (bGrabbing)
			registerGrabbing();
		
		if ( XML.tagExists("world:ground:x"))
			groundX = XML.getValue("world:ground:x",0);
		
		if ( XML.tagExists("world:ground:y"))
			groundY = XML.getValue("world:ground:y",10);
	
		if( boundingObj != NULL ){
			createGround(ofPoint(	(groundX!=-1)?groundX:0,
									(groundY!=-1)?groundY:0),
							ofPoint((groundX!=-1)?groundX:boundingObj->getScaledWidth(), 
									(groundY!=-1)?groundY:boundingObj->getScaledHeight()));
			createBounds(0, 0, boundingObj->getScaledWidth(),boundingObj->getScaledHeight());
		}
		
		// TODO:
		//		This need some love
		
	} else
		cout << " [ FAIL ]" << endl;
		
	return * this;
}
コード例 #17
0
ファイル: Scene.cpp プロジェクト: novichiv/osgode
/* ....................................................................... */
osgODE::World*
createWorld(void)
{
    PS_DBG("%s", "createWorld()") ;


    osgODE::Space*  space = new osgODE::Space() ;
    PS_ASSERT1(space) ;




    space->setERP(0.2) ;
    space->setCFM(1.0e-5) ;



    osgODE::NearCallback*   near_callback = createNearCallback() ;
    PS_ASSERT1(near_callback) ;

    space->setNearCallback( near_callback ) ;



    osgODE::ODEObject*  ball = createBall() ;
    PS_ASSERT1(ball) ;

    osgODE::ODEObject*  ground = createGround() ;
    PS_ASSERT1(ground) ;


    space->addObject(ball) ;
    space->addObject(ground) ;



    return space ;
}
コード例 #18
0
KeyframingDemo::KeyframingDemo(hkDemoEnvironment* env)
:	hkDefaultPhysicsDemo(env)
{
	//
	// Set parameters for keyframes, and number of bodies
	//
	m_speed = 0.2f;
	m_radius = 5.0f;
	m_numBodies = 15;

	m_time = 0.0f;


	//
	// Setup the camera
	//
	{
		hkVector4 from(0, 40, 40);
		hkVector4 to(0, 0, 0);
		hkVector4 up(0, 1, 0);
		setupDefaultCameras(env, from, to, up);
	}


	//
	// Setup and create the hkpWorld.
	//
	{
		hkpWorldCinfo info;
		info.m_gravity = hkVector4(0.0f, -9.8f, 0.0f);
		info.setBroadPhaseWorldSize(150.0f);
		info.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM);
		
		m_world = new hkpWorld( info );
		m_world->lock();

		setupGraphics();		
	}

	//
	// Register the single agent required (a hkpBoxBoxAgent).
	//
	{
		hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher());
	}


	//
	// Create the rigid bodies.
	//
	createBodies();

	//
	// Create the ground.
	//
	createGround();



	//
	// Create the keyframed body.
	//
	{
		const hkVector4 halfExtents(3.0f, 1.75f, 0.3f);
		hkpBoxShape* shape = new hkpBoxShape(halfExtents, 0 );

		// Assign the rigid body properties
		hkpRigidBodyCinfo bodyInfo;
		bodyInfo.m_shape = shape;

		// By setting the motion type to hkpMotion::MOTION_KEYFRAMED we are essentially telling Havok that this
		// body has infinite mass. Thus neither applying forces nor impulses can change the velocity of the body and
		// as a result, the body is considered totally immovable during interactions (collisions) with other bodies.
		// This means that the user can force the body to follow a set of keyframes by directly setting the
		// velocity required to move to the next keyframe before each world step.
		// The body is guaranteed to reach the next keyframe, even if other bodies collide with it.
		// To help convert keyframes to velocities we have provided some useful methods in hkpKeyFrameUtility.
		// To create a keyframed object simply set the motion type as follows:

		bodyInfo.m_motionType = hkpMotion::MOTION_KEYFRAMED;

		{
			// Get inital keyframe.
			getKeyframePositionAndRotation(0.0f, bodyInfo.m_position, bodyInfo.m_rotation);
		}


		// Add our keyframed body.
		m_keyframedBody = new hkpRigidBody(bodyInfo);
		m_world->addEntity(m_keyframedBody);
		m_keyframedBody->removeReference();

		shape->removeReference();
	}

	m_world->unlock();
}
コード例 #19
0
ファイル: BasicDemo.cpp プロジェクト: Zerak/bullet3
void	BasicDemo::initPhysics()
{
//	Bullet2RigidBodyDemo::initPhysics();

	m_config = new btDefaultCollisionConfiguration;
	m_dispatcher = new btCollisionDispatcher(m_config);
	m_bp = new btDbvtBroadphase();
	m_solver = new btNNCGConstraintSolver();
	m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_bp,m_solver,m_config);

	int curColor=0;
	//create ground
	int cubeShapeId = m_glApp->registerCubeShape();
	float pos[]={0,0,0};
	float orn[]={0,0,0,1};
		

	createGround(cubeShapeId);
	

	{
		float halfExtents[]={scaling,scaling,scaling,1};
		btVector4 colors[4] =
		{
			btVector4(1,0,0,1),
			btVector4(0,1,0,1),
			btVector4(0,1,1,1),
			btVector4(1,1,0,1),
		};
		


		btTransform startTransform;
		startTransform.setIdentity();
		btScalar mass = 1.f;
		btVector3 localInertia;
		btBoxShape* colShape = new btBoxShape(btVector3(halfExtents[0],halfExtents[1],halfExtents[2]));
		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++)
				{
					
					btVector4 color = colors[curColor];
					curColor++;
					curColor&=3;
					startTransform.setOrigin(btVector3(
										btScalar(2.0*scaling*i),
										btScalar(2.*scaling+2.0*scaling*k),
										btScalar(2.0*scaling*j)));

					m_glApp->m_instancingRenderer->registerGraphicsInstance(cubeShapeId,startTransform.getOrigin(),startTransform.getRotation(),color,halfExtents);
			
					//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
					btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
					btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);
					btRigidBody* body = new btRigidBody(rbInfo);
					

					m_dynamicsWorld->addRigidBody(body);
				}
			}
		}
	}

	m_glApp->m_instancingRenderer->writeTransforms();
}
コード例 #20
0
ファイル: Stage.cpp プロジェクト: leomarques/Dickbox
bool Stage::step(void)
{
    updateInput();

    menuOn = false;

    if (keys[KEYESC])
        return false;

    if (mouse[0] or (autoDumpOn and (bodyType == Random or bodyType == Box or bodyType == Circle)))
    {
        bodiesSize = smallBodiesOn ? SMALLBODYSIZE : RANDBODYSIZE;
        bodiesRadius = smallBodiesOn ? SMALLHALFSIZE : RANDHALFSIZE;

        switch (bodyType)
        {
        case Random:
            if (RANDOM(0, 1))
                world->makeBox(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesSize);
            else
                world->makeCircle(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesRadius);
            break;

        case Box:
            world->makeBox(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesSize);
            break;

        case Circle:
            world->makeCircle(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesRadius);
            break;

        case Free_Draw:
            freeDraw->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Polygon:
            customPolygon->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Box:
            customBox->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Circle:
            customCircle->takePoint(Point(mouse_x, mouse_y));
            break;
        }
    }
    else
    {
        if (freeDraw->On)
            freeDraw->makeBody(world);
        if (customBox->On)
            customBox->makeBody(world);
        if (customCircle->On)
            customCircle->makeBody(world);
        if (customPolygon->On)
            customPolygon->updateView(Point(mouse_x, mouse_y));
    }

    if (mouse[1])
    {
        if (customPolygon->On)
            customPolygon->makeBody(world);
        else
            world->makeBomb(coordAllegToB2(Point(mouse_x, mouse_y)));
    }

    if (keys[KEY1])
        bodyType = Random;

    if (keys[KEY2])
        bodyType = Box;

    if (keys[KEY3])
        bodyType = Circle;

    if (keys[KEY4])
    {
        bodyType = Free_Draw;
        setMouseLock(false);
    }

    if (keys[KEY5])
    {
        bodyType = Custom_Box;
        setMouseLock(false);
    }

    if (keys[KEY6])
        world->destroyLastBody();

    if (keys[KEY7])
        world->toggleStaticMode();

    if (keys[KEY8])
        world->toggleSimulation();

    if (keys[KEY9])
        if (bodyType == Random or bodyType == Box or bodyType == Circle)
            toggleMouseLock();

    if (keys[KEY0])
    {
        world->destroyAllBodies();
        createGround();
    }

    if (keys[KEYP])
        pyramidShow();

    if (keys[KEYTAB])
        menuOn = true;

    if (keys[KEYH])
        cleanModeOn = !cleanModeOn;

    if (keys[KEYA])
        autoDumpOn = !autoDumpOn;

    if (keys[KEYC])
        cursorOn = !cursorOn;

    if (keys[KEYX])
    {
        bodyType = Custom_Circle;
        setMouseLock(false);
    }

    if (keys[KEYV])
    {
        bodyType = Custom_Polygon;
        setMouseLock(true);
    }

    if (keys[KEYN])
        world->destroyLastNonStaticBody();

    if (keys[KEYM])
        world->destroyAllNonStaticBodies();

    if (keys[KEYS])
        smallBodiesOn = !smallBodiesOn;

    if (keys[KEYUP])
    {
        gravity.y += 2;
        world->setGravity(gravity);
    }

    if (keys[KEYDOWN])
    {
        gravity.y -= 2;
        world->setGravity(gravity);
    }

    if (keys[KEYLEFT])
    {
        gravity.x -= 2;
        world->setGravity(gravity);
    }

    if (keys[KEYRIGHT])
    {
        gravity.x += 2;
        world->setGravity(gravity);
    }

    if (keys[KEYD])
    {
        if (debugDrawOn)
        {
            if (bmpDrawOn)
            {
                bmpDrawOn = false;
            }
            else
            {
                bmpDrawOn = true;
                toggleDebugDraw();
            }
        }
        else
        {
            toggleDebugDraw();
        }
    }

    world->simulate();

    return true;
}
コード例 #21
0
ファイル: ofxBox2d.cpp プロジェクト: callihiggins/VFA
// ------------------------------------------------------ create Ground
void ofxBox2d::createGround(const ofPoint & p1, const ofPoint & p2) {
	createGround(p1.x, p1.y, p2.x, p2.y);
}
コード例 #22
0
ファイル: NodeFactory.cpp プロジェクト: dburihabwa/SokobanOSG
osg::ref_ptr<osg::Node> Sokoban::NodeFactory::getOrCreateGeode(Type element) {
	if(_geoCache.find(element) != _geoCache.end()) {
		return _geoCache[element];
	}

	osg::ref_ptr<osg::Geode> noeudGeo = new osg::Geode();
	osg::ref_ptr<osg::ShapeDrawable> shape;
	std::string textureImage = TEXTURE_DIR;

	if (isAButton(element)) {
		std::map<Sokoban::Type, std::string>::iterator it = _textures.find(element);
		if (it != _textures.end())
			textureImage.append(it->second);
		else
			textureImage.append("default.jpg");
		shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), BUTTON_LENGTH_X, BUTTON_LENGTH_Y, BUTTON_LENGTH_Z));
		noeudGeo->addDrawable(shape);
		setTexture(noeudGeo, element, textureImage);

		osg::ref_ptr<osg::Geode> switchNoeudGeo = new osg::Geode();
		std::string switchTextureImage = TEXTURE_DIR;
		it = _switchTextures.find(element);
		if (it != _switchTextures.end())
			switchTextureImage.append(it->second);
		else
			switchTextureImage.append("default.jpg");
		osg::ref_ptr<osg::ShapeDrawable> switchShape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), BUTTON_LENGTH_X, BUTTON_LENGTH_Y, BUTTON_LENGTH_Z));
		switchNoeudGeo->addDrawable(switchShape);
		setTexture(switchNoeudGeo, element, switchTextureImage);

		osg::ref_ptr<osg::Switch> nodeSwitch = new osg::Switch();
		nodeSwitch->insertChild(0, noeudGeo); 
		nodeSwitch->insertChild(1, switchNoeudGeo);
		nodeSwitch->setChildValue(switchNoeudGeo, false);
		return nodeSwitch;
	} else {
		float lengthX, lengthY, lengthZ;
		//Switch on the element for texture and shape
		switch(element)
		{
		case GROUND :
			noeudGeo->addDrawable(createGround());
			break;
		case BOX:
			shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, BOX_CENTER_Z), BOX_WIDTH));
			break;
		case WALL:
			lengthX = DEFAULT_LENGTH_X, lengthY = DEFAULT_LENGTH_Y, lengthZ = WALL_LENGTH_Z;
			//shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0.55), lengthX, lengthY, lengthZ));
			shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, WALL_CENTER_Z), lengthX, lengthY, lengthZ));
			break;
		case TARGET:
			lengthX = DEFAULT_LENGTH_X, lengthY = DEFAULT_LENGTH_Y, lengthZ = TARGET_LENGTH_Z;
			//shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, -0.6), lengthX, lengthY, lengthZ));
			shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, TARGET_CENTER_Z), lengthX, lengthY, lengthZ));
			break;
		case PLAYER:
			//shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0, 0, -0.5), PLAYER_RADIUS));
			shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0, 0, PLAYER_CENTER_Z), PLAYER_RADIUS));
			break;
		default:
			shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), DEFAULT_WIDTH));
			break;
		}
	}

	if (element != GROUND)
		noeudGeo->addDrawable(shape);

	std::map<Sokoban::Type, std::string>::iterator it = _textures.find(element);
	if (it != _textures.end())
		textureImage.append(it->second);
	else
		textureImage.append("default.jpg");

	noeudGeo = setTexture(noeudGeo, element, textureImage);

	_geoCache.insert(std::make_pair(element, noeudGeo));
	return  noeudGeo;
}
コード例 #23
0
ファイル: DemoKeeper.cpp プロジェクト: kevinmore/MyPhysicsLab
void DemoKeeper::KeyframingDemo( void )
{
	mWorld->markForWrite();
	//
	// Set parameters for keyframes, and number of bodies
	//
	m_speed = 0.2f;
	m_radius = 5.0f;
	m_numBodies = 15;
	m_time = 0.0f;

	//
	// Create the rigid bodies.
	//
	createBodies();

	//
	// Create the ground.
	//
	createGround();

	//
	// Create the keyframed body.
	//
	{
		const hkVector4 halfExtents(3.0f, 1.75f, 0.3f);
		hkpBoxShape* shape = new hkpBoxShape(halfExtents, 0 );

		// Assign the rigid body properties
		hkpRigidBodyCinfo bodyInfo;
		bodyInfo.m_shape = shape;
		// By setting the motion type to hkpMotion::MOTION_KEYFRAMED we are essentially telling Havok that this
		// body has infinite mass. Thus neither applying forces nor impulses can change the velocity of the body and
		// as a result, the body is considered totally immovable during interactions (collisions) with other bodies.
		// This means that the user can force the body to follow a set of keyframes by directly setting the
		// velocity required to move to the next keyframe before each world step.
		// The body is guaranteed to reach the next keyframe, even if other bodies collide with it.
		// To help convert keyframes to velocities we have provided some useful methods in hkpKeyFrameUtility.
		// To create a keyframed object simply set the motion type as follows:

		bodyInfo.m_motionType = hkpMotion::MOTION_KEYFRAMED;

		{
			// Get inital keyframe.
			getKeyframePositionAndRotation(0.0f, bodyInfo.m_position, bodyInfo.m_rotation);
		}


		// Add our keyframed body.
		m_keyframedBody = new hkpRigidBody(bodyInfo);
		mWorld->addEntity(m_keyframedBody);
		m_keyframedBody->removeReference();

		shape->removeReference();


		//render it with Ogre
		Ogre::SceneNode* boxNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();

		//scale
		boxNode->scale(6, 3.5, 0.6);

		//display and sync
		Ogre::Entity *ent = mSceneMgr->createEntity(Ogre::StringConverter::toString(mLabMgr->getEntityCount()),"defCube.mesh");
		mLabMgr->setColor(ent, Ogre::Vector3(rand()/(double)RAND_MAX,rand()/(double)RAND_MAX,rand()/(double)RAND_MAX));
		HkOgre::Renderable* rend = new HkOgre::Renderable(boxNode, m_keyframedBody,mWorld);
		boxNode->attachObject(ent);

		//register to lab manager
		mLabMgr->registerEnity( boxNode, m_keyframedBody);
	}



	mWorld->unmarkForWrite();

	Keyframe_demoRunning = true;

}
コード例 #24
0
DestructibleWallsDemo::DestructibleWallsDemo(hkDemoEnvironment* env)
:hkDefaultPhysicsDemo(env),
m_fractureUtility(HK_NULL),
m_constraintListener(HK_NULL),
m_shootingDirX(.0f),
m_shootingDirY(.0f),
m_gunCounter(0),
m_centerOfScene( hkVector4::getZero() ),
m_brickHalfExtents( 0.5f, 0.5f, 0.5f )
{
	// General setup
	m_frameToSimulationFrequencyRatio = 1.0f;
	m_timestep = 1.0f / 60.0f;

	// read demo options
	//const BreakableWallVariant& variant =  g_variants[m_variantId];

	m_collisionDetectionType = (m_options.m_useParallelSimulation)? PARALLEL : SIMPLE;  //variant.m_Type;

	// wall shape options 
	int wallWidth  = m_options.m_WallsWidth;  
	int wallHeight = m_options.m_WallsHeight; 

	// setup camera
	{
		hkReal tot = static_cast<hkReal>( m_options.m_WallsHeight + m_options.m_WallsWidth );
		if(tot < 5)
			tot = 5;
		//hkVector4 from(-25.0f, 30.0f, 30.0f);
		hkVector4 from(-tot*1.0f, tot*1.25f, tot*1.25f);
		hkVector4 to( -5.0f, 15.0f, 15.0f);
		//hkVector4 to  ( 0.0f, 0.0f, 0.0f);
		hkVector4 up( 0.0f,  1.0f, 0.0f);
		setupDefaultCameras( env, from, to, up );
	}

	// Main world initialization
	// define world info..

	hkpWorldCinfo worldInfo;
	worldInfo.setBroadPhaseWorldSize(500.0f);
	worldInfo.setupSolverInfo(hkpWorldCinfo/*::SOLVER_TYPE_8ITERS_HARD*/::SOLVER_TYPE_4ITERS_HARD);// using 8 iterations is much stiffer and realistic..	
	worldInfo.m_collisionTolerance = 0.01f;
	worldInfo.m_gravity = hkVector4( 0.0f,-9.8f,0.0f);
	worldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_CONTINUOUS;
	worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY;
	worldInfo.m_enableDeactivation = false;
	// .. create the world..
	m_world = new hkpWorld(worldInfo);

	// ..and LOCK it
	m_world->lock();

	// register agents and setup graphics
	hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher());
	// to enable wireframe display remove comment from next line
	if(m_options.m_wireFrameMode)
		m_env->m_window->getViewport(0)->toggleState(HKG_ENABLED_WIREFRAME);  
	setupGraphics();

	// Create and add the ground
	hkpRigidBody* ground = createGround();
	m_world->addEntity( ground , HK_ENTITY_ACTIVATION_DO_NOT_ACTIVATE);
	ground->removeReference();

	if(g_variants[m_variantId].singleBrick) // TMP SINGLE BRICK FRACTURE VARIANT
	{
		// geometry of a wall brick
		hkpBoxShape* brickGeom = new hkpBoxShape(m_brickHalfExtents, 0);
		// wall builder settings
		BrickwallBuilderDescriptor bwDescriptor;
		bwDescriptor.m_brickShape = brickGeom;
		bwDescriptor.m_width = 1;
		bwDescriptor.m_height = 1;
		bwDescriptor.m_brickMass = 10.0f;
		// Set positions and orientations for the walls
		m_centerOfScene(1) += 10.0f; 
		bwDescriptor.m_transform.set(hkQuaternion::getIdentity(), m_centerOfScene);
		//bwDescriptor.m_position = m_centerOfScene;
		//bwDescriptor.m_orientation.setIdentity();
		
		// create the fracture utility
		m_fractureUtility = new WallFractureUtility( m_world );
		// ...and add the wall
		WallWrapper* addedWall = m_fractureUtility->addWallToSimulation(bwDescriptor);
		// make this wall fracturable
		addedWall->toggleFracturableState(true);

		brickGeom->removeReference();
	} else
	 // WORLD AND WALLS SETUP
	{
		// common to both parallel and simple
		// geometry of a wall brick
		hkpBoxShape* brickGeom = new hkpBoxShape(m_brickHalfExtents, 0);
		// wall builder settings
		BrickwallBuilderDescriptor bwDescriptor;
		bwDescriptor.m_brickShape = brickGeom;
		bwDescriptor.m_width = wallWidth;
		bwDescriptor.m_height = wallHeight;
		bwDescriptor.m_brickMass = 10.0f;
		bwDescriptor.m_strength = m_options.m_bottomConstraintStrength;
		bwDescriptor.m_lowerThreshold = m_options.m_topConstraintStrength;
		bwDescriptor.m_attachToGround = m_options.m_attachToGround;
		bwDescriptor.m_theGround = m_world->getFixedRigidBody();
		// Set positions and orientations for the walls
		//hkArray< hkVector4 > wallsPositions(3);
		//hkArray< hkQuaternion > wallsOrientations(3); 
		hkArray< hkTransform > wallTransforms(3);
		{
			posOnGround(m_world, m_centerOfScene, m_centerOfScene);
			// wall 1
			m_centerOfScene(2) += wallWidth*m_brickHalfExtents(0); 
			wallTransforms[0].set(hkQuaternion::getIdentity(), m_centerOfScene);
			//wallsPositions[0] = m_centerOfScene;
			//wallsOrientations[0].setIdentity();
			// wall 2
			m_centerOfScene(2) -= wallWidth*m_brickHalfExtents(0)*2.0f; 
			wallTransforms[1].set(hkQuaternion::getIdentity(), m_centerOfScene);
			//wallsPositions[1] = m_centerOfScene;
			//wallsOrientations[1].setIdentity();
			// wall 3
			m_centerOfScene(2) += wallWidth*m_brickHalfExtents(0);
			m_centerOfScene(0) += wallWidth*m_brickHalfExtents(0);
			m_centerOfScene(0) += m_brickHalfExtents(0);
			//wallsPositions[2] = m_centerOfScene;
			hkVector4 axis(0,1,0); 
			hkQuaternion rot( axis, HK_REAL_PI/2.0f );
			//wallsOrientations[2].setAxisAngle( axis, HK_REAL_PI/2.0f );
			wallTransforms[2].set(rot, m_centerOfScene);
		}
		//
		
		// Differentiate simple and parallel simulation versions
		switch(m_collisionDetectionType)
		{
		case SIMPLE :
			{
				// Set up a collision filter so we can disable collisions between the bricks we constrain together
				hkpCollisionFilter* brickFilter = new BrickFilter();
				m_world->setCollisionFilter( brickFilter );
				brickFilter->removeReference();

				// constraint listener to enable collision detection between bricks whose constraints are broken
				m_constraintListener = new BrickConstraintListenerEntities();
				m_world->addConstraintListener( m_constraintListener );

				for(int i=0; i<3; ++i)
				{
					// build walls
					bwDescriptor.m_transform = wallTransforms[i];
					//bwDescriptor.m_position = wallsPositions[i];
					//bwDescriptor.m_orientation = wallsOrientations[i];
					bwDescriptor.m_wallID = i+1;
					createAddBrickWall(m_world, bwDescriptor);
				}
			}	
			break;
		case PARALLEL :
			{
				// create the fracture manager utility
				m_fractureUtility  = new WallFractureUtility( m_world );

				for(int i=0; i< 3; ++i)
				{
					// set positions and ask the utility to create and add the walls
					bwDescriptor.m_transform = wallTransforms[i];
					/*bwDescriptor.m_position = wallsPositions[i];
					bwDescriptor.m_orientation = wallsOrientations[i];*/
					m_fractureUtility->addWallToSimulation( bwDescriptor );
				}
			}
		} //  end of switch

		brickGeom->removeReference();
	}

	// UNLOCK the main world
	m_world->unlock();
}
コード例 #25
0
ファイル: main.cpp プロジェクト: satanas/sfml-test
int main(int, char const**) {
    int width = 1000;
    int height = 600;
    char buff[15];

    srand(time(NULL));

    sf::Clock clock;

    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;

    // Create the main window
    sf::RenderWindow window(sf::VideoMode(width, height), "My First SFML example", sf::Style::Default, settings);
    window.setFramerateLimit(60);

    sf::Font font;
    if (!font.loadFromFile("sansation.ttf")) {
        return EXIT_FAILURE;
    }

    sf::Text text;
    text.setFont(font);
    text.setString("Hello Benchmark!");
    text.setCharacterSize(24);
    int text_x = (width - (text.getCharacterSize() * 5)) / 2;
    text.setPosition(text_x, 0);
    text.setColor(sf::Color::White);

    sf::Text fps;
    fps.setFont(font);
    fps.setCharacterSize(20);
    fps.setColor(sf::Color::Black);

    sf::Texture barrel;
    if (!barrel.loadFromFile("barrel.png")) {
        return EXIT_FAILURE;
    }

    std::vector<sf::Sprite> sprites(MAX_SPRITES);
    for (int i=0; i<MAX_SPRITES; i++) {
        sprites[i].setTexture(barrel);
        int x = rand() % width;
        int y = rand() % height;
        sprites[i].setPosition(x, y);
    }

    // Box2D
    b2Vec2 gravity(0.0f, 10.0f);
    b2World world(gravity);

    createGround(world);

    /** Prepare textures */
    sf::Texture GroundTexture;
    sf::Texture BoxTexture;
    GroundTexture.loadFromFile("ground.png");
    BoxTexture.loadFromFile("box.png");

    createBox(world, 300, 0);
    createBox(world, 300, 20);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

    //    window.clear(sf::Color::Black);

        sprintf(buff, "FPS: %3.2f", framesPerSecond(clock));
        fps.setString(sf::String(buff));


    //    //for (int i=0; i<MAX_SPRITES; i++) {
    //    //    sf::Sprite s = sprites[i];
    //    //    s.setScale(rand() % 2 + 1, 2);
    //    //    s.setRotation((rand() % 720) - 360);
    //    //    window.draw(s);
    //    //}

    //    window.draw(text);

    //    window.display();
    //}


        if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            int MouseX = sf::Mouse::getPosition(window).x;
            int MouseY = sf::Mouse::getPosition(window).y;
            createBox(world, MouseX, MouseY);
        }
        world.Step(1.0f/60.f, 8, 3);


        window.clear(sf::Color::White);
        int BodyCount = 0;
        for (b2Body* BodyIterator = world.GetBodyList(); BodyIterator != 0; BodyIterator = BodyIterator->GetNext()) {
            if (BodyIterator->GetType() == b2_dynamicBody) {
                sf::Sprite Sprite;
                Sprite.setTexture(BoxTexture);
                Sprite.setOrigin(0.5f * SCALE, 0.5f * SCALE);
                Sprite.setPosition(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
                Sprite.setRotation(BodyIterator->GetAngle() * 180/b2_pi);
                window.draw(Sprite);
                ++BodyCount;
            } else {
                sf::Sprite GroundSprite;
                GroundSprite.setTexture(GroundTexture);
                GroundSprite.setColor(sf::Color::Red);
                GroundSprite.setOrigin(40.0f * SCALE, 1.0f * SCALE);
                GroundSprite.setPosition(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
                GroundSprite.setRotation(180/b2_pi * BodyIterator->GetAngle());
                window.draw(GroundSprite);
            }
        }
        window.draw(fps);
        window.display();
    }

    return 0;
}