Beispiel #1
0
/** The main loop. **/
void CEngine::Start()
{
	m_lLastTick = SDL_GetTicks();
	m_bQuit = false;

	// Main loop: loop forever.
	while ( !m_bQuit )
	{
		// Handle mouse and keyboard input
		HandleInput();

		if ( m_bMinimized ) {
			// Release some system resources if the app. is minimized.
			//WaitMessage(); // pause the application until focus in regained
		} else {
			// Do some thinking
			DoThink();

			// Render stuff
			DoRender();
		}
	}

	End();
}
Beispiel #2
0
void XWindow::Start()
{
  int64_t previous = Ticks();
  int64_t updateLag = 0;
  int64_t renderLag = 0;
  while (!m_asked_to_stop) {
    int64_t current = Ticks();
    int64_t elapsed = current - previous;
    previous = current;
    updateLag += elapsed;
    renderLag += elapsed;
    int64_t wait_time = std::min(TicksPerFrame() - renderLag, TicksPerUpdate() - updateLag);
    if (wait_time > 0) {
      int64_t wait_started = Ticks();
      while (Ticks() < wait_started + wait_time) {
        // active waiting
      }
    }
    while (updateLag >= TicksPerUpdate()) {
      Update();
      HandleInput();
      updateLag -= TicksPerUpdate();
    }
    if (renderLag >= TicksPerFrame()) {
      Render(1.0 * updateLag / TicksPerUpdate());
      XFlush(m_pDisplay);
      renderLag = 0;
    }
  }
}
int main(int argc, char *argv[]) {


	int startticks = 0, fpsticks = 0;

	Initialize();

	do {

		startticks = SDL_GetTicks();

		HandleInput();

		Update(/*SDL_GetTicks()-startticks*/ );

		Render();

		fpsticks = SDL_GetTicks() - startticks;

		if(fpsticks < 1000/FPS) {

			SDL_Delay((1000/FPS-fpsticks));

		}

	} while( !g_bEndGame );

	Release();

    return EXIT_SUCCESS;
}
Beispiel #4
0
void CMenu::Draw()
{
	// If we don't need to draw the menu, quit
	if(!m_bShowMenu) return;

	// Draw the main menu with it's preset dimensions
	DrawBox(kMenuWidth, kMenuHeight, kMenuX, kMenuY);

	// Create and draw 4 buttons for the main menu
	DrawString("Inventory", 9, kMenuX + 5, kMenuY + 3, NULL,  ShowInventoryMenu);
	DrawString("Load Game", 9, kMenuX + 5, kMenuY + 6, NULL,  ShowLoadMenu);
	DrawString("Save Game", 9, kMenuX + 5, kMenuY + 9, NULL,  ShowSaveMenu);
	DrawString("Quit",      4, kMenuX + 5, kMenuY + 12, NULL, Quit);

	// Loop until the user either makes a choice or hits escape
	while(!m_bEscapePressed && !m_menuChoice)
	{
		// Check for user input
		HandleInput();
	}

	// Reset some member variables and redraw the screen before executing a function pointer
	m_bEscapePressed = false;
	m_bShowMenu = false;

	g_Map.SetDrawFlag(true);
	g_Map.Draw();

	// If there is a menu choice, let's call the function associated with that button
	if(m_menuChoice)
		m_menuChoice->m_function();
}
Beispiel #5
0
VOID COGLAppBase::Run()
{
    MSG msg;
    ZeroMemory( &msg, sizeof(msg) );

	LARGE_INTEGER timeStart;
	LARGE_INTEGER timeEnd;
	LARGE_INTEGER timerFrequency;
	QueryPerformanceFrequency(&timerFrequency);
	double fi = 1000.0/(double)timerFrequency.QuadPart;

    while( msg.message!=WM_QUIT )
    {
        if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
		{
			QueryPerformanceCounter(&timeStart);

			UpdateScene();
			DrawBase();
			HandleInput();

			QueryPerformanceCounter(&timeEnd);

			// the time elapsed since the last frame is stored in m_timeElapsed
			m_timeElapsed = (float)((timeEnd.QuadPart - timeStart.QuadPart)*fi);
		}
    }

	Cleanup();
}
void InputHandler_Win32_Pump::InputThreadMain()
{
	if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) )
		LOG->Warn( werr_ssprintf(GetLastError(), "Failed to set Pump thread priority") );

	/* Enable priority boosting. */
	SetThreadPriorityBoost( GetCurrentThread(), FALSE );

	vector<WindowsFileIO *> apSources;
	for( int i = 0; i < NUM_PUMPS; ++i )
	{
		if( m_pDevice[i].io.IsOpen() )
			apSources.push_back( &m_pDevice[i].io );
	}

	while( !m_bShutdown )
	{
		CHECKPOINT;
		int iActual = 0, iVal = 0;
		int iRet = WindowsFileIO::read_several( apSources, &iVal, iActual, 0.100f );

		CHECKPOINT;
		if( iRet <= 0 )
			continue; /* no event */

		HandleInput( iActual, iVal );
		InputHandler::UpdateTimer();
	}
	CHECKPOINT;
}
Beispiel #7
0
void Game::GameLoop() {
    
    isRunning = true;
    hasStarted = false;
    
    float desiredFrameFreq = 1.0 / 120.0;
    
    clock_t lastTime = clock();
    while (isRunning == true) {
        clock_t currentTime = clock();
        double delta = difftime(currentTime, lastTime) / CLOCKS_PER_SEC;
        lastTime = currentTime;
        
        while (delta < desiredFrameFreq) {
            delta += desiredFrameFreq;
            
            HandleInput();
            Update(desiredFrameFreq);
        }
        
        Render();
    }
    
    Shutdown();
    
}
Beispiel #8
0
//update the game
void GameWindow::Update()
{
	//if in game
	if(m_bInGame){
		//Spawn Enemies
		Spawn();
		//check for damage
		Damage();
		//run enemy ai
		for(int i = 0; i < 7; i++){
			if(m_eAllEnemies[i].m_bOnScreen){
				m_eAllEnemies[i].AI(m_pPlatformList, m_PlatformCount, m_wPlayer);
			}
		}
		//move all entities
		Movement();
		//check players displayed image
		m_wPlayer.SwapImage();
		m_wPlayer.Tick();
		//apply gravity to all entities
		Gravity();
		//reset player velocity
		m_wPlayer.m_xVelocity = 0;
	}
	//handle key input
	HandleInput();
	//draw all images and sprites
	Draw();
	//check if game over
	EndGame();
}
Beispiel #9
0
void DirectIP::OnKeyDown(const ::SDL_KeyboardEvent& key)
{
	switch(key.keysym.sym)
	{
		case SDLK_UP:
			if(!addr.empty())
				SetNextActivity(new Fade(new Game(true, addr, connection_ptr()), world, eye), true);
			break;
		case SDLK_DOWN:
			if(!addr.empty())
				SetNextActivity(new Fade(new Game(false, addr, connection_ptr()), world, eye), true);
			break;
		case SDLK_ESCAPE:
			SetNextActivity(new Fade(new Menu, world, eye), true);
			break;
		default:
			break;
	}
	// Hantera input, sortera bort oönskade tecken.
	HandleInput(key, addr);
	addr = StripCharacters(addr, "abcdefghijklmnopqrstuvwxyz,!?+-:/ =");

	if(addr.size() >= max_addr_len)
		addr = addr.substr(0, max_addr_len);

	world[0] = object_ptr(new Text(addr, Letter(Size(0.05,0.07,0.0), 0.03, 2.5, Color(0,0,0)),
		Point(2.4, 2, 1+MILLI), Size(1.3, 0.2,0), Color(0.3,0.3,0.3), Rotation(), false));
}
Beispiel #10
0
/*
==================
Connection::MainLoop

Return values:
	-1   on error
	 0   on success
==================
*/
int Connection::MainLoop() {
	pthread_t inputThread;

	if (pthread_mutex_init(&inlock, NULL)) {
		Error("Failed to create mutex", errno);
		return -1;
	}

	if (pthread_create(&inputThread, NULL, &StdinThread, NULL)) {
		Error("Failed to create stdin-thread", errno);
		return -1;
	}

	if (!channel->Init()) {
		return -1;
	}

	while (!quit) {
		while (socket->HasData())  {
			DispatchPacket();
		}
			
		HandleInput();

		usleep(10000);
	}

	socket->Disconnect();

	t_continue = false;
	pthread_join(inputThread, NULL);
	pthread_mutex_destroy(&inlock);

	return 0;
}
Beispiel #11
0
void gameEngine::Start()
{
	while (!m_bQuit)
	{
		if (gi_ptr == 0)
		{
			m_bQuit = true;
			continue;
		}
		gi_ptr->Load();
		while(gi_ptr->Running())
		{
			HandleInput();
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glClearColor(0.1, 0.1, 0.1, 1);
			gi_ptr->Step();
			CEGUI::System::getSingleton().renderGUI();
			SDL_GL_SwapBuffers();
		}
		gi_ptr->Unload();
		delete gi_ptr;
		gi_ptr = 0;
		if (nextInstance != 0)
		{
			gi_ptr = nextInstance;
			nextInstance = 0;
		}
	}
}
Beispiel #12
0
	void Window::Update(float dt)
	{
		//Event polling
		while (SDL_PollEvent(&e))
		{
			switch( e.type )
			{
				//If user closes the window
				case SDL_QUIT:
					Core::GetInstance()->SetState(-1);
					break;

				case SDL_WINDOWEVENT:	
				{
					if( e.window.event == SDL_WINDOWEVENT_RESIZED )
					{
						WINDOW_W = e.window.data1;
						WINDOW_H = e.window.data2;
						GetSystem(Graphics)->UpdateScreenDims(WINDOW_X, WINDOW_Y, WINDOW_W, WINDOW_H);
						break;
					}
				}
				
				default:
					HandleInput(e, dt);
					break;
			};
		}


		//SDL_RenderClear(renderer);
		//SDL_RenderPresent(renderer);
	}
Beispiel #13
0
/* Loop, synchronously processing requests from clients. */
static void
ClientLoop(void)
{
    int		i, sts;
    int		maxFd;
    __pmFdSet	readableFds;

    for (;;) {
	/* Figure out which file descriptors to wait for input on.  Keep
	 * track of the highest numbered descriptor for the select call.
	 */
	readableFds = sockFds;
	maxFd = maxSockFd + 1;

	sts = __pmSelectRead(maxFd, &readableFds, NULL);

	if (sts > 0) {
	    if (pmDebug & DBG_TRACE_APPL0)
		for (i = 0; i <= maxSockFd; i++)
		    if (__pmFD_ISSET(i, &readableFds))
			fprintf(stderr, "__pmSelectRead(): from %s fd=%d\n",
				FdToString(i), i);
	    __pmServerAddNewClients(&readableFds, CheckNewClient);
	    HandleInput(&readableFds);
	}
	else if (sts == -1 && neterror() != EINTR) {
	    __pmNotifyErr(LOG_ERR, "ClientLoop select: %s\n", netstrerror());
	    break;
	}
	if (timeToDie) {
	    SignalShutdown();
	    break;
	}
    }
}
void PlayerUIDialog::OnTick(float deltaTime)
{
  VDialog::OnTick(deltaTime);

#if defined (SUPPORTS_MULTITOUCH) && (HAVOK_VISION_RESTRUCTURING) && !defined(_VISION_ANDROID)

  if (m_touchInput != NULL)
  {     
    int count = m_touchInput->GetNumberOfTouchPoints();
    if (count > 1)
      return;
  }

#endif

  RPG_Character *characterEntity = static_cast<RPG_Character *>(m_playerController->GetOwner());
  if (!characterEntity)
  {
    // @todo: handle player death properly
    Vision::Error.Warning("Player character has probably died, which isn't yet handled. Set the character's Unlimited Health entity property to true to prevent this.");
    return;
  }

  HandleInput(characterEntity);
  RPG_GuiManager::GetInstance()->OnTick(deltaTime);
}
Beispiel #15
0
void CShop::Draw()
{
	// This draws the first menu to the player to have them select if they
	// want to buy or sell items.  First, draw menu and it's buy/sell buttons
	DrawBox(kShopPromptWidth, kShopPromptHeight, kMenuX, kMenuY);

	DrawString("Buy", 3, kMenuX + kTileWidth, kMenuY + kTileWidth-3, NULL,  ShowBuyMenu);
	DrawString("Sell", 4, kMenuX + kTileWidth*3, kMenuY + kTileWidth-3, NULL,  ShowSellMenu);

	// Swap the buffers to display the change
	g_Buffer.SwapBackBuffer(FALSE);

	// Loop until the user escapes or clicks on one of the buttons
	while(!EscapePressed() && !ChoiceMade())
	{
		HandleInput();
	}

	// Reset the flag that says we hit escape and redraw the map
	ResetEscapeFlag();
	g_Map.SetDrawFlag(true);
	g_Map.Draw();
	g_Buffer.SwapBackBuffer(FALSE);

	// If there was a button clicked, let's go to it's associated function
	if(ChoiceMade())
		ChoiceMade()->m_function();

	// More pausing for feeling :)
	Sleep(100);
}
Beispiel #16
0
void Game::Run(int argc, char* argv[]){
	Initialize(argc, argv);

	mRunning = gGlobalContext.gameStateManager->IsValid();

	while(mRunning){
		float dt = mWindow.GetFrameTime();
		gGlobalContext.gameStateManager->SetFrameDeltaTime(dt);

		HandleInput();
		if(!gGlobalContext.gameStateManager->IsValid()) mRunning = false;
		if(!mRunning) break;

		gGlobalContext.gameStateManager->Update();

		mWindow.Clear();

		gGlobalContext.gameStateManager->RenderScene(mWindow);

		mWindow.Display();

		sf::Sound::Status s = mBackgroundMusic.GetStatus();
		if(gGameSettings.MusicOn){
			if(s == sf::Sound::Paused) mBackgroundMusic.Play();
		}else{
			if(s == sf::Sound::Playing) mBackgroundMusic.Pause();
		}

		sf::Sleep(0.001f);
	}

	Clear();
}
Beispiel #17
0
bool Socket::HandleGameInput()
{
    World* world = World::GetPtr();
    Player* mob = GetPlayer();
    std::string input;

//check to see if an input handler was associated with the socket before we pass to command parsing
    if (HasHandle())
        {
            HandleInput();
            return true;
        }

//No handle was found, pass on to command parsing
    input=PopCommand();
    if (!input.length())
        {
            return true;
        }
    if (!world->DoCommand(mob, input))
        {
            mob->Message(MSG_ERROR, "I did not understand that.");
            return false;
        }

    return true;
}
Beispiel #18
0
HRESULT GameState::Update()
{
	// TODO: Lock to execute OnUpdate() to specific time based update interval?
	HandleInput();
	OnUpdate();
	HRESULT hr = Render();
	return hr;
}
Beispiel #19
0
bool Game::Run()
{
	
	SplashScreen();

	LoadScreen();
	

	Initialize();
	_currentState=_pMenu;
	//_currentState = new Level1(_rWindow,_rSfmlDebugDraw,_pWorld,score);
	
	LoadContent();

	Clock timeElapsed;

	while ( _rWindow.isOpen() )
	{
		
		_rWindow.pollEvent(e);

		if ( e.type == Event::Closed )
		{
			_rWindow.close();
			UnloadContent();
			break;
		}

		if(e.type==Event::KeyPressed)
		{
			if(Keyboard::isKeyPressed(Keyboard::LAlt) && Keyboard::isKeyPressed(Keyboard::F4))
			{
				_rWindow.close();
				UnloadContent();
				break;
			}

			
		}
		
		HandleInput( e );

		//Time lastUpdateCall = timeElapsed.restart();

		if ( timeElapsed.getElapsedTime().asMilliseconds() >= timeStep)
		{
			Update( e, oldEvent, timeElapsed.restart() );
		}
	
		Time lastDrawCall = /*lastUpdateCall +*/ timeElapsed.getElapsedTime(); //.restart();

		Draw( _rWindow, lastDrawCall );

		oldEvent = e;
	}
	
	return true;
}
void LuaInterpreter::Update(const float& anElapsedTime)
{
	myTextPositionIndicatorTimer += anElapsedTime;
	if(myTextPositionIndicatorTimer > 1.f)
	{
		myTextPositionIndicatorTimer = 0.f;
	}
	HandleInput();
}
Beispiel #21
0
bool ColorPicker::OnMouseEvent(const Vec2& mouse_position)
{
	// We can't do changes if the sliders are hidden.
	if(!_visible)
		return false;

	// Check each gradient set. We will not need to check any further if one
	//	is changed as you can only change one at a time.

	if(HandleInput(mouse_position, _ambient_gradient))
		return true;
	if(HandleInput(mouse_position, _specular_gradient))
		return true;
	if(HandleInput(mouse_position, _diffuse_gradient))
		return true;

	return false;
}
bool ApplicationClass::Frame()
{
	bool result;


	// Read the user input.
	result = m_Input->Frame();
	if(!result)
	{
		return false;
	}
	
	// Check if the user pressed escape and wants to exit the application.
	if(m_Input->IsEscapePressed() == true)
	{
		return false;
	}

	// Update the system stats.
	m_Timer->Frame();
	m_Fps->Frame();
	m_Cpu->Frame();

	// Update the FPS value in the text object.
	result = m_Text->SetFps(m_Fps->GetFps(), m_Direct3D->GetDeviceContext());
	if(!result)
	{
		return false;
	}
	
	// Update the CPU usage value in the text object.
	result = m_Text->SetCpu(m_Cpu->GetCpuPercentage(), m_Direct3D->GetDeviceContext());
	if(!result)
	{
		return false;
	}

	// Do the frame input processing.
	result = HandleInput(m_Timer->GetTime());
	if(!result)
	{
		return false;
	}

	// Do the sky plane frame processing.
	m_SkyPlane->Frame();

	// Render the graphics.
	result = RenderGraphics();
	if(!result)
	{
		return false;
	}

	return result;
}
Beispiel #23
0
void ShaderApp::Update(const float dtSeconds)
{	
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen And The Depth Buffer
	
	glLoadIdentity();
	HandleInput(dtSeconds);
	terrain->Render();
	//glutSolidTeapot(2);
	
}
void Level00::VUpdate(double milliseconds)
{
	HandleInput(*mInput);
	mNetworkManager->Update();

	UpdateExplorers(milliseconds);
	UpdateGrid();
	UpdateRobots();

}
Beispiel #25
0
		void Camera3D::Update()
		{
			HandleInput();

			float distance = m_RunSpeed * Core::Window::DeltaTime();
			Vector3 displacement = Forward() * distance;

			Object3D::Move(displacement);

			m_bUpdateViewMatrix = false;
		}
LRESULT PushToTalkController::WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
	case WM_INPUT:
		return HandleInput(wParam, lParam);

	default:
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
	}
}
Beispiel #27
0
void DemoState::AdvanceFrame(float delta_time) {
  HandleInput();
  UpdateIcons(delta_time);
  audio_engine_.AdvanceFrame(delta_time);
  RemoveInvalidSounds();
  SDL_RenderClear(renderer_);
  DrawInstructions();
  DrawIcons();
  SDL_RenderPresent(renderer_);
  SDL_Delay(kDelayMilliseconds);
}
Beispiel #28
0
void GameEngine::GameLoop()
{
    // Set framerate cap
    GLdouble framerate = 999.0;
    GLdouble lastFrameTime = 0, currentFrameTime = 0, fpsLastUpdate = 0;
    gameRunning = true;

    // Main-loop
    while(gameRunning)
    {
        currentFrameTime = glfwGetTime();
        if ((currentFrameTime - lastFrameTime) * 1000.0 < 1000.0 / framerate)
        {
            Sleep(0.0001);
        }
        else
        {
            // Check if a state has been queued
            if (StateManager::GetInstance()->StateHasBeenQueued())
            {
                StateManager *sM = StateManager::GetInstance();
                ResourceManager * rM = ResourceManager::GetInstance();

                // Change state
                rM->UnloadAll();
                sM->ChangeState(sM->GetQueuedState());
                rM->StartLoading();
            }

            // Handle input
            HandleInput();

            // Update
            Update((currentFrameTime - lastFrameTime) * 1000.0);

            // Draw
            Draw();

            // update fps-counter
            GLdouble time = currentFrameTime;
            if (time - fpsLastUpdate >= 1.0)
            {
                GLdouble fps = ((currentFrameTime - lastFrameTime) * 1000.0);
                glfwSetWindowTitle(Context::getWindow(), toString((int)((1000.0 / fps) * 100.0) / 100.0).c_str());
                fpsLastUpdate = time;
            }

            lastFrameTime = currentFrameTime;
        }
    }

    // Cleanup game if loop stops
    Cleanup();
}
Beispiel #29
0
static void EditCampaign(void)
{
	int xc = 0, yc = 0;
	int xcOld, ycOld;
	Mission scrap;
	memset(&scrap, 0, sizeof scrap);

	gCampaign.seed = 0;
	Setup(1);

	SDL_EnableKeyRepeat(0, 0);
	Uint32 ticksNow = SDL_GetTicks();
	sTicksElapsed = 0;
	ticksAutosave = AUTOSAVE_INTERVAL_SECONDS * 1000;
	for (;;)
	{
		Uint32 ticksThen = ticksNow;
		ticksNow = SDL_GetTicks();
		sTicksElapsed += ticksNow - ticksThen;
		if (sTicksElapsed < 1000 / FPS_FRAMELIMIT * 2)
		{
			SDL_Delay(1);
			debug(D_VERBOSE, "Delaying 1 ticksNow %u elapsed %u\n", ticksNow, sTicksElapsed);
			continue;
		}

		debug(D_MAX, "Polling for input\n");
		EventPoll(&gEventHandlers, SDL_GetTicks());
		int c = KeyGetPressed(&gEventHandlers.keyboard);
		int m = MouseGetPressed(&gEventHandlers.mouse);

		debug(D_MAX, "Handling input\n");
		HandleInputResult result = HandleInput(
			c, m, &xc, &yc, &xcOld, &ycOld, &scrap);
		if (result.Done)
		{
			break;
		}
		if (result.Redraw || result.RemakeBg || sJustLoaded)
		{
			sJustLoaded = false;
			debug(D_MAX, "Drawing UI\n");
			Display(&gGraphicsDevice, yc, result);
			if (result.WillDisplayAutomap)
			{
				GetKey(&gEventHandlers);
			}
		}
		debug(D_MAX, "End loop\n");
		SDL_Delay(10);
	}
}
Beispiel #30
0
void Update()
{
	HandleInput();

	deltaLastMove += deltaTime;

	if (deltaLastMove > cooldown)
	{
		MoveSnake(dx, dy);

		deltaLastMove =	deltaLastMove - cooldown;
	}
}