Example #1
0
void StaticShape::unpackUpdate(NetConnection *connection, BitStream *bstream)
{
   Parent::unpackUpdate(connection,bstream);
   if (bstream->readFlag())
   {
      MatrixF mat;
      mathRead(*bstream,&mat);
      Parent::setTransform(mat);
      Parent::setRenderTransform(mat);

      VectorF scale;
      mathRead(*bstream, &scale);
      setScale(scale);
   }

   // powered?
   mPowered = bstream->readFlag();

   if (mLightPlugin)
   {
      mLightPlugin->unpackUpdate(this, connection, bstream);
   }
   //.logicking >>
   if (bstream->readFlag())
		updatePhysics();
   //.logicking <<
}
Example #2
0
void Unit::setUnitSize( float size )
{
	Image.setSize(size);
	phys.scale( size );
	updatePhysics( );

}
Example #3
0
void Player::update(Server& s)
{
	while(socket->bytesAvailable()) {
		QDataStream is(socket);
		if (packetSize<0) {
			if (socket->bytesAvailable()<4) break;
			is>>packetSize;
		}
		if (socket->bytesAvailable()<packetSize) break;
		packetSize=-1;
		quint8 type;
		is>>type;
		switch(type) {
			case MSG_STATE:
				readState(is);
				break;
			case MSG_SHOOT:
				readShoot(is, s);
				break;
			case MSG_INFO:
				readInfo(is);
				break;
		    case MSG_CHAT:
		        readChat(is);
		        break;
			default:
				qDebug()<<type;
				abort();
		}
	}

	updatePhysics(s);
}
Example #4
0
// ------------- update
void EyeLinker::update(){
    updateVelocity();
    updateParameters();
    updatePhysics();
    updateEye();
    updateFading();
    updateFireworks();
}
Example #5
0
void GLWidget::startPhysics()
{
#if DRGDRW
    connect(internalTimer(), SIGNAL(timeout()), this, SLOT(simulate()));
#else
    connect(this, SIGNAL(updatePhysics()), m_thread, SLOT(simulate()));
    connect(m_thread, SIGNAL(doneStep()), this, SLOT(update()));
#endif
    m_isPhysicsRunning = true;
}
Example #6
0
	void BlobLayer::update(float dt)
	{
		if (state == GameStates::Playing)
		{
			updatePhysics(dt);
			regenTime += dt;
			if (regenTime > regenPeriod)
			{
				regenTime = 0;
				generate();
			}
			if (regenPeriod > minRegenPeriod) regenPeriod -= dt * 0.06f;
		}
	}
Example #7
0
void GLWidget::clientDraw()
{
    if(m_thread->numLoops() < WorldThread::NumSubsteps) {
        emit updatePhysics();
        return;
    }
    
    std::stringstream sst;
	sst.str("");
	sst<<"fps: "<<frameRate();
    hudText(sst.str(), 1);
    
#if DRGDRW
    if(m_isPhysicsRunning) m_interface->draw(m_world, getDrawer());
#else
    if(m_isPhysicsRunning) {
        emit updatePhysics();
        m_interface->draw(m_world, getDrawer());
        m_world->dbgDraw();
    }
#endif
    //else m_interface->drawFaulty(m_world, getDrawer());
}
Example #8
0
void Antimony::step()
{
	timer.catchTime(TIMER_FRAME_GLOBAL);
	delta = timer.getDelta();
	double fstep = delta * worldSpeed;

	cpuUsage.GetUsage(0);

	if (GetForegroundWindow() == window_main.hWnd && mouse.isExclusive())
	{
		mouse.acquire(false);
	}
	else
	{
		mouse.release(false);
		/*SetCursor(arrow);
		SetClassLong(window_main.hWnd, GCL_HCURSOR, (DWORD)arrow);*/
	}

	updateGameState();

	if (ifGameState(GAMESTATE_INGAME))									// In-game (non-paused, non-menu etc.)
	{
		if (devConsole.isOpen())
		{
			player.lock();
			camera_main.lock();
		}
		else
		{
			player.unlock();
			camera_main.unlock();
		}

		updateAI(fstep);														// update AI/scripts etc. (TBI)
		updateWorld(fstep);														// update moving objects, triggers etc. (TBI)
		player.update(delta, m_objectsCollisions);
		updatePlayerControls(&keys, &controller[0], fstep);						// update player inputs
		updatePhysics(fstep);													// btWorld step
		updateCameraControls(&mouse, &keys, &controller[0], fstep);				// update camera (--> mat_view)
	}
	else if (ifGameState(GAMESTATE_PAUSED) && devConsole.isClosed())		// Game is paused
	{
		camera_main.unlock();

		updateCameraControls(&mouse, &keys, &controller[0], fstep);				// update camera (--> mat_view)
	}

	prepareFrame();														// prepare the frame for rendering
}
Example #9
0
//-----------------------------------------------------------------------------
void StamFluidSolver::Update()
{

    updatePhysics();
    Mesh& m = mGame.GetRenderer().GetMesh(mMeshes[0]);
    m.Lock();

    if(mTextureMorph) {
        setUVs(texU, texV);
        mUV = m.SwapUVPointer(mUV);
    } else {
        adjustColorsOfVertices2(dens);
        mColors = m.SwapColorPointer(mColors);
    }

    m.Unlock();
}
Example #10
0
/*!
 * Lesson 01 - Hello Bullet
 * Create an irrlicht scene and a bullet world
 * Implement the integration, and build a foundation
 * for the other tutorials
 */
int main(int argc, char *argv[]) {

    // Irrlicht grabs the cursor so it is not in the way of our visualisation
    // Window caption gets set.
    device->getCursorControl()->setVisible(0);
    device->setWindowCaption(L"Lesson 02 - Additional Meshes");

    // Set the camera backwards and viewing the origin; setting up the visualisation
    cam->setPosition(irr::core::vector3df(0, 2, -5));
    cam->setTarget(irr::core::vector3df(0, 2, 0));
    smgr->addLightSceneNode(0, irr::core::vector3df(2, 10, -2), irr::video::SColorf(4, 4, 4, 1));

    // Creating our scene
    createScene();

    // Use a timestamp to regulate the frames, and stepping the simulation
    irr::u32 timeStamp = timer->getTime(), deltaTime = 0;

    // Game loop
    while(!done) {

	// Code to record when the frame began
	deltaTime = timer->getTime() - timeStamp;
	timeStamp = timer->getTime();

	// Step the simulation
	updatePhysics(deltaTime);

	// Irrlicht draws the scene
	driver->beginScene(true, true, irr::video::SColor(0, 15, 192, 252));
	smgr->drawAll();
	driver->endScene();
	device->run();
    }

    // clean up
    clearObjects();
    delete world;
    delete solver;
    delete dispatcher;
    delete broadphase;
    delete collisionConfiguration;
    device->drop();

   return 0;
}
Example #11
0
bool StaticShape::onAdd()
{
   if(!Parent::onAdd() || !mDataBlock)
      return false;

   // We need to modify our type mask based on what our datablock says...
   mTypeMask |= (mDataBlock->dynamicTypeField & sgAllowedDynamicTypes);

   addToScene();

   	//.logicking >>
	updatePhysics();
    //.logicking << 
   if (isServerObject())
      scriptOnAdd();
   return true;
}
Example #12
0
bool BallGame::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;

    if(mShutDown)
        return false;

    //Need to capture/update each device
    mKeyboard->capture();
    mMouse->capture();

	updatePhysics();
	
	if(cam != NULL)
		cam->updateFollower(evt.timeSinceLastFrame);

    return true;
}
Example #13
0
void Engine::Engine::mainLoop()
{
    m_Factory.test_createObjects();

    btPairCachingGhostObject *pGhostObject = new btPairCachingGhostObject();
    pGhostObject->activate();
    btConvexShape *pShape = new btSphereShape(1.0f);
    m_pCharacterController = new btKinematicCharacterController(pGhostObject, pShape, 1.0f);
    //m_PhysicsSystem.world()->addCharacter(m_pCharacterController);

	// Define the updaterate for the game-logic
    const float update_fps = 64;
    auto update_dt = std::chrono::duration<double>(1 / update_fps);
	auto max_dt_seconds = std::chrono::duration<double>(0.2f);
	std::chrono::duration<double> accumulator = std::chrono::duration<double>::zero();
	std::chrono::duration<double> delta = std::chrono::duration<double>::zero();
	// Start the timer
	m_MainLoopTimer.update();

	bool isRunning = true;
    std::thread physicsThread([this, &isRunning]()
    {
        Utils::Timer<double> timer;
        std::chrono::duration<double> delta = std::chrono::duration<double>::zero();
		double acc = 0.0;
        while(isRunning)
        {
			timer.update();
			acc += timer.getAvgDelta().count();
			if(acc < 1.0 / 60.0)
			{			
				std::this_thread::sleep_for(std::chrono::nanoseconds(static_cast<long>((1.0 / 60.0) * 1000000000.0)));
				continue;
			}

			acc = 0.0;

            m_PhysicsSystem.updateRigidBodies();
            // Let bullet do it's own fixed timestamp
            updatePhysics(delta);
        }
    });

    
    while(isRunning)
    {
		delta =  m_MainLoopTimer.update();
        accumulator += delta;

        if(accumulator > max_dt_seconds)
            accumulator = max_dt_seconds;

		// Update the physics as often as we have to
        while(accumulator > update_dt)
            accumulator -= update_dt;

		//updatePhysics(accumulator);
		//accumulator = std::chrono::duration<double>::zero();

		// Generate interpolation value for the renderer
        const float alpha = static_cast<float>(accumulator / update_dt);

		// Draw the current frame
        isRunning = render(alpha);
    }

    physicsThread.join();
}
Example #14
0
/*!
 * Lesson 01 - Hello Bullet
 * Create an irrlicht scene and a bullet world
 * Implement the integration, and build a foundation
 * for the other tutorials
 */
int main(int argc, char *argv[]) {

    // Irrlicht grabs the cursor so it is not in the way of our visualisation
    // Window caption gets set.
    device->getCursorControl()->setVisible(0);
    device->setWindowCaption(L"Lesson 03 - Intro to Raycasting");

    // Set the camera backwards and viewing the origin; setting up the visualisation
    cam->setPosition(irr::core::vector3df(0, 2, -5));
    cam->setTarget(irr::core::vector3df(0, 2, 0));
    smgr->addLightSceneNode(0, irr::core::vector3df(2, 10, -2), irr::video::SColorf(4, 4, 4, 1));

    // Creating our scene
    createScene();

    // Use a timestamp to regulate the frames, and stepping the simulation
    irr::u32 timeStamp = timer->getTime(), deltaTime = 0;

    // Game loop
    while(!done) {

	// Code to record when the frame began
	deltaTime = timer->getTime() - timeStamp;
	timeStamp = timer->getTime();

	// Step the simulation
	updatePhysics(deltaTime);

	// Irrlicht draws the scene
	driver->beginScene(true, true, irr::video::SColor(0, 15, 192, 252));

	//Visualize the raycast for the camera. The line needs to only be as long as the ray cast that way we are not blazing through objects and it really helps show the concept of ray casting, and it is a more realistic laser sight

	// Need the name for this mathmatical formula
	irr::core::vector3df rayEnd(sin(cam->getRotation().Y * M_PI / 180.0f) * cos(cam->getRotation().X * M_PI / 180.0f) * 50.0f,
		       -1 * sin(cam->getRotation().X * M_PI / 180.0f) * 50.0f,
		       cos(cam->getRotation().Y * M_PI / 180.0f) * cos(cam->getRotation().X * M_PI / 180.0f) * 50.0f);

	// Reset the transformation matrix for the raycast
	irr::video::SMaterial m;
	m.Lighting=false;
	driver->setMaterial(m);
	driver->setTransform(irr::video::ETS_WORLD, irr::core::matrix4());

	//Draw our laser sight
	driver->draw3DLine(cam->getPosition() + irr::core::vector3df(.1, .01, 0),
			   rayEnd,
			   irr::video::SColor(255, 255, 0, 0));
	
	smgr->drawAll();
	driver->endScene();
	device->run();
    }

    // clean up
    clearObjects();
    delete world;
    delete solver;
    delete dispatcher;
    delete broadphase;
    delete collisionConfiguration;
    device->drop();

   return 0;
}
void Mission::onUpdateActivity(float dt)
{
    _fadTimeout -= dt;
    _interruptTimeout -= dt;

    // important action: ESC - interrupt mission
    if( Gameplay::iGameplay->getKeyboardState()->keyState[0x01] & 0x80 )
    {
        if( _endOfPlayerActivity )
        {
            _scene->getCareer()->setMissionWalkthroughFlag( _wttid, _wtmid, true );
            _endOfMission = true;
        }
        else if( _interruptTimeout < 0 )
        {
            assert( _scene->getCamera() );
            _scene->getCamera()->updateActivity( 0.0f );
            new Interrupt( _scene, _scene->getCamera()->getPose(), &_endOfMission, ( _player->getPhase() != jpRoaming ) );
            _interruptTimeout = 0.25f;
            return;
        }
    }

    // soft time acceleration
    if( _fadValue != _fadTargetValue )
    {
        float fadSpeed =     1.0f;
        float direction = _fadTargetValue - _fadValue;
        if( direction < 0 )
        {
            _fadValue -= fadSpeed * dt;
            if( _fadValue < _fadTargetValue ) _fadValue = _fadTargetValue;
        }
        else
        {
            _fadValue += fadSpeed * dt;
            if( _fadValue > _fadTargetValue ) _fadValue = _fadTargetValue;
        }
        //_scene->setTimeSpeedMultiplier( _fadValue );
    }

    // action: first person mode
    if( Gameplay::iGameplay->getActionChannel( iaCameraMode0 )->getTrigger() )
    {
        setFirstPersonCamera();
		Gameplay::iGameplay->getActionChannel( iaCameraMode0 )->reset();
    }
    // action: third person mode
    if( Gameplay::iGameplay->getActionChannel( iaCameraMode1 )->getTrigger() )
    {
        setThirdPersonCamera();
    }
    // action : flyway mode
    if( Gameplay::iGameplay->getActionChannel( iaCameraMode2 )->getTrigger() )
    {
        _player->happen( this, EVENT_JUMPER_THIRDPERSON, _player );
        _scene->setCamera( _fwcamera );
        _fwcamera->setupCamera( _player, 2.0f, 0.75f );
    }
    // action : free camera
    if( Gameplay::iGameplay->getActionChannel( iaCameraMode3 )->getTrigger() )
    {
        _player->happen( this, EVENT_JUMPER_THIRDPERSON, _player );
        _scene->setCamera( _frcamera );
    }    
    // action: time acceleration
    if( Gameplay::iGameplay->getActionChannel( ::iaAccelerateFlightTime )->getTrigger() && 
        _fadTimeout < 0 && ( _player->getPhase() == ::jpFlight || _player->getPhase() == ::jpRoaming ) )
    {
        _fadTargetValue *= 2.0f;
        if( _fadTargetValue > 4.0f ) _fadTargetValue = 4.0f;
        _fadTimeout = 0.25f;
    }
    // action: time deceleration
    if( Gameplay::iGameplay->getActionChannel( ::iaDecelerateFlightTime )->getTrigger() && 
        _fadTimeout < 0 && ( _player->getPhase() == ::jpFlight || _player->getPhase() == ::jpRoaming ) )
    {
        _fadTargetValue *= 0.5f;
        if( _fadTargetValue < 1.0f ) _fadTargetValue = 1.0f;
        _fadTimeout = 0.25f;
    }

    // reset time deceleration/acceleration
    if( _player->getPhase() == ::jpFreeFalling )
    {
        _fadTargetValue = 1.0f;
    }
    
    // collect forest actors
    unsigned int forestId;
    std::vector<Forest*> forests;
    getScene()->getScenery()->happen( this, EVENT_FOREST_ENUMERATE, &forests );

    // update physics
    _phTimeLeft += dt;
    while( _phTimeLeft > simulationStepTime )
    {
        // begin to simulate physics
        _scene->getPhScene()->simulate( simulationStepTime );
        // PHYSX3
		_scene->getPhScene()->flushSimulation();
        _scene->getPhScene()->fetchResults(true);
        updatePhysics();
        _phTimeLeft -= simulationStepTime;

        // forest interaction
        for( forestId=0; forestId<forests.size(); forestId++ )
        {
            forests[forestId]->simulateInteraction( _player );
        }
    }
    
	//PHYSX3
	//_scene->getPhScene()->visualize();

    // player is over its activity?
    if( !_endOfPlayerActivity && _player->isOverActivity() )
    {
        // raise local switch
        _endOfPlayerActivity = true;  

        // hide HUD
        happen( this, EVENT_HUD_HIDE );
    }

    // important action: TAB - show goals
    if( ( Gameplay::iGameplay->getKeyboardState()->keyState[0x0F] & 0x80 ) || _endOfPlayerActivity )
    {
        if( !goalsIsVisible() )
        {
            showGoals( true );
        }
    }
    else
    {
        if( goalsIsVisible() )
        {
            showGoals( false );
        }
    }
	
	/// NETWORK
	NetworkData *packet = getScene()->network->consumePacketByReceiver(NET_REC_MISSION);
	while (packet != NULL) {
		consumePacket(packet);
		//delete packet;

		packet = getScene()->network->consumePacketByReceiver(NET_REC_MISSION);
	}

	// receive packets for jumpers
	//for (unsigned int i = 0; i < _children.size(); ++i) {
	//	if (strcmp(_children[i]->getName(), "Jumper") != 0) continue;

	//	NetworkData *packet = getScene()->network->consumePacketByReceiver(NET_REC_JUMPER, _children[i]->network_id);
	//	while (packet != NULL) {
	//		_children[i]->consumePacket(packet);
	//		packet = getScene()->network->consumePacketByReceiver(NET_REC_JUMPER, _children[i]->network_id);
	//	}
	//}
}
Example #16
0
void PhysicsProcessor::update(SlowScene *d_scene, float dt)
{
	updatePhysics(dimBlock1, dimGrid1, d_scene, d_V);
	updateScene(dimBlock2, dimGrid2, d_scene, d_V, dt);
}
void PhysicsSim::view(Camera* cam, RenderTarget* pipTarget)
{
	//if (dvc->isWindowActive())
	//{
	updatePhysics();
//*

	driver->beginScene(true, true, SColor(255,255,255,255));

	for(unsigned int i = 0; i < render_targets.size(); i++)
		render_targets[i]->drawAll();

	driver->setRenderTarget(0, true, true, 0);

	smgr->setActiveCamera(cam);

	smgr->drawAll();

	if(pipTarget != NULL)
	{
		pipImage->setImage(pipTarget->target);
	}

	driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
	for(uint i = 0; i < lines.size(); i++)
		drawLine(lines[i].p1, lines[i].p2, lines[i].color);
	lines.clear();

	for(uint i = 0; i < boxes.size(); i++)
		driver->draw3DBox(boxes[i].box, boxes[i].color) ;
	boxes.clear();

	for(uint i = 0; i < images.size(); i++)
	{
		ITexture* tex = driver->getTexture(images[i].name);
		Dimension dim = tex->getOriginalSize();
		driver->draw2DImage(tex, images[i].position,
                                rect<s32>(0,0,dim.Width,dim.Height),0,
                                video::SColor(255,255,255,255), true);
	}
	images.clear();

	for(uint i = 0; i < texts.size(); i++)
	{
		this->font = NULL;
		if(texts[i].size == 0)
			this->font = env->getBuiltInFont();
		else if(texts[i].size == 1)
			this->font = env->getFont(mediaDirectory + "fontcourier.bmp");
		else
			this->font = env->getFont(mediaDirectory + "bigfont.png");
		if(!this->font)
			this->font = env->getBuiltInFont();

		Dimension dim = this->font->getDimension(texts[i].text.c_str());
		this->font->draw(texts[i].text,
							rect<s32>(texts[i].position.X,texts[i].position.Y,texts[i].position.X+dim.Width,texts[i].position.Y+dim.Height),
							texts[i].color);
	}
	texts.clear();

	env->drawAll();
	driver->endScene();

	for(uint i = 0; i < arrows.size(); i++)
	{
		smgr->getMeshCache()->removeMesh(arrows[i]->getMesh());
		arrows[i]->remove();
	}
	arrows.clear();

//*/
	//}
	//else
	//	dvc->yield();
}
void WordTreeScene::update(float dt) {
    if( isIdle==true ) {
        return;
    }
    
    totalIdleTimes += dt;
    if( isProcessing==true ) {
        return;
    }
    else if( totalIdleTimes>=5.0f ) {
        totalIdleTimes = 0.0f;
        CCUserDefault::sharedUserDefault()->setStringForKey("FromCppToObjC", "requestWord");
    }
    
    static CCSize designResolutionSize = CCEGLView::sharedOpenGLView()->getDesignResolutionSize();
    
    ChipmunkManager::getInstance()->update(dt);
    WordModels::getInstance()->update(dt);
    
    Word* word = WordModels::getInstance()->getNotRenderedWord();
    if( word!=NULL ) {
        CCLabelTTF* wordLabel = CCLabelTTF::create(word->getWord()->getCString(), "Arial", DEFAULT_FONT_SIZE);
        
        float offsetX = CCRANDOM_MINUS1_1()*400;
        float offsetY = CCRANDOM_MINUS1_1()*300+100;
        wordLabel->setPosition(ccp(designResolutionSize.width/2+offsetX,designResolutionSize.height/2+offsetY));
        word->setLabel(wordLabel);
        word->setRendered(true);
        
        CCSprite* sprite = CCSprite::create("images/heart.png");
        sprite->setPosition(wordLabel->getPosition());
        CCSize labelSize = wordLabel->getContentSize();
        float spriteScale = MAX(labelSize.width, labelSize.height)/HEART_IMAGE_SIZE;
        sprite->setScale(spriteScale+spriteScale*0.3f);
        word->setSprite(sprite);
        
        this->addChild(sprite);
        this->addChild(wordLabel);
        
        updatePhysics(word);
        word = NULL;
        return;
    }
    
    
    word = WordModels::getInstance()->getDirtyWord();
    if( word!=NULL ) {
        CCLabelTTF* wordLabel = word->getLabel();
        CCSprite* sprite = word->getSprite();
        if( wordLabel!=NULL && sprite!=NULL ) {
            wordLabel->setFontSize(DEFAULT_FONT_SIZE+LABEL_INCREASE_SCALE_PER_WORD*word->getCount());
            
            CCSize labelSize = wordLabel->getContentSize();
            float spriteScale = MAX(labelSize.width, labelSize.height)/HEART_IMAGE_SIZE;
            sprite->setScale(spriteScale+spriteScale*0.3f);
            
            CCScaleTo* scaleUp = CCScaleTo::create(0.2f, spriteScale+spriteScale*0.5f);
            CCEaseIn* in = CCEaseIn::create(scaleUp, 2.0f);
            
            CCScaleTo* scaleDown = CCScaleTo::create(0.2f, spriteScale+spriteScale*0.3f);
            CCEaseOut* out = CCEaseOut::create(scaleDown, 2.0f);
            
            CCSequence* sequence = CCSequence::create(in, out, NULL);
            sprite->runAction(sequence);
            
            updatePhysics(word);
        }
        return;
    }
}
Example #19
0
void Mission::onUpdateActivity(float dt)
{
        _fadTimeout -= dt;
        _interruptTimeout -= dt;

        // important action: ESC - interrupt mission
        if( Gameplay::iGameplay->getKeyboardState()->keyState[0x01] & 0x80 )
        {
                if( _endOfPlayerActivity )
                {
                        _scene->getCareer()->setMissionWalkthroughFlag( _tournamentInfo, _wtmid, true );
                        _endOfMission = true;
                }
                else if( _interruptTimeout < 0 )
                {
                        assert( _scene->getCamera() );
                        _scene->getCamera()->updateActivity( 0.0f );
                        new Interrupt( _scene, _scene->getCamera()->getPose(), &_endOfMission, ( _player->getPhase() != jpRoaming ) );
                        _interruptTimeout = 0.25f;
                        return;
                }
        }

        // soft time acceleration
        if( _fadValue != _fadTargetValue )
        {
                float fadSpeed =     1.0f;
                float direction = _fadTargetValue - _fadValue;
                if( direction < 0 )
                {
                        _fadValue -= fadSpeed * dt;
                        if( _fadValue < _fadTargetValue ) _fadValue = _fadTargetValue;
                }
                else
                {
                        _fadValue += fadSpeed * dt;
                        if( _fadValue > _fadTargetValue ) _fadValue = _fadTargetValue;
                }
                _scene->setTimeSpeedMultiplier( _fadValue );
        }

        // action: first person mode
        if( Gameplay::iGameplay->getActionChannel( iaCameraMode0 )->getTrigger() )
        {
                setFirstPersonCamera();
        }
        // action: third person mode
        if( Gameplay::iGameplay->getActionChannel( iaCameraMode1 )->getTrigger() )
        {
                setThirdPersonCamera();
        }
        // action: follow mode
        if( Gameplay::iGameplay->getActionChannel( iaCameraMode4 )->getTrigger() )
        {
                setFollowCamera();
        }
        // action : flyway mode
        if( Gameplay::iGameplay->getActionChannel( iaCameraMode2 )->getTrigger() )
        {
                _player->happen( this, EVENT_JUMPER_THIRDPERSON, _player );
                _scene->setCamera( _fwcamera );
                _fwcamera->setupCamera( _player, 2.0f, 0.75f );
        }
        // action : free camera
        if( Gameplay::iGameplay->getActionChannel( iaCameraMode3 )->getTrigger() )
        {
                _player->happen( this, EVENT_JUMPER_THIRDPERSON, _player );
                _scene->setCamera( _frcamera );
        }    
        // action: time acceleration
        if( Gameplay::iGameplay->getActionChannel( ::iaAccelerateFlightTime )->getTrigger() && 
                _fadTimeout < 0 && ( _player->getPhase() == ::jpFlight || _player->getPhase() == ::jpRoaming ) )
        {
                _fadTargetValue *= 2.0f;
                if( _fadTargetValue > 4.0f ) _fadTargetValue = 4.0f;
                _fadTimeout = 0.25f;
        }
        // action: time deceleration
        if( Gameplay::iGameplay->getActionChannel( ::iaDecelerateFlightTime )->getTrigger() && 
                _fadTimeout < 0 && ( _player->getPhase() == ::jpFlight || _player->getPhase() == ::jpRoaming ) )
        {
                _fadTargetValue *= 0.5f;
                if( _fadTargetValue < 1.0f ) _fadTargetValue = 1.0f;
                _fadTimeout = 0.25f;
        }

        // reset time deceleration/acceleration
        if( _player->getPhase() == ::jpFreeFalling )
        {
                _fadTargetValue = 1.0f;
        }

        // collect forest actors
        unsigned int forestId;
        std::vector<Forest*> forests;
        getScene()->getScenery()->happen( this, EVENT_FOREST_ENUMERATE, &forests );

        // update physics
        _phTimeLeft += dt;
        while( _phTimeLeft > simulationStepTime )
        {
                // begin to simulate physics
                _scene->getPhScene()->simulate( simulationStepTime );
                _scene->getPhScene()->flushStream();
                _scene->getPhScene()->fetchResults( NX_RIGID_BODY_FINISHED, true );
                updatePhysics();
                _phTimeLeft -= simulationStepTime;

                // forest interaction
                for( forestId=0; forestId<forests.size(); forestId++ )
                {
                        forests[forestId]->simulateInteraction( _player );
                }
        }
        _scene->getPhScene()->visualize();

        // player is over its activity?
        if( !_endOfPlayerActivity && _player->isOverActivity() )
        {
                // raise local switch
                _endOfPlayerActivity = true;  

                // hide HUD
                happen( this, EVENT_HUD_HIDE );
        }

        // important action: TAB - show goals
        if( ( Gameplay::iGameplay->getKeyboardState()->keyState[0x0F] & 0x80 ) || _endOfPlayerActivity )
        {
                if( !goalsIsVisible() )
                {
                        showGoals( true );
                }
        }
        else
        {
                if( goalsIsVisible() )
                {
                        showGoals( false );
                }
        }
}
Example #20
0
bool Game::update( float dt )
{
    m_lastRealDt = dt;

    if (m_pauseUpdates)
        m_lastDt = 0.f;
    else
        m_lastDt = dt;

    DebugDrawer::getSingleton().clear();

#ifdef ENABLE_BULLET_DEBUG_DRAW
    if (s_EnableBulletDebugDraw)
    {
        g_debugPhysicsDrawer->setDebugMode(true);
        g_debugPhysicsDrawer->step();
        m_physicsWorld->debugDrawWorld();
    }
    else if (g_debugPhysicsDrawer->getDebugMode())
    {
        g_debugPhysicsDrawer->setDebugMode(false);
        g_debugPhysicsDrawer->step();
    }
#endif

    updateInput(dt);

    if (m_pauseUpdates)
        updateLogic(0.f);
    else
    {
        const float logic_dt = dt * m_slomo;
        float logic_dt_left = logic_dt;
        m_logicTime += logic_dt;

        do 
        {
            const float it_dt = std::min(logic_dt_left, dt);
            updateLogic(it_dt);

            logic_dt_left -= it_dt;
        } while (logic_dt_left > 0.001f);

        updatePhysics(logic_dt);
    }

    updateVisuals(dt);

    DebugDrawer::getSingleton().build();

    if (s_ForceLowFramerate && dt < 0.1f)
        Sleep(100);

    if (!m_ogreRoot->renderOneFrame(dt))
        return false;

    if (m_renderWindow->isClosed())
        return false;

    if (m_exit)
        return false;

    return true;
}
Example #21
0
void OEMFGame :: run()
{
	// clearWithColor(0x000000, false);
	// refresh();
	refreshCentered();
	refreshScoreBoard();
	updateScreen();
	
	Uint32 start = SDL_GetTicks();
	Sint32 waitTime = 0;
	
	SDL_Event event;
	while (!m_done) 
	{
		if ((waitTime = SDL_GetTicks() - start) >= m_frameDuration) 
		{
			start = SDL_GetTicks();
			//refresh();
			refreshCentered();
			refreshScoreBoard();
			updateScreen();
		}
		handleInput();
		updatePhysics();
		
		// handle flags
		if (m_requestFlagDie)
		{
			m_requestFlagDie = false;
			die();
		}
		if (m_requestFlagEnd)
		{
			m_requestFlagEnd = false;
			endLevel();
			initialize();
		}
		
		Uint32 sym;
		/* Check for events */
		while (SDL_PollEvent(&event)) 
		{
			switch (event.type) 
			{
				case SDL_MOUSEMOTION:
					break;
				case SDL_MOUSEBUTTONDOWN:
					break;
				case SDL_KEYDOWN:
					if (event.key.keysym.sym == SDLK_ESCAPE)
					{	
						string options[2] = {string("No"), string("Yes")};
						if (chooseList(0, "Are you sure you want to end the game?", options, 2) == 1)
							m_done = 1;
					}
					else if (event.key.keysym.sym == SDLK_q)
					{
						m_frameDuration-=10;
					}
					else if (event.key.keysym.sym == SDLK_w)
					{
						m_frameDuration+=10;
					}
					else if (event.key.keysym.sym == SDLK_e)
					{
						m_delayTime--;
						printf("m_delayTime = %d\n", m_delayTime);
					}
					else if (event.key.keysym.sym == SDLK_r)
					{
						m_delayTime++;
						printf("m_delayTime = %d\n", m_delayTime);
					}
					else if (event.key.keysym.sym == SDLK_p)
					{
						SDL_SaveBMP(m_screen, "screenshot.bmp");
					}
					else
					{
						// key array
						sym = event.key.keysym.sym;
						if (sym < KEYCOUNT)
						{
							m_keyDown[sym] = true;
						}
					}
					break;
				case SDL_KEYUP:
					// key array
					sym = event.key.keysym.sym;
					if (sym < KEYCOUNT)
					{
						m_keyDown[sym] = false;
					}
					break;
				case SDL_QUIT:
					m_done = 1;
					break;
				default:
					break;
			}
		}
//		Uint32 start2 = SDL_GetTicks();
//		while (SDL_GetTicks() - start2 < m_delayTime);
		
		SDL_Delay(m_delayTime);
		
//		frameDuration = SDL_GetTicks() - start;
//		waitTime = 20 - (Sint32) frameDuration;
//		if (waitTime > 0)
//			SDL_Delay(waitTime);
	}
}
Example #22
0
void REV_process(tMapQ3 * map)
{
	//Variables
	f32 preWait = 0, postWait = 0;
	static u8 firstFrame = 1;
	TRACKER * auxT;
	setUp3D();
	//Wait just before drawing (instead of after), this should enhance performance
	VIDEO_Flush();
	preWait = (f32)(ticks_to_millisecs(gettime()));
 	VIDEO_WaitVSync();
	postWait = (f32)(ticks_to_millisecs(gettime()));
	GPUWaitTime = 0.001f * (postWait - preWait);
	//Update physics
	updatePhysics();
	setBGColor(SC_BLUE);
	//Clasify objects into solid or transparent queues
	//This is done before everything else because this clasification is the same for every viewport
	clasify3D(mainRoot->rootNode);
	//Now we use the clasified queues to render shadows
	//if(mainRoot->shadowCaster)
		//mainRoot->shadowScene();
	//Render each Viewport into it's texture
	GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
	//GX_SetZMode (GX_TRUE, GX_LEQUAL, GX_TRUE);
	std::multimap<CAMERA*, TRender2Texture*>::iterator iter = mainRoot->m_Render2Textures.begin();
	for(;iter != mainRoot->m_Render2Textures.end(); ++iter)
	{
		(*iter).second->setForRender(perspective);
		(*iter).second->getCamera()->setForRender(view);
		//Before rendering the scene, render the skyBox
		GX_SetZMode (GX_FALSE, GX_LEQUAL, GX_TRUE);
		mainRoot->skyBox.render((*iter).second->getCamera());
		GX_SetZMode (GX_TRUE, GX_LEQUAL, GX_TRUE);
		//Now render the map
		//GX_LoadPosMtxImm(view, GX_PNMTX0);
		//if(map)
			//renderQ3Map(tTex->cam->getPos(), map);
		//Now render objects
		GX_SetCullMode(GX_CULL_NONE);
		auxT = solidQueue;
		while(auxT)
		{
			render(auxT->target, (*iter).second->getCamera()->getPos());
			auxT = auxT->next;
		}
		orderQueue((*iter).second->getCamera());
		auxT = transQueue;
		while(auxT)
		{
			render(auxT->target, (*iter).second->getCamera()->getPos());
			auxT = auxT->next;
		}
		//Copy the embeded frame buffer to the texture
		(*iter).second->copyTexture();
	}
	while(solidQueue)
	{
		auxT = solidQueue;
		solidQueue = solidQueue->next;
		free(auxT);
	}
	while(transQueue)
	{
		auxT = transQueue;
		transQueue = transQueue->next;
		free(auxT);
	}
	setBGColor(SC_WHITE);
	//2D System
	//GX_SetZMode (GX_FALSE, GX_LEQUAL, GX_TRUE);
	GX_SetCopyFilter(rMode->aa,rMode->sample_pattern,GX_TRUE,rMode->vfilter);
	GX_SetViewport(0,0, w, h,0,1);
	GX_SetScissor(0,0, w, h);
	guOrtho(perspective,0,h,0,w, 1.0,100.0);
	GX_LoadProjectionMtx(perspective, GX_ORTHOGRAPHIC);
	GX_SetCullMode(GX_CULL_NONE);
	setUp2D();
	parse2D(mainRoot->rootN2D);
	order2D();
	render2D();
	GX_DrawDone();
	
	GX_CopyDisp(frameBuffer[fb],GX_TRUE);
	VIDEO_SetNextFramebuffer(frameBuffer[fb]);
	
	//Set out black screen after first frame
	if(firstFrame)
	{
		firstFrame = 0;
		VIDEO_SetBlack(FALSE);
	}
	
	fb ^= 1;
}
Example #23
0
bool Unit::update( const Frame& frame )
{
	const StackData& param = frame.params[0];

	switch(frame.command){
		case acNone:
			break;

		// Functions
		case acSuper:
			Actions.saveState( true );
			Actions.setParentAction( param.stringData );
			break;
		case acRestoreState:
			// This is return for acSuper command. It does nothing if no saved state .
			Actions.restoreState();
			break;
		case acSetAction:
			// If param is not null, it will be action call, not replacing
			if( Actions.checkFrameParams( frame, 1, stStringOrNone ) ){
				Actions.setAction( param.stringData );
				return false;
			}
			break;
		case acSetTimer:
			if( Actions.checkFrameParams( frame, 2, stFunction, stInt ) ){
				ActionTimer* timer = actionTimers;
				const Frame* pframe = &frame;
				while( timer != NULL ){
					if( timer->frame == pframe )
						break;
					timer = timer->next;
				}
				if( !timer || !Timer::UpdateEventById( timer->timerId, frame.params[1].intData) ){
					if( timer ){
						ActionTimer* oldtimer = actionTimers;
						while( timer != NULL ){
							// ActionTimer is deleted from manager. Delete it from holder.
							if( oldtimer->next == timer ){
								oldtimer->next = oldtimer->next->next;
								delete timer, timer = NULL;
								break;
							}
							timer = timer->next;
						}
					}
					IActionTimer* t = new IActionTimer( this, param.intData );
					actionTimers = new ActionTimer( pframe, t, actionTimers );
					actionTimers->timerId = Timer::AddInternalTimerEvent( t, frame.params[1].intData );
				}
			}
			break;

		// Action parameters stack
		case acPushInt:
			Actions.params.Push( param.intData );
			break;
		case acPushFloat:
			//TODO: float
			Actions.params.Push( param.intData );
			Debug::debug( Debug::PROTO, "acPushFloat not implemented.\n" );
			break;
		case acPushString:
			Actions.params.Push( param.stringData );
			break;
		case acPush:
			for( int i = 0; i < FRAME_PARAMS_COUNT; ++i ){
				switch( frame.param_types[i] ){
					case stInt:
						Actions.params.Push( frame.params[i].intData );
						break;
					case stString:
						Actions.params.Push( frame.params[i].stringData );
						break;
					default:
						break;
				}
			}
			break;

		// Conditions
		case acCondition: // acCondition always false
			Actions.frame = frame.condition_end;
			break;
		case acEnd: // Do nothing
			break;



		case acIfParamEqual:
			PARAMCOND( != )
			break;
		case acIfParamLess:
			PARAMCOND( > )
			break;
		case acIfParamMore:
			PARAMCOND( < )
			break;


		case acIfParametersEqual:
			PARAMSCOND( != )
			break;
		case acIfParametersLess:
			PARAMSCOND( > )
			break;
		case acIfParametersMore:
			PARAMSCOND( < )
			break;
		case acIfParametersLessBy:
			PARAMSCOND( + param.intData > )
			break;



		// Unit flags
		case acIfFlag:
			CHECKFLAG
				if( !( flags & param.intData ) )
					Actions.frame = frame.condition_end;
			break;
		case acIfNotFlag:
			CHECKFLAG
				if( flags & param.intData )
					Actions.frame = frame.condition_end;
			break;
		case acSetFlag:
			CHECKFLAG
				flags |= param.intData;
			break;
		case acRemoveFlag:
			CHECKFLAG
				flags &= ~param.intData;
			break;



		// Unit Parameters
		case acSetParam:
			if( Actions.checkFrameParams( frame, 2, stInt, stInt ) )
				Char.set( param.intData, (float)frame.params[1].intData );
			else
				Debug::debug( Debug::PROTO, "acSetParam bad parameter name.\n" );
			break;
		case acCopyParam:
			if( !Actions.checkFrameParams( frame, 2, stInt, stInt ) )
				Debug::debug( Debug::PROTO, "acCopyParam bad original parameter name.\n" );
			else if( !param.intData )
				Debug::debug( Debug::PROTO, "acCopyParam bad parameter name.\n" );
			else
				Char.set( param.intData, Char.get( frame.params[1].intData ) );
			break;
		case acLoadParam:
		{
			if( !Actions.checkFrameParams( frame, 2, stInt, stString ) )
				break;
			LuaConfig* cfg = new LuaConfig;
			if( param.intData < uCharIntLast )
				cfg->getValue( frame.params[1].stringData, UnitName, TypeName,
								Char.getRef( (enum character)param.intData ) );
			else
				cfg->getValue( frame.params[1].stringData, UnitName, TypeName,
								Char.getRef( (enum character_float)param.intData ) );
			delete cfg;
			break;
		}
		case acLoadParamBunch:
		{
			if( param.intData <= 0 )
				break;
			LuaConfig* cfg = new LuaConfig;
			for( int i = 0; i < param.intData; i++ ){
				if( !Actions.params.CheckParamTypes( 2, stInt, stString ) ){
					Debug::debug( Debug::PROTO, "acLoadPraramBunch wrong " +
							citoa(i+1) + " parameter set.\n" );
					continue;
				}
				int psparam = Actions.params.PopInt();
				if( psparam < uCharIntLast )
					cfg->getValue( Actions.params.PopString(), UnitName, TypeName,
							Char.getRef( (enum character)psparam ) );
				else
					cfg->getValue( Actions.params.PopString(), UnitName, TypeName,
							Char.getRef( (enum character_float)psparam ) );
			}
			delete cfg;
			break;
		}


		// Physics
		case acSetUnitPhysics:
			if( Actions.checkFrameParams( frame, 3, stInt, stInt, stIntOrNone ) ){
				int firstparam = frame.params[1].intData;
				switch(param.intData){
					case pptMat:
						break;
					case pptRadius:
						phys.radius = firstparam;
						break;
					case pptSides:
						phys.sides.x = firstparam;
						phys.sides.y = frame.params[2].intData;
						break;
				}
				phys.calc_mass();
				updatePhysics( );
			}
			break;
		case acSetPhysicsLayer:
			if( Actions.checkFrameParams( frame, 1, stInt ) && physShape != NULL )
				cpShapeSetGroup( physShape, param.intData );
			break;

		// Misc
		case acSetUnitSize:
			if( Actions.checkFrameParams( frame, 1, stInt ) )
				setUnitSize( static_cast<float>(param.intData) / 100 );
			break;
		case acSetColor:
			if( Actions.checkFrameParams( frame, 4, stInt, stInt, stInt, stInt ) )
				Image.getSprite()->clr.set( frame.params[0].intData, frame.params[1].intData,
						frame.params[2].intData, frame.params[3].intData );
			break;

		default:
			return false;
	}
	return true;
}
Example #24
0
int main(void)
{
    if( !initContext(&context) )
    {
        fprintf(stderr, "Failed to initialize application\n");
        return -1;
    }

    window = context.window;

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // Create and compile our GLSL program from the shaders
    /* GLuint programID = LoadShaders("data/shader/SimpleVertexShader.vertexshader", "data/shader/SimpleFragmentShader.fragmentshader"); */
    Shader s("data/shader/SimpleVertexShader.vertexshader", "data/shader/SimpleFragmentShader.fragmentshader");
    /* Shader s("data/shader/font_shader.vert", "data/shader/font_shader.frag"); */
    if( !s.link() )
    {
        fprintf(stderr, "Failed to initialize main shader\n");
        return -1;
    }
    programID = s.getProgramId();

    /* Shader gui_shader("data/shader/GuiShader.vert", "data/shader/GuiShader.frag"); */
    /* Shader gui_shader("data/shader/GuiShader.vert", "data/shader/SimpleFragmentShader.fragmentshader"); */
    /* gui_shader.link(); */

	//Create vertex buffer
	GLuint vertex_buffer;
	glGenBuffers(1, &vertex_buffer);
	glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

	//Create texture coordinate buffer
	GLuint texcoordbuffer;
	glGenBuffers(1, &texcoordbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, texcoordbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_texture_coordinates), g_texture_coordinates, GL_STATIC_DRAW);


	GLuint colorbuffer;
	glGenBuffers(1, &colorbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);

	/* GLuint projection_view_loc = glGetUniformLocation(programID, "projection_view"); */

    context.velocity = glm::vec3(0,0,0);

    int png_width, png_height;
//    GLuint font_texture = png_texture_load("data/font/monospaced_bold.png", &png_width, &png_height);
    glBindAttribLocation(programID, ATTRIB_VERTEX_POSITION_LOC, ATTRIB_VERTEX_POSITION_NAME);
    glBindAttribLocation(programID, ATTRIB_VERTEX_COLOR_LOC,    ATTRIB_VERTEX_COLOR_NAME);

    // Prepare rendering
    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glVertexAttribPointer(
            ATTRIB_VERTEX_POSITION_LOC, 3,
            GL_FLOAT, // type
            GL_FALSE, // normalized?
            0,        // stride
            (void*)0  // array buffer offset
            );
    //
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glVertexAttribPointer(
            1,                                // attribute. No particular reason for 1, but must match the layout in the shader.
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
            );
    //
    glEnableVertexAttribArray(3);
    glBindBuffer(GL_ARRAY_BUFFER, texcoordbuffer);
    glVertexAttribPointer(
            3,
            2,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
            );

    onWindowResize(context.window, context.width, context.height);

    context.do_stop = false;
    while( !context.do_stop )
    {
        // Update timing related stuff
        context.time_last_frame = context.time_now;
        context.time_now = glfwGetTime();
        context.time_delta = context.time_now - context.time_last_frame;

        updatePhysics(&context);
        manageUserInput(&context);
        render(&context);

        // Main loop cleanup
        // TODO is this needed?
		/* glDisableVertexAttribArray(0); */

		// Swap buffers
		glfwSwapBuffers(context.window);
		glfwPollEvents();
	}

	// Cleanup VBO
	glDeleteBuffers(1, &vertex_buffer);
	glDeleteVertexArrays(1, &VertexArrayID);

	// Close OpenGL window and terminate GLFW
	glfwTerminate();

	return 0;
}