Example #1
0
int gui_confirm_box(char *msg)
{
	int done = 0;

	gui_draw();
	apply_surface_center(400, 240, confirm_box, myscreen);
	message = TTF_RenderUTF8_Blended( font, msg, WHITE );
	apply_surface_center(400, 240, message, myscreen);
	SDL_FreeSurface( message );
	SDL_Flip(myscreen);

	while(!done)
	{
		get_mouse_loc();

		if(get_mouse_click(MOUSE_LEFT))
		{
			if(reset_ts_pos) { mouse_hold_x = MOUSE_X; mouse_hold_y = MOUSE_Y; reset_ts_pos = 0; }

			if(mouse_is_over(300, 378, 285, 322)) // OK
			{
				return 1;
			}
			else if(mouse_is_over(428, 508, 285, 322)) // Cancel
			{
				return 0;
			}
		}
		else reset_ts_pos = 1;

		SDL_framerateDelay( &sixteen );
	}
	return 0;
}
Example #2
0
File: main.c Project: pikhq/cmako
static void render_screen()
{
	static int screen_inited;

	static SDL_Surface *real_screen;
	static SDL_Surface *mako_screen;

	if(!inited_sdl)
		init_sdl();

	if(!screen_inited) {
		const SDL_VideoInfo *info = SDL_GetVideoInfo();

		if(info->wm_available) {
			if(!SDL_SetVideoMode(320, 240, 0,
						SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF | SDL_RESIZABLE)) {
				fprintf(stderr, "%s.\n", SDL_GetError());
				exit(1);
			}
		} else {
			if(!SDL_SetVideoMode(info->current_w, info->current_h, 0,
						SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF | SDL_RESIZABLE)) {
				fprintf(stderr, "%s.\n", SDL_GetError());
				exit(1);
			}
			SDL_ShowCursor(SDL_DISABLE);
		}

		real_screen = SDL_GetVideoSurface();
		mako_screen = SDL_CreateRGBSurfaceFrom(framebuf, 320, 240, 32,
				320*sizeof(uint32_t), 0xFF0000, 0xFF00, 0xFF, 0);

		screen_inited = 1;
	}

	if(real_screen->h == 240 && real_screen->w == 320)
		SDL_BlitSurface(mako_screen, NULL, real_screen, NULL);
	else {
		int desired_h = real_screen->w * 3 / 4;
		if(desired_h > real_screen->h)
			desired_h = real_screen->h;
		int desired_w = desired_h * 4 / 3;

		SDL_Rect rect = {
			.x = (real_screen->w - desired_w)/2,
			.y = (real_screen->h - desired_h)/2,
			.w = desired_w,
			.h = desired_h
		};

		SDL_SoftStretch(mako_screen, NULL, real_screen, &rect);
	}

	SDL_Flip(real_screen);
}

static void delay()
{
	SDL_framerateDelay(&fps);
}
Example #3
0
int processSdlEvents(void) {
    SDL_Event event;

    resetEvents();
    while (SDL_PollEvent(&event)) {
        switch(event.type) {
        case SDL_KEYDOWN:
            switch(event.key.keysym.sym) {
            case SDLK_ESCAPE:
                return 1;
                break;
            default:
                keyboardEvent(&event.key,1);
                break;
            }
            break;
        case SDL_KEYUP:
            keyboardEvent(&event.key,0);
            break;
        case SDL_MOUSEMOTION:
            mouseMovedEvent(event.motion.x,event.motion.y,
                       event.motion.xrel,event.motion.yrel);
            break;
        case SDL_MOUSEBUTTONDOWN:
            mouseButtonEvent(event.button.button,1);
            break;
        case SDL_MOUSEBUTTONUP:
            mouseButtonEvent(event.button.button,0);
            break;
        case SDL_QUIT:
            exit(0);
            break;
        }
        /* If the next event to process is of type KEYUP or
         * MOUSEBUTTONUP we want to stop processing here, so that
         * a fast up/down event be noticed by Lua. */
        if (SDL_PeepEvents(&event,1,SDL_PEEKEVENT,SDL_ALLEVENTS)) {
            if (event.type == SDL_KEYUP ||
                event.type == SDL_MOUSEBUTTONUP)
                break; /* Go to lua before processing more. */
        }
    }

    /* Call the setup function, only the first time. */
    if (l81.epoch == 0) {
        setup();
        if (l81.luaerr) return l81.luaerr;
    }
    /* Call the draw function at every iteration.  */
    draw();
    l81.epoch++;
    /* Refresh the screen */
    if (l81.opt_show_fps) showFPS();
    SDL_Flip(l81.fb->screen);
    /* Wait some time if the frame was produced in less than 1/FPS seconds. */
    SDL_framerateDelay(&l81.fb->fps_mgr);
    /* Stop execution on error */
    return l81.luaerr;
}
Example #4
0
void Draw(SDL_Surface *screen)
{
 int i,rate,x,y,dx,dy,r,g,b;
 FPSmanager fpsm;
 
 /* Initialize variables */
 srand(time(NULL));
 i=0;
 x=screen->w/2;
 y=screen->h/2;
 dx=7;
 dy=5;
 r=g=b=255;
  
 SDL_initFramerate(&fpsm);

 while (1) {
  
  /* Set/switch framerate */
  i -= 1;
  if (i<0) {
   /* Set new rate */
   rate=5+5*(rand() % 10);
   SDL_setFramerate(&fpsm,rate);
   printf ("\nFramerate set to %i Hz ...\n\n",rate);
   /* New timeout */
   i=2*rate;
   /* New Color */
   r=rand() & 255;
   g=rand() & 255;
   b=rand() & 255;
  }

  HandleEvent();
  
  /* Black screen */
  ClearScreen(screen);

  /* Move */
  x += dx;
  y += dy;
  
  /* Reflect */
  if ((x<0) || (x>screen->w)) { dx=-dx; }
  if ((y<0) || (y>screen->h)) { dy=-dy; }

  /* Draw */
  filledCircleRGBA (screen,x,y,30,r,g,b,255);
  circleRGBA(screen,x,y,30,255,255,255,255);
    
  /* Display by flipping screens */
  SDL_UpdateRect(screen,0,0,0,0);

  /* Delay to fix rate */                   
  SDL_framerateDelay(&fpsm);  
 }
}
Example #5
0
int main(int argc, char *argv[])
{

	int gui_done = 0;
	scroll_count = 800;
	selected_menu = ROMS;
	alpha_up = 1;
	alpha = 0;
	mouse_y_pos = 120;
	selected_option_item = 0;

	if(!cfg_read("config.txt"))
	{
		printf("Fail => cfg_read()\n");
		exit(0);
	}

	if(!gui_init_sdl())
	{
		printf("Fail => gui_init_sdl()\n");
		exit(0);
	}

	emu_config_init();
	
	gui_load();

	strncpy(now_path, config->roms_path, MAXPATH);
	filer_read_dir(now_path);

	SDL_initFramerate( &sixteen );
	SDL_setFramerate( &sixteen, 65 );

	while(!gui_done)
	{
		handle_mouse();

		while( SDL_PollEvent( &event ) )
		{	
			switch(event.type)
			{
				case SDL_QUIT:
				{
					gui_clean();
					free(emu);
					exit(0);
				}
				break;
			}
		}
		gui_draw();
		SDL_Flip(myscreen);
		SDL_framerateDelay( &sixteen );
	}
	return 0;
}
Example #6
0
void Draw(SDL_Renderer *renderer, FPSmanager *fpsm)
{
	int newRate;
	int currentRate;

		/* FPSmanager: get current rate */
		currentRate = SDL_getFramerate(fpsm);

		/* Set/switch framerate */
		timeout--;
		if (timeout < 0) {
			/* New rate */
			newRate = 5 + 5 * (rand() % 10);

			/* Update timeout */
			timeout = 2 * newRate;

			/* New Color */
			r = rand() & 255;
			g = rand() & 255;
			b = rand() & 255;

			/* FPSmanager: set new rate */
			SDL_setFramerate(fpsm, newRate);
		}

		/* Black screen */
		ClearScreen(renderer);

		/* Move */
		x += dx;
		y += dy;

		/* Reflect */
		if ((x<0) || (x>WIDTH)) { dx=-dx; }
		if ((y<0) || (y>HEIGHT)) { dy=-dy; }

		/* Draw */
		filledCircleRGBA (renderer,x,y,30,r,g,b,255);
		circleRGBA(renderer,x,y,30,255,255,255,255);

		/* Report set rate and current delay (from last iteration) */
		if (time_passed > 0) {
			SDL_snprintf(messageText, 1024, "Set rate: %4iHz   Last delay=%4ims / Calc.Rate=%4iHz", currentRate, time_passed, 1000 / time_passed); 
			stringRGBA (renderer, WIDTH/2 - 4*strlen(messageText),HEIGHT-24,messageText,255,255,255,255);
		}

		/* Simulate some random delay from drawing, business logic, network interaction, etc. */
		SDL_Delay(1 + rand() % 10);

		/* Display */
		SDL_RenderPresent(renderer);

		/* FPSmanager: Delay to a fixed rate */                   
		time_passed = SDL_framerateDelay(fpsm);  
}
int video_copy_screen(s_screen* src)
{
	// do any needed scaling and color conversion
	s_videosurface *surface = getVideoSurface(src);

	if(opengl) return video_gl_copy_screen(surface);

	SDL_UpdateTexture(texture, NULL, surface->data, surface->pitch);
	blit();

#if WIN || LINUX
	SDL_framerateDelay(&framerate_manager);
#endif

	return 1;
}
Example #8
0
int main(int argc, char* argv[])
{
    FPSmanager framerate_manager;

    (void)argc;
    (void)argv;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) return 1;

    SDL_initFramerate(&framerate_manager);
    SDL_setFramerate(&framerate_manager, 60);
    SDL_framerateDelay(&framerate_manager);

    SDL_Quit();
    return 0;
}
static int waitForAnotherSpace() {

    SDL_Event event;

    while(1) {
        SDL_framerateDelay(&fpsm);

        while(SDL_PollEvent(&event)) {
            if(event.type == SDL_KEYDOWN) {
                if(event.key.keysym.sym == SDLK_SPACE)
                    return 0;
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    return 1;
            }
        }
    }

}
Example #10
0
/*!
 * \fn int main (int argc, char **argv)
 * \param argc Number of arguments.
 * \param argv Arguments.
 * \return Return the program state at exit: 0 if everything is fine, 1 if an error occur.
 *
 * Main function of MapMe.
 * Start the programme, initialize libraries, then start game pipe, wich contain menu and game.
 */
int main(int argc, char **argv)
#endif
{
    /*    States initialization        */
    StateManager &StateManager= StateManager::getInstance();
    StateManager.setSoftwareState(1);

    /*    Loading configuration        */
    ConfigManager &ConfigManager= ConfigManager::getInstance();
    if (ConfigManager.LoadConfig() == false)
    {
        std::cerr << "[X] Loading configuration : CRITICAL ERROR." << std::endl;// debug
        std::cerr << "[X] Attempt to shutdone." << std::endl;                   // debug

        return EXIT_FAILURE;
    }


    /*    Graphics initialization        */
    GfxManager &GfxManager= GfxManager::getInstance();
    if (GfxManager.createScreen() == false)
    {
        std::cerr << "[X] Screen initialization : CRITICAL ERROR." << std::endl;// debug
        std::cerr << "[X] Attempt to shutdone." << std::endl;                   // debug

        return EXIT_FAILURE;
    }

    // Temporary loading screen
    GfxManager.loadingScreen();

    // Load all gfx ressources
    GfxManager.loadRessources(0);


    /*    Events initialization        */
    EventManager &EventManager= EventManager::getInstance();


    /*    Audio initialization        */
    SoundManager &SoundManager= SoundManager::getInstance();
    if (SoundManager.initAudio() == false)
    {
        std::cerr << "[X] Audio initialization : CRITICAL ERROR." << std::endl; // debug
        std::cerr << "[X] Attempt to shutdone." << std::endl;                   // debug

        return EXIT_FAILURE;
    }
    SoundManager.loadRessources();

    /*    Menu and Game initialization    */
    GameWorld *pGAME= NULL;
    Menu *pMENU= NULL;


    /*    FPS manager initialization    */
    FPSmanager FramesManager;
    SDL_initFramerate(&FramesManager);
    SDL_setFramerate(&FramesManager, 30);


    // Main loop start
    /////////////////////
    std::cout << "[Y] Program started successfully !" << std::endl;
    while(StateManager.isExitCode() == false)
    {
        // Menu
        if ((StateManager.getSoftwareState() == 1) && (pMENU != NULL))
        {
            pMENU->MenuPipe();
        }
        else if ((StateManager.getSoftwareState() == 1) && (pMENU == NULL))
        {
            pMENU= new Menu();
            //GfxManager.loadRessources(1);
            if (pGAME != NULL)
            {
                delete pGAME;
                //GfxManager.unloadRessources(2);
                pGAME= NULL;
            }
        }

        // Game
        if ((StateManager.getSoftwareState() == 2) && (pGAME != NULL))
        {
            pGAME->GamePipe();
        }
        else if ((StateManager.getSoftwareState() == 2) && (pGAME == NULL))
        {
            pGAME= new GameWorld();
            //GfxManager.loadRessources(2);
            if (pMENU != NULL)
            {
                delete pMENU;
                //GfxManager.unloadRessources(1);
                pMENU= NULL;
            }
        }

        GfxManager.flipVideoBuffers();

        /* fps */
        SDL_framerateDelay(&FramesManager);
        //std::cout << "FPS : " << SDL_getFramerate(&FramesManager) << std::endl;
    }

    if (pMENU != NULL)
        delete pMENU;
    if (pGAME != NULL)
        delete pGAME;
    /////////////////////
    // Main loop end


    // Exit sequence
    std::cout << "[Y] Program shutting-done." << std::endl;                     // debug
    ConfigManager.destroyInstance();
    SoundManager.destroyInstance();
    GfxManager.destroyInstance();
    EventManager.destroyInstance();
    StateManager.destroyInstance();

return EXIT_SUCCESS;
}
Example #11
0
/// \brief Main program function
///
/// This function does very little on its own. It manages some output to
/// player's console, directs subsystems to initialize themselves and makes
/// choice of rendering engine. Then it runs the main game loop, processing
/// events and sending them further into the game.
int main(int argc, char *argv[])
{

    #if !defined(WIN32) && !defined(__APPLE__)
    #ifdef _GLIBCXX_DEBUG
	/*#if __WORDSIZE != 64*/

    /* Install our signal handler */
    struct sigaction sa;

    sa.sa_sigaction = /*(void *)*/crashhndl;
    sigemptyset (&sa.sa_mask);
    sa.sa_flags = SA_RESTART | SA_SIGINFO;

    sigaction(SIGSEGV, &sa, NULL);
    sigaction(SIGFPE, &sa, NULL);
    /*#endif*/
	#endif
    #endif



#ifdef WIN32
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD( 2, 2 );

	if(WSAStartup(wVersionRequested, &wsaData) != 0){
		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Winsock startup failed!!");
		return -1;
	}

	if((LOBYTE(wsaData.wVersion) != 2) || (HIBYTE(wsaData.wVersion) != 2)){
		WSACleanup( );
		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "No Winsock 2.2 found!");
		return -1;
	}

#endif

	//setenv("SDL_VIDEODRIVER", "aalib", 0);
	//setenv("AAOPTS","-width 200 -height 70 -dim -reverse -bold -normal -boldfont  -eight -extended ",0);
	//setenv("AAFont","-*-fixed-bold-*-*-*-*-55-*-*-*-*-*-*",0);
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, PRODUCTLONG "\n");
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "================================\n");
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "version " PRODUCTVERSION "\n");
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "compiled on " __DATE__ " " __TIME__ "\n");
#ifdef BUILDVERSION
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "build %s\n", BUILDVERSION);
#endif
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, " This is free software: you are free to change and redistribute it.\n"
		" There is NO WARRANTY, to the extent permitted by law. \n"
		" Review LICENSE in " PRODUCTSHORT " distribution for details.\n");


    yatc_fopen_init(argv[0]);



	options.Load();
	MAXFPS = options.maxfps;



#if HAVE_LIBINTL_H
    // set up i18n stuff
    if(options.lang.size())
    {
        std::string l("LANG=");
        l+=options.lang;
        putenv((char*)l.c_str());
    }
    setlocale( LC_ALL, "");//options.lang.c_str() );
    setlocale( LC_NUMERIC, "C");
    #if !BAZEL_BUILD
    bindtextdomain( "yatc", "./translations" );
    #else
    bindtextdomain( "yatc", (yatc_path_to_binary() + "yatc.runfiles/yatc/translations").c_str());
    #endif
    textdomain( "yatc" );
    bind_textdomain_codeset("yatc","windows-1252");
#endif

	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Checking graphics files existence...\n");
	checkFiles();
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "All graphics files were found.\n");


	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Initializing windowing...\n");

	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0){
		std::stringstream out;
		out << "Couldn't initialize SDL: " << SDL_GetError() << std::endl;
		DEBUGPRINT(DEBUGPRINT_ERROR, DEBUGPRINT_LEVEL_OBLIGATORY, out.str().c_str());

		NativeGUIError(out.str().c_str(), PRODUCTSHORT " Fatal Error");
		exit(1);
	}

    // We are no longer dependant on .dat for this!
    // ivucica asks: nate, not dependant for what? why is this removed?
    // because of .ico? disagree.
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Loading data...\n");
	if(!Objects::getInstance()->loadDat("Tibia.dat")){
		DEBUGPRINT(DEBUGPRINT_ERROR, DEBUGPRINT_LEVEL_OBLIGATORY, gettext("Loading data file failed!"));
		std::string forreplace = gettext("Loading the data file '$$FILENAME$$' has failed.\nPlease place '$$FILENAME$$' in the same folder as $$PRODUCTSHORT$$.\n");
		forreplace = str_replace("$$FILENAME$$", "Tibia.dat", forreplace);
		forreplace = str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, forreplace);
		NativeGUIError(forreplace.c_str(), str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, gettext("$$PRODUCTSHORT$$ Fatal Error")).c_str());
		exit(1);
	}


	setIcon(); // must be called prior to first call to SDL_SetVideoMode() (currently done in engine)

	SDL_EnableKeyRepeat(200, 50);
	SDL_EnableUNICODE(1);

	try{
	    g_engine = NULL; // set to null, in case anything that happens inside engine constructor wants to know we're just constructing
		switch(options.engine){
			#ifdef USE_OPENGL
			case ENGINE_OPENGL:
				g_engine = new EngineGL;
				break;
			#endif

			default:
				DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_WARNING, "Unknown engine was selected. Falling back to SDL.");
				options.engine = ENGINE_SDL;
			case ENGINE_SDL:
				g_engine = new EngineSDL;
				break;
		}

		if(!g_engine->isSupported()){
			DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_WARNING, "The selected graphics engine is not supported. Falling back to SDL.");
			delete g_engine;
			g_engine = NULL; // set to null, in case anything that happens inside engine constructor wants to know we're just constructing
			options.engine = ENGINE_SDL;
			g_engine = new EngineSDL;
		}

		// NOTE (nfries88): Make sure the window is sized as per the options
		int w = MAX(options.w, 656);
		int h = MAX(options.h, 352+options.consoleh);
		g_engine->doResize(w, h);


		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Loading skin...\n");
		g_skin.loadSkin();
		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Skin has been loaded\n");


		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Constructing gamemode...\n");
		resetDefaultCursor();
		if (argc == 1)
		{
		    g_game = new GM_MainMenu();
            //g_game = new GM_Debug(); // ivucica: this is for testing -- choice should be a cmd line option
		} else
		{
		    g_game = new GM_MainMenu();
            ProtocolGame* protocol = ProtocolConfig::createGameProtocol(854,"","","",false);
            g_connection = new ConnectionReplay(argv[1], protocol);
            if (argc==3)
            {
                sscanf(argv[2], "%f", &g_replayspeed);
            }

		}


        DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Initializing framerate manager...\n");
        SDL_initFramerate(&g_fpsmgr);
        SDL_setFramerate(&g_fpsmgr,MAXFPS);


		DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Running\n");
        g_running = true;

        #ifdef WIN32
        SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
        #endif

		SDL_Event event;
		while(g_running){

            //g_engine->fpsMutexLock();

            //int beginticks = SDL_GetTicks();
            g_engine->performFpsCalc();

			//first process sdl events
			while(SDL_PollEvent(&event)){
				switch (event.type){
					case SDL_VIDEORESIZE:
						g_engine->doResize(event.resize.w, event.resize.h);
						g_game->doResize(event.resize.w, event.resize.h);
						break;

					case SDL_QUIT:
						g_game->onExitAttempt();
						break;

					case SDL_KEYDOWN:
						onKeyDown(event);
						break;
                    case SDL_KEYUP:
                        if((event.key.keysym.sym == SDLK_LSUPER)
                          || (event.key.keysym.sym == SDLK_RSUPER))
                            superkey_state = false;
                        break;

					case SDL_MOUSEBUTTONUP:
					case SDL_MOUSEBUTTONDOWN:
						#ifdef WINCE
						if (ptrx < 5 && ptry < 5)
							SDL_WM_IconifyWindow(); // appears to crash the application?! ah nevermind
						#endif
						g_game->mouseEvent(event);
						break;

					case SDL_MOUSEMOTION:
						ptrx = event.motion.x;
						ptry = event.motion.y;
						g_game->mouseEvent(event);
						break;
					default:
						break;
				}
			}
			//update current frame time
			g_frameDiff = SDL_GetTicks() - g_frameTime;
			g_frameTime = SDL_GetTicks();


            if (MAXFPS) {
                SDL_framerateDelay(&g_fpsmgr);

            }

			//check connection
			if(g_connection){
				g_connection->executeNetwork();
			}

            if (!(SDL_GetAppState() & SDL_APPACTIVE)) {// if the application is minimized
                #ifdef WIN32
                Sleep(100); // sleep a while, and don't paint
                #else
                usleep(100 * 1000);
                #endif
            } else { //otherwise update scene
                g_game->updateScene();
                g_engine->Flip();
            }
			g_frames ++;


			//g_engine->fpsMutexUnlock();

		}
	}
	catch(std::string errtext){
		DEBUGPRINT(DEBUGPRINT_ERROR, DEBUGPRINT_LEVEL_OBLIGATORY, "%s", errtext.c_str());
	}

	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Game over\n");

	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Terminating protocol connection from main...\n");
	delete g_connection;
	g_connection = NULL;
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Destroying map...\n");
	Map::getInstance().clear();
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Destroying creature cache...\n");
	Creatures::getInstance().clear();
	Creatures::destroyInstance();
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Destroying inventory...\n");
	Inventory::getInstance().clear();

	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Unloading data...\n");
	Objects::getInstance()->unloadDat();
    Objects::destroyInstance();

    DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Unloading skin...\n");
	g_skin.unloadSkin();


	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Saving options...\n");
	options.Save();
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Finishing engine...\n");
	delete g_engine;
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Ending game...\n");
	delete g_game;
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Shutting down SDL...\n");
	SDL_Quit();

#ifdef WIN32
	WSACleanup();
#endif

	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Thanks for playing!\n");

	return 0;
}
Example #12
0
	void MainLoop(){
		while(Going){
    		SDL_Event event;
			System::Input::Update();
    		while ( SDL_PollEvent(&event) ){
				switch(event.type){
		        case SDL_QUIT:
					return; // Break from main loop
					break;
		        case SDL_KEYDOWN:
					if(CurrentGameState)
						CurrentGameState->KeyDown(event.key.keysym.sym);
					else
						if(event.key.keysym.sym == SDLK_ESCAPE)
							return;
					if(event.key.keysym.sym == SDLK_F12)
						TakeScreenshot();
					break;
		        case SDL_KEYUP:
					if(CurrentGameState)
						CurrentGameState->KeyUp(event.key.keysym.sym);
					break;
				case SDL_MOUSEMOTION:
					if(CurrentGameState)
						CurrentGameState->MouseMotion();
					break;
				case SDL_MOUSEBUTTONDOWN:
					if(CurrentGameState)
						CurrentGameState->MouseButtonDown(event.button.button);
					break;
				case SDL_MOUSEBUTTONUP:
					if(CurrentGameState)
						CurrentGameState->MouseButtonUp(event.button.button);
					break;
		        default:
					break;
		    	}
				if(CurrentGameState)
					CurrentGameState->CheckGUIObjectsEvent(&event);
			}

			if(CurrentGameState){
				CurrentGameState->Update(); // Game Logic
				CurrentGameState->UpdateGUIObjects();
			}
			// Paint screen
			SDL_Flip(Screen);
	  		SDL_FillRect(Screen, NULL, 0); // Clear the buffer black
			
			if(CurrentGameState){
				CurrentGameState->Draw(); // Draw
				CurrentGameState->DrawGUIObjects();
			}else
				System::Graphics::DrawFilledTriangle(System::Width/2, 1, System::Width - 1, System::Height - 1, 1, System::Height - 1, 0, 0, 255, 255);

			// Provide time delay
			SDL_framerateDelay(&fpsm);

			// Calculate FPS
			timeNow = SDL_GetTicks();
			if(timeNow - timeLast > 1000){
				m_FPS = numFrames;
				timeLast = timeNow;
				numFrames = 0;
			} else {
				numFrames++;
			}
		}

		// Close data
		System::Graphics::Image::Close();
		System::Text::Close();
		SDL_Quit();
	}
Example #13
0
void
Display::Delay(){
	SDL_framerateDelay(&manager);
}
Example #14
0
void sdl_frame_delay( void ) {
	if( frame_rate ) {
		SDL_framerateDelay( &manager );
	}
}
Example #15
0
void Draw(SDL_Surface *screen)
{
	int i,rate,x,y,dx,dy;
	int psize = NUM_POINTS; 
	double sin_start = 0;
	double sin_amp = 100;
	Sint16 polygon_x[NUM_POINTS], polygon_y[NUM_POINTS];
	Sint16 polygon_alpha_x[4], polygon_alpha_y[4];
	SDL_Surface *texture;
	SDL_Surface *texture_alpha;
	FPSmanager fpsm;
	int width_half = screen->w/2;
	int height_half = screen->h/2;

	/* Load texture surfaces */
	texture = SDL_LoadBMP("texture.bmp");
	texture_alpha = SDL_LoadBMP("texture_alpha.bmp");
	SDL_SetAlpha(texture_alpha, SDL_SRCALPHA, 128);

	/* Initialize variables */
	srand((int)time(NULL));
	i=0;
	x=width_half;
	y=height_half;
	dx=7;
	dy=5;

	/* Initialize Framerate manager */  
	SDL_initFramerate(&fpsm);

	/* Polygon for blended texture */
	polygon_alpha_x[0]= 0;
	polygon_alpha_y[0]= 0;
	polygon_alpha_x[1]= width_half;
	polygon_alpha_y[1]= 0;
	polygon_alpha_x[2]= screen->w*2 / 3;
	polygon_alpha_y[2]= screen->h;
	polygon_alpha_x[3]= 0;
	polygon_alpha_y[3]= screen->h;

	/* Set/switch framerate */
	rate=25;
	SDL_setFramerate(&fpsm,rate);

	/* Drawing loop */
	while (1) {

		/* Generate wave polygon */
		sin_start++;
		polygon_x[0]= 0;
		polygon_y[0]= screen->h;
		polygon_x[1]= 0;
		polygon_y[1]= height_half;    
		for (i=2; i < psize -2 ; i++){
			polygon_x[i]= (screen->w  * (i-2)) / (psize -5) ;
			polygon_y[i]= (Sint16)(sin(sin_start/100) * 200) + height_half - (Sint16)(sin((i + sin_start) / 20) * sin_amp);
		}

		polygon_x[psize-2]= screen->w;
		polygon_y[psize-2]= height_half;
		polygon_x[psize-1]= screen->w;
		polygon_y[psize-1]= screen->h;

		/* Event handler */
		HandleEvent();

		/* Black screen */
		ClearScreen(screen);

		/* Move */
		x += dx;
		y += dy;

		/* Reflect */
		if ((x<0) || (x>screen->w)) { dx=-dx; }
		if ((y<0) || (y>screen->h)) { dy=-dy; }

		/* Draw */
		texturedPolygon(screen,polygon_x,polygon_y,psize,texture, -(screen->w  * (Sint16)(sin_start-2)) / (psize - 5), -(Sint16)(sin(sin_start/100) * 200));
		texturedPolygon(screen,polygon_alpha_x,polygon_alpha_y,4,texture_alpha,(Sint16)sin_start,-(Sint16)sin_start);

		/* Display by flipping screens */
		SDL_Flip(screen);

		/* Delay to fix rate */                   
		SDL_framerateDelay(&fpsm);  
	}
}
Example #16
0
/*----------------------------------------------------------------------------
 * Call at the end of each iteration.
 *----------------------------------------------------------------------------*/
void
media_sync(void)
{
    SDL_framerateDelay(&media.fpsmanager);
    SDL_Flip(media.canvas);
}
Example #17
0
int main ( int argc, char** argv )
{
	std::cout << "Starting\n";
    initalize();

    //TODO add resource load error handling
    add_surface("spaceb", load_surface("gray_space.png",1)   );
    add_surface("spacem", load_surface("gray_space.png",1)   );
    add_surface("spacef", load_surface("gray_space.png",1)   );

    for(int i=-2; i < 20+2; i++)
        meta::objects.push_back(new psrect_static(200*i, 200, 200, 200));
//meta::objects.push_back(new psrect_static(320, 20, 320, 20));

//meta::objects.push_back(new psrect_static(0, -400,1, 1000));
//meta::objects.push_back(new psrect_static(1000, -400, 1, 1000));

    meta::objects.push_back(new rocket(2000,-100, 50,70));

    //load_map("test.json");

    float32 timeStep = 1.0f / 30.0f;
    int32 velocityIterations = 6;
    int32 positionIterations = 2;

    FPSmanager manager;
    SDL_initFramerate(&manager);
    SDL_setFramerate(&manager, 30);

    // program main loop
    bool done = false;
    while (!done)
    {
        SDL_framerateDelay(&manager);

        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
                // exit if ESCAPE is pressed
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    done = true;
                break;


            } // end switch
        } // end of message processing

        // DRAWING STARTS HERE
        // clear screen
        //SDL_FillRect(meta::screen, 0, SDL_MapRGB(meta::screen->format, 0, 0, 0 ));
        SDL_FillRect(meta::screen, 0, SDL_MapRGB(meta::screen->format, meta::background_red , meta::background_green, meta::background_blue ));

        draw_background();

        // Instruct the world to perform a single step of simulation.
        // It is generally best to keep the time step and iterations fixed.
        meta::world.Step(timeStep, velocityIterations, positionIterations);

        update_objects();
        meta::world.DrawDebugData();

        // DRAWING ENDS HERE

        // finally, update the screen :)
        SDL_Flip(meta::screen);
    } // end main loop

    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
Example #18
0
void fps_sleep(void)
{
	numTicks++;
	SDL_framerateDelay(&fpsManager);
}
void Draw(SDL_Surface *screen)
{
	int rate,x,y,s;
	SDL_Rect dest,clip;
	SDL_Surface *texture_image;
	SDL_Surface *texture_target1;
	SDL_Surface *texture_target2;
	FPSmanager fpsm;
	Uint32 rmask, gmask, bmask, amask;
	int width_half = screen->w/2;
	int height_half = screen->h/2;
	Uint32 text_color = 0xffffffff;

	/* Define masks for 32bit surface */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	rmask = 0xff000000;
	gmask = 0x00ff0000;
	bmask = 0x0000ff00;
	amask = 0x000000ff;
#else 
	rmask = 0x000000ff;
	gmask = 0x0000ff00;
	bmask = 0x00ff0000;
	amask = 0xff000000;                               
#endif

	/* Create semi-transparent textured surface */
	s=64;
	texture_image = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, s, s, 32, rmask, gmask, bmask, amask));
	/* Add some color */
	boxRGBA(texture_image, 0,  0, s/2, s/2, 255, 0, 0, 255); 
	boxRGBA(texture_image, s/2, 0, s, s/2, 0, 255, 0, 255); 
	boxRGBA(texture_image, 0, s/2, s/2, s, 0, 0, 255, 255); 
	boxRGBA(texture_image, s/2, s/2, s, s, 255, 255, 255, 255);  
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_image, 96);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_image, SDL_SRCALPHA, 255);

	/* Create an all transparent surface */
	texture_target1 = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, 256, 256, 32, rmask, gmask, bmask, amask));
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_target1, 64);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_target1, SDL_SRCALPHA, 255);

	/* Create an all transparent surface (2) */
	texture_target2 = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, 256, 256, 32, rmask, gmask, bmask, amask));
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_target2, 64);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_target2, SDL_SRCALPHA, 255);

	/* Define clipping region for left box */
	clip.x = width_half-256-10 ;
	clip.y = height_half-256/2 ;
	clip.w = 256;
	clip.h = 256;

	/* Initialize Framerate manager */  
	SDL_initFramerate(&fpsm);

	/* Set/switch framerate */
	rate=5;
	SDL_setFramerate(&fpsm,rate);

	/* --- Drawing loop */
	while (1) {

		/* Event handler */
		HandleEvent();

		/* Black screen */
		ClearScreen(screen);

		/* Random position of new texture */
		x=(rand() % (256+2*s))-s;
		y=(rand() % (256+2*s))-s;

		/* Same for comparison texture */
		dest.x = x;
		dest.y = y;
		dest.w = texture_image->w;
		dest.h = texture_image->h;
		SDL_BlitSurface(texture_image, NULL, texture_target1, &dest);

		/* Blit image into the target using custom Blit function. */
		dest.x = x;
		dest.y = y;
		dest.w = texture_image->w;
		dest.h = texture_image->h;
		SDL_gfxBlitRGBA(texture_image, NULL, texture_target2, &dest);

		/* Draw comparison target on screen (left) */
		dest.x = width_half-256-10;
		dest.y = height_half-256/2;
		dest.w = 256;
		dest.h = 256;
		SDL_BlitSurface(texture_target1, NULL, screen, &dest);

		/* Draw combiner target on screen (right) */
		dest.x = width_half+10;
		dest.y = height_half-256/2;
		dest.w = 256;
		dest.h = 256;
		SDL_BlitSurface(texture_target2, NULL, screen, &dest);

		/* Draw some frames with titles */
		rectangleColor(screen, width_half-256-10-1, height_half-256/2-1, width_half-256-10-1+257, height_half-256/2-1+257,  text_color);
		rectangleColor(screen, width_half+10-1, height_half-256/2-1, width_half+10-1+257, height_half-256/2-1+257, text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-36, "     SDL Standard Blitter     ", text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-24, "Image    --sdlBlit-->  Target1", text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-12, "Target1  --sdlBlit-->  Screen", text_color);
		stringColor(screen, width_half+10-1, height_half-256/2-1-36, " SDL_gfx Compositing Blitter", text_color);  
		stringColor(screen, width_half+10-1, height_half-256/2-1-24, "Image    --gfxBlit-->  Target2", text_color);  
		stringColor(screen, width_half+10-1, height_half-256/2-1-12, "Target2  --sdlBlit-->  Screen", text_color);  

		stringColor(screen, width_half-256-10-1, height_half-256/2-1-60, "gfxBlitRGBA Demo: Target1/2 A=64 (25%), Image A=96 (37%)", text_color);  

		/* Display by flipping screens */
		SDL_Flip(screen);

		/* Delay to fix rate */                   
		SDL_framerateDelay(&fpsm);  
	}
}
Example #20
0
int main(){
    //config_manager config("data/settings.sqlite");
	//config.set_setting_int("int", "Settings",100);
    //cout << config.get_setting_int("int", "Settings") << "\n";

    new message_log(MESSAGE_EVENT,"WWSiGE Loading");

    game_engine * engine=new game_engine();

    if (! engine->load(640,480,0))
    {
        new message_log(MESSAGE_FATAL_ERROR,"WWSiGE Failed To Load Necessary Resources, Quitting ...");
        return 100;
    }

    new message_log(MESSAGE_EVENT,"WWSiGE Started");

    FPSmanager manager;
    SDL_initFramerate(&manager);
    SDL_setFramerate(&manager, 30);

    uint32_t last_tick=0;
    char counter=0;
    float fps=0;
    float fps_average=0;
    bool run=1;

    while (run)
    {
        last_tick=SDL_GetTicks();
        run=engine->update();
        SDL_framerateDelay(&manager);
        fps=SDL_GetTicks()-last_tick;
        fps/=1000;
        fps=1/fps;
        fps_average=(fps_average+fps)/2;

        counter++;

        if (counter > 59)
        {
            counter=0;
			new message_log("FPS" ,"%f (%f)", fps_average, fps);
        }

        controller * fps_text = engine->get_object("fps-text");
        if (fps_text==NULL)
        {
            fps_text=new text(engine,"fps-text",625,0,"jura_medium-12","",BLIT_ABSOLUTE);
            engine->add_object(fps_text);
            int value=0xFF;
            engine->get_object("fps-text")->set("font_green",value);
        }

        string text=convert_int_string(fps_average);
        fps_text->set("text",text);

    }

    new message_log(MESSAGE_EVENT,"WWSiGE Closed");

    return 0;
}
unsigned int viewer(state* s, action* a, double reward, void* instance) {

    char str[255];
    double ratioPixels = ((screenWidth / 2.0) - 20) / (2.0 * parameters[1]);
    int done = 0;
    SDL_Event event;

    SDL_FillRect(screen, NULL, SDL_MapRGBA(screen->format, 255,255,255,255));

    if(a != NULL) {
        sprintf(str, "Applied X Force 1: % f", a->xAcceleration1);
        stringRGBA(screen, 5, 5, str, 0, 0, 0, 255);
        sprintf(str, "Applied X Force 2: % f", a->xAcceleration2);
        stringRGBA(screen, 5, 25, str, 0, 0, 0, 255);
    }

    sprintf(str, "Angular Position1: % f", s->angularPosition1);
    stringRGBA(screen, 5, 15, str, 0, 0, 0, 255);

    sprintf(str, "Angular Position2: % f", s->angularPosition2);
    stringRGBA(screen, 5, 35, str, 0, 0, 0, 255);

    sprintf(str, "Distance         : % f", fabs(s->xPosition2 - s->xPosition1));
    stringRGBA(screen, 5, 45, str, 0, 0, 0, 255);

    sprintf(str, "Reward           : % f", reward);
    stringRGBA(screen, 5, 55, str, 0, 0, 0, 255);

    lineRGBA(screen, 10, screenHeight / 2.0, screenHeight - 10, screenHeight / 2.0, 0, 0, 0, 255);

    if(algorithm_drawingProcedure != NULL)
        algorithm_drawingProcedure(screen, screenWidth, screenHeight, instance);

    drawDIPS(screen, s, 0, 0, 0, 255, ratioPixels);

    if(a != NULL) {
        if(a->xAcceleration2 < 0)
            filledTrigonRGBA(screen, ((screenWidth / 2.0) * 3.0 / 4.0) - 10, screenHeight * 0.9, ((screenWidth / 2.0) * 3.0 / 4.0) - 20, (screenHeight * 0.9) - 5, ((screenWidth / 2.0) * 3.0 / 4.0) - 10, (screenHeight * 0.9) - 10 , 0, 0, 0, 255);
        else if(a->xAcceleration2 > 0)
            filledTrigonRGBA(screen, ((screenWidth / 2.0) * 3.0 / 4.0) + 10, screenHeight * 0.9, ((screenWidth / 2.0) * 3.0 / 4.0) + 20, (screenHeight * 0.9) - 5, ((screenWidth / 2.0) * 3.0 / 4.0) + 10, (screenHeight * 0.9) - 10, 0, 0, 0, 255);
        else
            boxRGBA(screen, ((screenWidth / 2.0) * 3.0 / 4.0) - 5, screenHeight * 0.9, ((screenWidth / 2.0) * 3.0 / 4.0) + 5, (screenHeight * 0.9) - 10, 0, 0, 0, 255);

        if(a->xAcceleration1 < 0)
            filledTrigonRGBA(screen, (screenWidth / 8.0) - 10, screenHeight * 0.9, (screenWidth / 8.0) - 20, (screenHeight * 0.9) - 5, (screenWidth / 8.0) - 10, (screenHeight * 0.9) - 10 , 0, 0, 0, 255);
        else if(a->xAcceleration1 > 0)
            filledTrigonRGBA(screen, (screenWidth / 8.0) + 10, screenHeight * 0.9, (screenWidth / 8.0) + 20, (screenHeight * 0.9) - 5, (screenWidth / 8.0) + 10, (screenHeight * 0.9) - 10, 0, 0, 0, 255);
        else
            boxRGBA(screen, (screenWidth / 8.0) - 5, screenHeight * 0.9, (screenWidth / 8.0) + 5, (screenHeight * 0.9) - 10, 0, 0, 0, 255);
    }

    if(algorithm_drawingProcedure != NULL)
        algorithm_drawingProcedure(screen, screenWidth, screenHeight, instance);

    SDL_Flip(screen);

    while(SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_KEYDOWN:
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    done = 1;
                if(event.key.keysym.sym == SDLK_SPACE)
                    done = waitForAnotherSpace();
                break;
	
            case SDL_QUIT:
                done = 1;
            break;

        }
    }

    SDL_framerateDelay(&fpsm);

    return done;

}
Example #22
0
void output_run(void* args)
{
    FPSmanager fps_manager;
    unsigned char frame[4096];

    SDL_initFramerate(&fps_manager);
    SDL_setFramerate(&fps_manager, 100);
    stat_ops = 100;

    output_running = 1;   
    unsigned int last_tick = SDL_GetTicks();

    while(output_running)
    {
        mbeat_t tb = timebase_get();

        update_patterns(tb);
        update_signals(tb);

        for(int i=0; i<n_output_strips; i++)
        {
            if(!output_strips[i].bus)
                continue;

            output_to_buffer(&output_strips[i], output_buffers[i]);

            float energy = 0.;
            float scalar = 1.0;
            for(int k = 0; k < output_strips[i].length; k++){
                energy += output_buffers[i][k].r;
                energy += output_buffers[i][k].g;
                energy += output_buffers[i][k].b;
            }
            scalar = output_strips[i].length * config.output.max_energy / energy * 255.;
            if(scalar > 255.)
                scalar = 255.;

            int j = 0;
            for(int k = 0; k < output_strips[i].length; k++){
                frame[j++] = output_buffers[i][k].r * scalar;
                frame[j++] = output_buffers[i][k].g * scalar;
                frame[j++] = output_buffers[i][k].b * scalar;
            }

            if(output_on_flux && (output_strips[i].bus & OUTPUT_FLUX))
                output_flux_push(&output_strips[i], frame, j);
        }
        SDL_framerateDelay(&fps_manager);
        //stat_ops = SDL_getFramerate(&fps_manager);
        stat_ops = 0.8 * stat_ops + 0.2 * (1000. / (SDL_GetTicks() - last_tick));
        last_tick = SDL_GetTicks();
    }

    for(int i=0; i<n_output_strips; i++)
    {
        free(output_buffers[i]);
    }

    free(output_buffers);

    if(output_on_flux)
        output_flux_del();
}
double FPSWrapper::delay(FPSmanager& fpsManager_){
	return (double)(SDL_framerateDelay(&fpsManager_)/1000.0);
}
Example #24
0
int Client::exec()
{
    int lastTickTime = tick_time;

    SDL_Event event;

    while (mState != STATE_EXIT)
    {
        if (mGame)
        {
            // Let the game handle the events while it is active
            mGame->handleInput();
        }
        else
        {
            // Handle SDL events
            while (SDL_PollEvent(&event))
            {
                switch (event.type)
                {
                    case SDL_QUIT:
                        mState = STATE_EXIT;
                        break;

                    case SDL_KEYDOWN:
                        break;

                    case SDL_VIDEORESIZE:
                        handleVideoResize(event.resize.w, event.resize.h);
                        break;
                }

                guiInput->pushInput(event);
            }
        }

        if (Net::getGeneralHandler())
            Net::getGeneralHandler()->flushNetwork();

        while (get_elapsed_time(lastTickTime) > 0)
        {
            gui->logic();
            if (mGame)
                mGame->logic();

            sound.logic();

            ++lastTickTime;
        }

        // This is done because at some point tick_time will wrap.
        lastTickTime = tick_time;

        // Update the screen when application is active, delay otherwise.
        if (isActive())
        {
            frame_count++;
            gui->draw();
            graphics->updateScreen();
        }
        else
        {
            SDL_Delay(10);
        }

        if (mLimitFps)
            SDL_framerateDelay(&mFpsManager);

        // TODO: Add connect timeouts
        if (mState == STATE_CONNECT_GAME &&
                 Net::getGameHandler()->isConnected())
        {
            Net::getLoginHandler()->disconnect();
        }
        else if (mState == STATE_CONNECT_SERVER &&
                 mOldState == STATE_CONNECT_SERVER &&
                 Net::getLoginHandler()->isConnected())
        {
            mState = STATE_LOGIN;
        }
        else if (mState == STATE_WORLD_SELECT && mOldState == STATE_UPDATE)
        {
            if (Net::getLoginHandler()->getWorlds().size() < 2)
            {
                mState = STATE_LOGIN;
            }
        }
        else if (mOldState == STATE_START ||
                 (mOldState == STATE_GAME && mState != STATE_GAME))
        {
            gcn::Container *top = static_cast<gcn::Container*>(gui->getTop());

            mDesktop = new Desktop;
            top->add(mDesktop);
            mSetupButton = new Button("", "Setup", this);
            mSetupButton->setButtonPopupText(_("Setup"));
            mSetupButton->setButtonIcon("button-icon-setup.png");
            mSetupButton->setPosition(top->getWidth() - mSetupButton->getWidth()
                                     - 3, 3);
            top->add(mSetupButton);

            mDesktop->setSize(graphics->getWidth(), graphics->getHeight());
        }

        if (mState == STATE_SWITCH_LOGIN && mOldState == STATE_GAME)
        {
            Net::getGameHandler()->disconnect();
        }

        if (mState != mOldState)
        {
            {
                Event event(Event::StateChange);
                event.setInt("oldState", mOldState);
                event.setInt("newState", mState);
                event.trigger(Event::ClientChannel);
            }

            if (mOldState == STATE_GAME)
            {
                delete mGame;
                mGame = 0;
            }

            mOldState = mState;

            // Get rid of the dialog of the previous state
            if (mCurrentDialog)
            {
                delete mCurrentDialog;
                mCurrentDialog = NULL;
            }
            // State has changed, while the quitDialog was active, it might
            // not be correct anymore
            if (mQuitDialog)
                mQuitDialog->scheduleDelete();

            switch (mState)
            {
                case STATE_CHOOSE_SERVER:
                    logger->log("State: CHOOSE SERVER");

                    // If a server was passed on the command line, or branding
                    // provides a server and a blank server list, we skip the
                    // server selection dialog.
                    if ((!mOptions.serverName.empty() && mOptions.serverPort)
                        || (!branding.getValue("defaultServer","").empty() &&
                            branding.getValue("defaultPort",0) &&
                            branding.getValue("onlineServerList", "").empty()))
                    {
                        mState = STATE_CONNECT_SERVER;

                        // Reset options so that cancelling or connect
                        // timeout will show the server dialog.
                        mOptions.serverName.clear();
                        mOptions.serverPort = 0;
                    }
                    else
                    {
                        // Don't allow an alpha opacity
                        // lower than the default value
                        Theme::instance()->setMinimumOpacity(0.8f);

                        mCurrentDialog = new ServerDialog(&mCurrentServer,
                                                          mConfigDir);
                    }
                    break;

                case STATE_CONNECT_SERVER:
                    logger->log("State: CONNECT SERVER");

                    Net::connectToServer(mCurrentServer);

                    mCurrentDialog = new ConnectionDialog(
                            _("Connecting to server"), STATE_SWITCH_SERVER);
                    break;

                case STATE_LOGIN:
                    logger->log("State: LOGIN");
                    // Don't allow an alpha opacity
                    // lower than the default value
                    Theme::instance()->setMinimumOpacity(0.8f);

                    if (mOptions.username.empty()
                            || mOptions.password.empty())
                    {
                        mCurrentDialog = new LoginDialog(&loginData);
                    }
                    else
                    {
                        mState = STATE_LOGIN_ATTEMPT;
                        // Clear the password so that when login fails, the
                        // dialog will show up next time.
                        mOptions.password.clear();
                    }
                    break;

                case STATE_LOGIN_ATTEMPT:
                    logger->log("State: LOGIN ATTEMPT");
                    accountLogin(&loginData);
                    mCurrentDialog = new ConnectionDialog(
                            _("Logging in"), STATE_SWITCH_SERVER);
                    break;

                case STATE_WORLD_SELECT:
                    logger->log("State: WORLD SELECT");
                    {
                        Worlds worlds = Net::getLoginHandler()->getWorlds();

                        if (worlds.size() == 0)
                        {
                            // Trust that the netcode knows what it's doing
                            mState = STATE_UPDATE;
                        }
                        else if (worlds.size() == 1)
                        {
                            Net::getLoginHandler()->chooseServer(0);
                            mState = STATE_UPDATE;
                        }
                        else
                        {
                            mCurrentDialog = new WorldSelectDialog(worlds);
                            if (mOptions.chooseDefault)
                            {
                                ((WorldSelectDialog*) mCurrentDialog)->action(
                                    gcn::ActionEvent(NULL, "ok"));
                            }
                        }
                    }
                    break;

                case STATE_WORLD_SELECT_ATTEMPT:
                    logger->log("State: WORLD SELECT ATTEMPT");
                    mCurrentDialog = new ConnectionDialog(
                            _("Entering game world"), STATE_WORLD_SELECT);
                    break;

                case STATE_UPDATE:
                    // Determine which source to use for the update host
                    if (!mOptions.updateHost.empty())
                        mUpdateHost = mOptions.updateHost;
                    else
                        mUpdateHost = loginData.updateHost;
                    initUpdatesDir();

                    if (mOptions.skipUpdate)
                    {
                        mState = STATE_LOAD_DATA;
                    }
                    else
                    {
                        logger->log("State: UPDATE");
                        mCurrentDialog = new UpdaterWindow(mUpdateHost,
                                mLocalDataDir + "/" + mUpdatesDir,mOptions.dataPath.empty());
                    }
                    break;

                case STATE_LOAD_DATA:
                    logger->log("State: LOAD DATA");

                    // If another data path has been set,
                    // we don't load any other files...
                    if (mOptions.dataPath.empty())
                    {
                        // Add customdata directory
                        ResourceManager::getInstance()->searchAndAddArchives(
                            "customdata/",
                            "zip",
                            false);
                    }

                    // Read default paths file 'data/paths.xml'
                    paths.init("paths.xml", true);

                    Event::trigger(Event::ClientChannel, Event::LoadingDatabases);

                    // Load XML databases
                    CharDB::load();
                    hairDB.load();
                    switch (Net::getNetworkType())
                    {
                      case ServerInfo::TMWATHENA:
                        itemDb = new TmwAthena::TaItemDB;
                      break;
                      case ServerInfo::MANASERV:
                        itemDb = new ManaServ::ManaServItemDB;
                      break;
                      default:
                        // Nothing
                        itemDb = 0;
                      break;
                    }
                    if (!itemDb || !itemDb->isLoaded())
                    {
                        // Warn and return to login screen
                        errorMessage =
                            _("This server is missing needed world data. "
                              "Please contact the administrator(s).");
                        showOkDialog(_("ItemDB: Error while loading "
                                       ITEMS_DB_FILE "!"), errorMessage,
                                     STATE_CHOOSE_SERVER);
                        break;
                    }
                    MonsterDB::load();
                    SpecialDB::load();
                    NPCDB::load();
                    EmoteDB::load();
                    StatusEffect::load();
                    Units::loadUnits();

                    ActorSprite::load();

                    mDesktop->reloadWallpaper();

                    mState = STATE_GET_CHARACTERS;
                    break;

                case STATE_GET_CHARACTERS:
                    logger->log("State: GET CHARACTERS");
                    Net::getCharHandler()->requestCharacters();
                    mCurrentDialog = new ConnectionDialog(
                            _("Requesting characters"),
                            STATE_SWITCH_SERVER);
                    break;

                case STATE_CHAR_SELECT:
                    logger->log("State: CHAR SELECT");
                    // Don't allow an alpha opacity
                    // lower than the default value
                    Theme::instance()->setMinimumOpacity(0.8f);

                    mCurrentDialog = new CharSelectDialog(&loginData);

                    if (!((CharSelectDialog*) mCurrentDialog)->selectByName(
                            mOptions.character, CharSelectDialog::Choose))
                    {
                        ((CharSelectDialog*) mCurrentDialog)->selectByName(
                                config.getStringValue("lastCharacter"),
                                mOptions.chooseDefault ?
                                    CharSelectDialog::Choose :
                                    CharSelectDialog::Focus);
                    }

                    // Choosing character on the command line should work only
                    // once, clear it so that 'switch character' works.
                    mOptions.character.clear();

                    break;

                case STATE_CONNECT_GAME:
                    logger->log("State: CONNECT GAME");

                    Net::getGameHandler()->connect();
                    mCurrentDialog = new ConnectionDialog(
                            _("Connecting to the game server"),
                            Net::getNetworkType() == ServerInfo::TMWATHENA ?
                            STATE_CHOOSE_SERVER : STATE_SWITCH_CHARACTER);
                    break;

                case STATE_CHANGE_MAP:
                    logger->log("State: CHANGE_MAP");

                    Net::getGameHandler()->connect();
                    mCurrentDialog = new ConnectionDialog(
                            _("Changing game servers"),
                            STATE_SWITCH_CHARACTER);
                    break;

                case STATE_GAME:
                    logger->log("Memorizing selected character %s",
                            local_player->getName().c_str());
                    config.setValue("lastCharacter", local_player->getName());

                    // Fade out logon-music here too to give the desired effect
                    // of "flowing" into the game.
                    sound.fadeOutMusic(1000);

                    // Allow any alpha opacity
                    Theme::instance()->setMinimumOpacity(-1.0f);

                    delete mSetupButton;
                    delete mDesktop;
                    mSetupButton = NULL;
                    mDesktop = NULL;

                    mCurrentDialog = NULL;

                    logger->log("State: GAME");
                    mGame = new Game;
                    break;

                case STATE_LOGIN_ERROR:
                    logger->log("State: LOGIN ERROR");
                    showErrorDialog(errorMessage, STATE_LOGIN);
                    break;

                case STATE_ACCOUNTCHANGE_ERROR:
                    logger->log("State: ACCOUNT CHANGE ERROR");
                    showErrorDialog(errorMessage, STATE_CHAR_SELECT);
                    break;

                case STATE_REGISTER_PREP:
                    logger->log("State: REGISTER_PREP");
                    Net::getLoginHandler()->getRegistrationDetails();
                    mCurrentDialog = new ConnectionDialog(
                            _("Requesting registration details"), STATE_LOGIN);
                    break;

                case STATE_REGISTER:
                    logger->log("State: REGISTER");
                    mCurrentDialog = new RegisterDialog(&loginData);
                    break;

                case STATE_REGISTER_ATTEMPT:
                    logger->log("Username is %s", loginData.username.c_str());
                    Net::getLoginHandler()->registerAccount(&loginData);
                    loginData.password = "";
                    break;

                case STATE_CHANGEPASSWORD:
                    logger->log("State: CHANGE PASSWORD");
                    mCurrentDialog = new ChangePasswordDialog(&loginData);
                    break;

                case STATE_CHANGEPASSWORD_ATTEMPT:
                    logger->log("State: CHANGE PASSWORD ATTEMPT");
                    Net::getLoginHandler()->changePassword(loginData.username,
                                                loginData.password,
                                                loginData.newPassword);
                    break;

                case STATE_CHANGEPASSWORD_SUCCESS:
                    logger->log("State: CHANGE PASSWORD SUCCESS");
                    showOkDialog(_("Password Change"),
                                 _("Password changed successfully!"),
                                 STATE_CHAR_SELECT);
                    loginData.password = "";
                    loginData.newPassword = "";
                    break;

                case STATE_CHANGEEMAIL:
                    logger->log("State: CHANGE EMAIL");
                    mCurrentDialog = new ChangeEmailDialog(&loginData);
                    break;

                case STATE_CHANGEEMAIL_ATTEMPT:
                    logger->log("State: CHANGE EMAIL ATTEMPT");
                    Net::getLoginHandler()->changeEmail(loginData.email);
                    break;

                case STATE_CHANGEEMAIL_SUCCESS:
                    logger->log("State: CHANGE EMAIL SUCCESS");
                    showOkDialog(_("Email Change"),
                                 _("Email changed successfully!"),
                                 STATE_CHAR_SELECT);
                    break;

                case STATE_UNREGISTER:
                    logger->log("State: UNREGISTER");
                    mCurrentDialog = new UnRegisterDialog(&loginData);
                    break;

                case STATE_UNREGISTER_ATTEMPT:
                    logger->log("State: UNREGISTER ATTEMPT");
                    Net::getLoginHandler()->unregisterAccount(
                            loginData.username, loginData.password);
                    break;

                case STATE_UNREGISTER_SUCCESS:
                    logger->log("State: UNREGISTER SUCCESS");
                    Net::getLoginHandler()->disconnect();

                    showOkDialog(_("Unregister Successful"),
                                 _("Farewell, come back any time..."),
                                 STATE_CHOOSE_SERVER);
                    loginData.clear();
                    break;

                case STATE_SWITCH_SERVER:
                    logger->log("State: SWITCH SERVER");

                    Net::getLoginHandler()->disconnect();
                    Net::getGameHandler()->disconnect();

                    mState = STATE_CHOOSE_SERVER;
                    break;

                case STATE_SWITCH_LOGIN:
                    logger->log("State: SWITCH LOGIN");

                    Net::getLoginHandler()->disconnect();

                    mState = STATE_CONNECT_SERVER;
                    break;

                case STATE_SWITCH_CHARACTER:
                    logger->log("State: SWITCH CHARACTER");

                    // Done with game
                    Net::getGameHandler()->disconnect();

                    mState = STATE_GET_CHARACTERS;
                    break;

                case STATE_LOGOUT_ATTEMPT:
                    logger->log("State: LOGOUT ATTEMPT");
                    // TODO
                    break;

                case STATE_WAIT:
                    logger->log("State: WAIT");
                    break;

                case STATE_EXIT:
                    logger->log("State: EXIT");
                    Net::unload();
                    break;

                case STATE_FORCE_QUIT:
                    logger->log("State: FORCE QUIT");
                    if (Net::getGeneralHandler())
                        Net::getGeneralHandler()->unload();
                    mState = STATE_EXIT;
                  break;

                case STATE_ERROR:
                    logger->log("State: ERROR");
                    logger->log("Error: %s", errorMessage.c_str());
                    showErrorDialog(errorMessage, STATE_CHOOSE_SERVER);
                    Net::getGameHandler()->disconnect();
                    break;

                default:
                    mState = STATE_FORCE_QUIT;
                    break;
            }
        }
    }

    return 0;
}
unsigned int viewer(state* s, double* a, double reward, void* instance) {

    char str[255];
    double cartPoleScalingFactor = (screenWidth / 2.0) - 20;
    double ratioPixels = cartPoleScalingFactor / (2.0 * parameters[1]);
    int done = 0;
    SDL_Event event;


    SDL_FillRect(screen, NULL, SDL_MapRGBA(screen->format, 255,255,255,255));

    if(a != NULL) {
        sprintf(str, "Applied X Force  : % f", ((parameters[7] + parameters[7]) * a[0]) - parameters[7]);
        stringRGBA(screen, 5, 5, str, 0, 0, 0, 255);
    }

    sprintf(str, "Angular Position: % f", s->angularPosition);
    stringRGBA(screen, 5, 15, str, 0, 0, 0, 255);

    sprintf(str, "Angular Velocity: % f", s->angularVelocity);
    stringRGBA(screen, 5, 25, str, 0, 0, 0, 255);

    sprintf(str, "X Position      : % f", s->xPosition);
    stringRGBA(screen, 5, 35, str, 0, 0, 0, 255);

    sprintf(str, "X Velocity      : % f", s->xVelocity);
    stringRGBA(screen, 5, 45, str, 0, 0, 0, 255);

    sprintf(str, "Reward          : % f", reward);
    stringRGBA(screen, 5, 55, str, 0, 0, 0, 255);

    stringRGBA(screen, 5, screenHeight - 10, "Press escape to quit", 0, 0, 0, 255);

    lineRGBA(screen, 10, screenHeight / 2.0, (screenWidth / 2.0) - 10, screenHeight / 2.0, 0, 0, 0, 255);
    drawPendulum(s, 0, 0, 0, 255, ratioPixels);

    if(a != NULL) {
        if(a[0] < 0.5)
            filledTrigonRGBA(screen, (screenWidth / 4.0) - 10, screenHeight * 0.9, (screenWidth / 4.0), (screenHeight * 0.9) - 5, (screenWidth / 4.0) - 10, (screenHeight * 0.9) - 10 , 0, 0, 0, 255);
        else if(a[0] > 0.5)
            filledTrigonRGBA(screen, (screenWidth / 4.0) + 10, screenHeight * 0.9, (screenWidth / 4.0) + 20, (screenHeight * 0.9) - 5, (screenWidth / 4.0) + 10, (screenHeight * 0.9) - 10, 0, 0, 0, 255);
        else
            boxRGBA(screen, (screenWidth / 4.0) - 5, screenHeight * 0.9, (screenWidth / 4.0) + 5, (screenHeight * 0.9) - 10, 0, 0, 0, 255);
    }

    if(algorithm_drawingProcedure != NULL)
        algorithm_drawingProcedure(screen, screenWidth, screenHeight, instance);

    SDL_Flip(screen);

    while(SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_KEYDOWN:
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    done = 1;
                if(event.key.keysym.sym == SDLK_SPACE)
                    done = waitForAnotherSpace();
                break;
	
            case SDL_QUIT:
                done = 1;
            break;

        }
    }

    SDL_framerateDelay(&fpsm);

    return done;

}