static void init_sdl() { SDL_putenv("SDL_NOMOUSE=1"); SDL_putenv("SDL_VIDEO_CENTERED=1"); SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE); atexit(SDL_Quit); signal(SIGINT, SIG_DFL); SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); SDL_AudioSpec desired = {.freq = 8000, .format = AUDIO_U8, .channels = 1, .callback = snd_callback, .samples=128}; if(SDL_OpenAudio(&desired, NULL)) { fprintf(stderr, "%s\n", SDL_GetError()); sound_playing = -1; } SDL_initFramerate(&fps); SDL_setFramerate(&fps, 60); inited_sdl = 1; } static void button_change(int up, SDLKey keysym) { const uint32_t key_map[SDLK_LAST] = { [SDLK_LEFT] = KEY_LF, [SDLK_RIGHT] = KEY_RT, [SDLK_UP] = KEY_UP, [SDLK_DOWN] = KEY_DN, [SDLK_RETURN] = KEY_A, [SDLK_SPACE] = KEY_A, [SDLK_z] = KEY_A, [SDLK_x] = KEY_B, [SDLK_LSHIFT] = KEY_B, [SDLK_RSHIFT] = KEY_A }; /* Don't invoke undefined behavior if they've added keysyms * since this was compiled. */ if(keysym > SDLK_LAST) return; if(!key_map[keysym]) return; if(up) { buttons &= ~key_map[keysym]; } else { buttons |= key_map[keysym]; } }
int setFPSBinding(lua_State *L) { l81.fps = lua_tonumber(L,-1); if (l81.fps <= 0) l81.fps = 1; SDL_setFramerate(&l81.fb->fps_mgr,l81.fps); return 0; }
void initSDL() { SDL_DisplayMode video_info; int init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK; if(SDL_Init(init_flags) < 0) { printf("SDL Failed to Init!!!! (%s)\n", SDL_GetError()); borExit(0); } SDL_ShowCursor(SDL_DISABLE); atexit(SDL_Quit); #ifdef LOADGL if(SDL_GL_LoadLibrary(NULL) < 0) { printf("Warning: couldn't load OpenGL library (%s)\n", SDL_GetError()); } #endif SDL_GetCurrentDisplayMode(0, &video_info); nativeWidth = video_info.w; nativeHeight = video_info.h; printf("debug:nativeWidth, nativeHeight, bpp, Hz %d, %d, %d, %d\n", nativeWidth, nativeHeight, SDL_BITSPERPIXEL(video_info.format), video_info.refresh_rate); SDL_initFramerate(&framerate_manager); SDL_setFramerate(&framerate_manager, 200); }
void initSimulation (Simulation* sim) { //initialisation de la simulation sim->sdlInitialisee = false; sim->simulationLancee = false; sim->map.largeur_map = NB_CASE_LARGEUR_DEFAUT; sim->map.hauteur_map = NB_CASE_HAUTEUR_DEFAUT; sim->genererNouvelleMap=1; sim->genererPosEspeces=1; sim->map.mapInitialisee=0; sim->nomSimulation=(char*)malloc(TAILLE_MAX*sizeof(char)); strcpy(sim->nomSimulation,"nouvelle simulation"); //initialisation de la generation aleatoire srand(time(NULL)); //initialisation de SDL_framerate qui gere le fps SDL_Init(SDL_INIT_TIMER // pour SDL_framerate |SDL_INIT_NOPARACHUTE); // pour mieux débugger, à enlever si besoin SDL_initFramerate(&(sim->fps)); SDL_setFramerate((&sim->fps), 30); //évite le problème d'affichage de la première ligne // @fixme: aucun printf ne marche sur windows, les g_print non plus (à vérifier) printf("\n"); }
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); } }
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; }
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); }
void WindowManager::setFramerate(const unsigned int fpsLimit) { if (!fpsLimit) return; if (!settings.limitFps) return; SDL_setFramerate(&fpsManager, fpsLimit); }
void FPSWrapper::initialize(FPSmanager& fpsManager_){ SDL_initFramerate(&fpsManager_); const int framerateIsSet = SDL_setFramerate(&fpsManager_, Configuration::getMaxFramerate()); if(framerateIsSet == 0){ Logger::log("Successfully started the framerate manager."); } else{ Logger::warning("Failed to start the framerate manager."); } }
int initViewer(char* resolution, void(*drawingProcedure)(SDL_Surface*,int,int,void*), char isFullscreen) { const SDL_VideoInfo *info; Uint8 video_bpp; Uint32 videoflags; /* Initialize SDL */ if(SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); return -1; } atexit(SDL_Quit); putenv("SDL_VIDEO_WINDOW_POS=center"); /* Alpha blending doesn't work well at 8-bit color */ info = SDL_GetVideoInfo(); if(info->vfmt->BitsPerPixel > 8) video_bpp = info->vfmt->BitsPerPixel; else video_bpp = 16; videoflags = SDL_HWSURFACE | SDL_SRCALPHA | SDL_RESIZABLE | SDL_DOUBLEBUF; if(isFullscreen) videoflags |= SDL_FULLSCREEN; /* Set 640x480 video mode */ screenWidth = atoi(strtok(resolution, "x")); screenHeight = atoi(strtok(NULL, "x")); if((screen=SDL_SetVideoMode(screenWidth,screenHeight,video_bpp,videoflags)) == NULL) { fprintf(stderr, "Couldn't set %ix%i video mode: %s\n",screenWidth, screenHeight,SDL_GetError()); return -1; } /* Use alpha blending */ SDL_SetAlpha(screen, SDL_SRCALPHA, 0); /* Set title for window */ SDL_WM_SetCaption("Double Cart Pole Viewer","Double Cart Pole Viewer"); SDL_initFramerate(&fpsm); SDL_setFramerate(&fpsm, 1.0 / timeStep); algorithm_drawingProcedure = drawingProcedure; return 0; }
void Client::event(Event::Channel channel, const Event &event) { if (channel == Event::ConfigChannel && event.getType() == Event::ConfigOptionChanged && event.getString("option") == "fpslimit") { const int fpsLimit = config.getIntValue("fpslimit"); mLimitFps = fpsLimit > 0; if (mLimitFps) SDL_setFramerate(&mFpsManager, fpsLimit); } }
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; }
int main(int argc, char **argv) { NOTUSED(argc); NOTUSED(argv); initConfig(); parseOptions(argc,argv); initScreen(); initEditor(l81.fb,30,30,30,30); editorOpen(l81.filename); while(1) { resetProgram(); loadProgram(); if (!l81.luaerr) { SDL_setFramerate(&l81.fb->fps_mgr,l81.fps); l81.start_ms = mstime(); while(!processSdlEvents()); if (editorFileWasModified()) editorSave(l81.filename); } editorRun(); } return 0; }
int sdl_init( void ) { int mode = SDL_SWSURFACE|SDL_OPENGL; const struct config *config = config_get(); if( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) { fprintf(stderr, "Error: Unable to initialise SDL: %s\n", SDL_GetError()); return 1; } SDL_ShowCursor(SDL_DISABLE); memcpy( &saved_video, SDL_GetVideoInfo(), sizeof(SDL_VideoInfo) ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); if( config->iface.full_screen ) mode |= SDL_FULLSCREEN; screen = SDL_SetVideoMode( config->iface.screen_width, config->iface.screen_height, SDL_SCREEN_BPP, mode ); if( screen == NULL ) { fprintf(stderr, "Error: Unable to set video mode: %s\n", SDL_GetError()); return 1; } SDL_initFramerate( &manager ); frame_rate = config->iface.frame_rate; if( frame_rate < 0 ) { frame_rate = 0; fprintf( stderr, "Warning: Negative frame rate, setting to 0 (unlimited)\n" ); } if( frame_rate > MAX_FRAME_RATE ) { frame_rate = MAX_FRAME_RATE; fprintf( stderr, "Warning: Frame rate above maximum allowed (%d) setting to maximum\n", MAX_FRAME_RATE ); } if( frame_rate ) { SDL_setFramerate( &manager, frame_rate ); } SDL_WM_SetCaption( title, NULL ); return 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; }
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(); }
void Display::Set_FPSmanager(int f){ SDL_setFramerate(&manager,f); }
/*---------------------------------------------------------------------------- * Initialize *----------------------------------------------------------------------------*/ int media_init(void) { if (SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "%s\n", SDL_GetError()); exit(0); } // Initialize window and load all graphics. Exit on failure (we need all // graphics to play). if ((media.canvas = SDL_SetVideoMode(800, 600, 16, SDL_DOUBLEBUF)) == NULL) { fprintf(stderr, "%s\n", SDL_GetError()); exit(0); } media.surface_title = load_texture("title.png"); media.surface_frame = load_texture("frame.png"); media.surface_objects = load_texture("objects.png"); media.surface_effects = load_texture("effects.png"); media.surface_manual = load_texture("manual.png"); media.surface_properties = load_texture("properties.png"); media.surface_circle = load_texture("circle.png"); if ((media.surface_background = SDL_CreateRGBSurface(SDL_SWSURFACE, media.canvas->w, media.canvas->h + 4, media.canvas->format->BitsPerPixel, media.canvas->format->Rmask, media.canvas->format->Gmask, media.canvas->format->Bmask, media.canvas->format->Amask)) == NULL) { fprintf(stderr, "%s\n", SDL_GetError()); exit(0); } SDL_Surface *tmp; SDL_Rect dst; tmp = load_texture("background.png"); for (dst.x = 0; dst.x < media.surface_background->w; dst.x += tmp->w) for (dst.y = 0; dst.y < media.surface_background->h; dst.y += tmp->h) { SDL_BlitSurface(tmp, NULL, media.surface_background, &dst); } SDL_FreeSurface(tmp); // Initialize and load true type fonts. Exit on failure. if (TTF_Init()) { fprintf(stderr, "%s\n", TTF_GetError()); exit(0); } media.font_small = load_font("underwood_champion.ttf", 16); media.font_normal = load_font("underwood_champion.ttf", 18); media.font_large = load_font("underwood_champion.ttf", 30); media.font_input = load_font("underwood_champion.ttf", 26); media.font_equation = load_font("underwood_champion.ttf", 20); media.font_button = load_font("j_d_handcrafted.ttf", 22); media.surface_hforhelp = TTF_RenderUTF8_Blended(media.font_normal, lang.hforhelp, color_white); // Initialize audio if wanted and load all samples. Disable audio on failure // (audio is not indispensable) if (media.enable_audio) { if (SDL_InitSubSystem(SDL_INIT_AUDIO)) { fprintf(stderr, "%s\n", SDL_GetError()); media.enable_audio = 0; } else if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024)) { fprintf(stderr, "%s\n", Mix_GetError()); media.enable_audio = 0; } else { media.chunk_press = load_sample("press.wav"); media.chunk_release = load_sample("release.wav"); media.chunk_open = load_sample("open.wav"); media.chunk_fail = load_sample("fail.wav"); media.chunk_wodox = load_sample("wodox.wav"); media.chunk_keystroke = load_sample("typewriter.wav"); media.chunk_marker = load_sample("marker01.wav"); } } // Give the window a name. SDL_WM_SetCaption("Wodox", "wodox"); // Initialize frame rate control. SDL_initFramerate(&media.fpsmanager); SDL_setFramerate(&media.fpsmanager, 30); // Most of the time keyrepeat is set to true. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); return 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); } }
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; }
/** \brief Initializers the event handlers * * \return void * */ void CShooterGame::InitHandlers() { /////////////////////////////////////////////////// // // On User Events // /////////////////////////////////////////////////// m_Handlers["OnUserEvent"] = { { // // STATE::SPLASH_SCREEN // (int)STATE::SPLASH_SCREEN, [&](SDL_Event& ev){ int nEventType = ev.user.code; if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) { int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nScene ) { case SCENE_0_Intro: // // SCENE::INTRO // if ( nState == (int)SceneSplashScreen::STATE::FADE_OUT ) { if ( !CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) ) { LoadAndRunScene( SCENE_1_Game ); SetState( (int)STATE::GAME ); } } if ( nState == (int)SceneSplashScreen::STATE::END ) { if ( CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) ) { SetRunning( false ); } } break; default: break; } } if ( nEventType == DemoEngine::EVENTTYPE::CUSTOM_EVENT ) { int nEventID = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nEventID ) { case (int)EVENT::START_NEW_GAME: SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT ); LoadAndRunScene( SCENE_1_Game ); SetState( (int)STATE::GAME ); break; case (int)EVENT::SHOW_HIGHSCORES: SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT_NOMUSIC ); LoadAndRunScene( SCENE_3_Highscores ); SetState( (int)STATE::HIGHSCORES ); break; case (int)EVENT::SHOW_HELP: SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT_NOMUSIC ); LoadAndRunScene( SCENE_4_Help ); SetState( (int)STATE::HELP ); break; case (int)EVENT::END_GAME: SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT ); CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) = (bool)true; break; default: break; } } } }, { // // STATE::HIGHSCORES // (int)STATE::HIGHSCORES, [&](SDL_Event& ev){ int nEventType = ev.user.code; if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) { int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nScene ) { case SCENE_3_Highscores: // // SCENE::HELP // if ( nState == (int)SceneHighscores::STATE::FADE_OUT ) { LoadAndRunScene( SCENE_0_Intro ); SetSceneState( SCENE_0_Intro, (int)SceneSplashScreen::STATE::START_NOMUSIC ); SetState( (int)STATE::SPLASH_SCREEN ); } break; default: break; } } } }, { // // STATE::HELP // (int)STATE::HELP, [&](SDL_Event& ev){ int nEventType = ev.user.code; if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) { int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nScene ) { case SCENE_4_Help: // // SCENE::HELP // if ( nState == (int)SceneHelp::STATE::FADE_OUT ) { LoadAndRunScene( SCENE_0_Intro ); SetSceneState( SCENE_0_Intro, (int)SceneSplashScreen::STATE::START_NOMUSIC ); SetState( (int)STATE::SPLASH_SCREEN ); } break; default: break; } } } }, { // // STATE::GAME // (int)STATE::GAME, [&](SDL_Event& ev){ int nEventType = ev.user.code; if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) { int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nScene ) { case SCENE_1_Game: // // SCENE::GAME // if ( nState == (int)SceneLevel::STATE::FADE_OUT ) { LoadAndRunScene( SCENE_2_GameOver ); SetState( (int)STATE::GAME_OVER ); } break; default: break; } } } }, { // // STATE::GAME_OVER // (int)STATE::GAME_OVER, [&](SDL_Event& ev){ int nEventType = ev.user.code; if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) { int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1)); int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2)); switch ( nScene ) { case SCENE_2_GameOver: // // SCENE::GAME_OVER // if ( nState == (int)SceneGameOver::STATE::FADE_OUT ) { #ifdef DEBUG_SCENE1 cout << "Restarting Scene 1 because DEBUG_SCENE1 defined." << endl; StopScene( SCENE_1_Game ); LoadAndRunScene( SCENE_1_Game ); SetState( (int)STATE::GAME ); #else LoadAndRunScene( SCENE_0_Intro ); SetState( (int)STATE::SPLASH_SCREEN ); #endif } break; default: break; } } } } }; /////////////////////////////////////////////////// // // Post Render // /////////////////////////////////////////////////// m_Handlers["PostRender"] = { { // // STATE::SPLASH_SCREEN // (int)CGame::STATE::ANY_STATE, [&](SDL_Event& ev){ DISCARD_UNUNSED_PARAMETER( ev ); auto& renderer = CSingleton<CRenderer>::Instance(); int x = m_iScreenW + m_noteImgWidth - ((int)(GetRealTime()*60) % (m_iScreenW + m_noteImgWidth*2)); renderer->Render( TextFactory::Instance()->Get( RESOURCE::TEXT_BETA_BUILD_NOTE ), x, m_iScreenH-12 ); } } }; /////////////////////////////////////////////////// // // OnKeyDown // /////////////////////////////////////////////////// m_Handlers["OnKeyDown"] = { { // // STATE::TESTS // (int)CGame::STATE::ANY_STATE, [&](SDL_Event& ev){ switch ( ev.key.keysym.sym ) { #ifdef DEBUG case SDLK_1: cout << "Setting Game speed to 0.1" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.1f; break; case SDLK_2: cout << "Setting Game speed to 0.3" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.3f; break; case SDLK_3: cout << "Setting Game speed to 0.5" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.5f; break; case SDLK_4: cout << "Setting Game speed to 0.7" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.7f; break; case SDLK_5: cout << "Setting Game speed to 1.0" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.0f; break; case SDLK_6: cout << "Setting Game speed to 1.3" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.3f; break; case SDLK_7: cout << "Setting Game speed to 1.5" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.5f; break; case SDLK_8: cout << "Setting Game speed to 1.7" << endl; CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.7f; break; #endif case SDLK_F1: cout << "Setting FPS to 10" << endl; SDL_setFramerate( &m_fpsManager, 10 ); break; case SDLK_F2: cout << "Setting FPS to 20" << endl; SDL_setFramerate( &m_fpsManager, 20 ); break; case SDLK_F3: cout << "Setting FPS to 30" << endl; SDL_setFramerate( &m_fpsManager, 30 ); break; case SDLK_F4: cout << "Setting FPS to 40" << endl; SDL_setFramerate( &m_fpsManager, 40 ); break; case SDLK_F5: cout << "Setting FPS to 50" << endl; SDL_setFramerate( &m_fpsManager, 50 ); break; case SDLK_F6: cout << "Setting FPS to 60" << endl; SDL_setFramerate( &m_fpsManager, 60 ); break; case SDLK_F7: cout << "Setting FPS to 120" << endl; SDL_setFramerate( &m_fpsManager, 120 ); break; default: break; } } } }; }
void * hax_sdl_main(void *configuration) { hax_thread_config_t * hax_configs = (hax_thread_config_t *) configuration; hax_general_settings_t * hax_user_settings = &hax_configs->user_settings; hax_sdl_data * hax_sound_data = (hax_sdl_data *) hax_configs->data_zone; printf("[SDL] Thread Start!\n"); FPSmanager hax_fps; float displ = 0; SDL_initFramerate(&hax_fps); SDL_setFramerate(&hax_fps, 60); // SDL video initialisation if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "Unable to init SDL: %s\n", SDL_GetError() ); pthread_exit((void *) 1); } atexit(SDL_Quit); SDL_Surface* screen = SDL_SetVideoMode(hax_user_settings->window_w, hax_user_settings->window_h, 32, SDL_HWSURFACE|SDL_DOUBLEBUF); if ( !screen ) { printf("Unable to set %i x %i video: %s\n", hax_user_settings->window_w, hax_user_settings->window_h, SDL_GetError()); pthread_exit((void *) 1); } printf("[SDL] Waiting to start...\n"); fflush(stdout); std::cout.flush(); hax_configs->timer->start(); printf("[SDL] Firing Loop!\n"); fflush(stdout); std::cout.flush(); while (*hax_user_settings->message) { hax_configs->timer->wait_next_activation(); hax_configs->timer->stat_execution_start(); // We catch an SDL signal SDL_Event event; while (SDL_PollEvent(&event)) { // If there was any signal switch (event.type) { // We exit if the window is closed case SDL_QUIT: *hax_user_settings->message = false; break; // We also check for keypresses case SDL_KEYDOWN: { // Then we exit if ESCAPE is pressed if (event.key.keysym.sym == SDLK_ESCAPE) *hax_user_settings->message = false; break; } } } // end of message processing // At first we clear the screen SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0)); vlineColor(screen, screen->w / 2, 0, screen->h, 0xffffffff); printf("[SDL] Requiring Locks!\n"); fflush(stdout); std::cout.flush(); // Here we lock the data and then plot amplitude and spectrums hax_sound_data->lock_data(); printf("[SDL] Plotting Sound Data!\n"); fflush(stdout); std::cout.flush(); draw_sound(screen, hax_sound_data->get_frames(), hax_sound_data->get_left_sound_channel(), hax_sound_data->get_right_sound_channel(), (screen->h)/7, (screen->h)/7, 0xff00ffff); draw_real_spectrum(screen, hax_sound_data->get_frames(), hax_sound_data->get_right_spectrum(), (screen->h*7)/14, ((screen->h)/14), (char *)"Right", 0x00ffffff ); draw_imaginary_spectrum(screen, hax_sound_data->get_frames(), hax_sound_data->get_right_spectrum(), (screen->h*9)/14, ((screen->h)/14), (char *)"Right", 0x00ffffff ); draw_real_spectrum(screen, hax_sound_data->get_frames(), hax_sound_data->get_left_spectrum(), (screen->h*11)/14, ((screen->h)/14), (char *)"Left", 0x00ffffff); draw_imaginary_spectrum(screen, hax_sound_data->get_frames(), hax_sound_data->get_left_spectrum(), (screen->h*13)/14, ((screen->h)/14), (char *)"Left", 0x00ffffff ); printf("[SDL] Releasing Locks!\n"); fflush(stdout); std::cout.flush(); hax_sound_data->unlock_data(); // Finally, we update the screen SDL_Flip(screen); displ ++; hax_configs->timer->stat_update(); } printf("Exited cleanly\n"); // Printing Thread Statistics hax_configs->timer->stats_print(); pthread_exit((void *) 0); }
void CShooterGame::Initialize() { // Must call base class initializations first CGame::Initialize(); #ifdef DEBUG cout << "CShooterGame::Initialize() called" << endl; #endif auto& renderer = CSingleton<CRenderer>::Instance(); SDL_WM_SetCaption("Space Attackers!", "Space Attackers!"); auto screen = renderer->GetScreen(); m_iScreenW = screen->w; m_iScreenH = screen->h; // Create global mutex using Factory pattern { // Prepare Mutex singleton for access from multiple threads at the same time MutexFactory::Instance()->Initialize( RESOURCE::MUTEX_MAINAPP ); } // Prepare rand() for multithreaded execution { CSingleton<CRandom>::Instance()->nextNumber(); } // Load window icon using Factory pattern { ImageColorkeyFactory::Instance()->Get( RESOURCE::WINDOW_ICON )->Load( "Assets/Icon/icon.bmp" ); ImageColorkeyFactory::Instance()->Get( RESOURCE::WINDOW_ICON )->SetColorKeyRGB( 0, 255, 255 ); SDL_WM_SetIcon( ImageColorkeyFactory::Instance()->Get( RESOURCE::WINDOW_ICON )->GetSurface(), 0 ); } // Load sprites using Factory pattern { ImageAlphaFactory::Instance()->Get( RESOURCE::PLAYER_PLANE )->Load( "Assets/Sprites/player_plane.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::PLAYER_PLANE_HIT )->Load( "Assets/Sprites/player_plane_hit.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::PLAYER_PLANE_SHADOW )->Load( "Assets/Sprites/player_plane_shadow_0.5x.png" ); AnimationFactory::Instance()->Get( RESOURCE::PLAYER_PLANE )->LoadAnimation( "Assets/Sprites/player_plane.anim" ); AnimationFactory::Instance()->Get( RESOURCE::PLAYER_PLANE_SHADOW )->LoadAnimation( "Assets/Sprites/player_plane_shadow_0.5x.anim" ); ImageAlphaFactory::Instance()->Get( RESOURCE::PLAYER_PROJECTILE )->Load( "Assets/Sprites/plasma_up_yellow.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::PLAYER_PROJECTILE_GUIDED )->Load( "Assets/Sprites/plasma_ball_blue.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PROJECTILE_SLOW )->Load( "Assets/Sprites/plasma_ball_green.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PROJECTILE_FAST )->Load( "Assets/Sprites/plasma_ball_red.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PLANE_GREEN )->Load( "Assets/Sprites/plane_green_down.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PLANE_RED )->Load( "Assets/Sprites/plane_red_down.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PLANE_GREEN_HIT )->Load( "Assets/Sprites/plane_green_down_hit.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PLANE_RED_HIT )->Load( "Assets/Sprites/plane_red_down_hit.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::ENEMY_PLANE_SHADOW )->Load( "Assets/Sprites/plane_down_shadow_0.5x.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::EXPLOSION )->Load( "Assets/Sprites/explosion.png" ); AnimationFactory::Instance()->Get( RESOURCE::EXPLOSION )->LoadAnimation( "Assets/Sprites/explosion.anim" ); } // Create interpolation sets for intro screen and level start message { auto& introOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_INTRO_SHOW ); introOverTime->AddValue( 0.0f, 0 ); introOverTime->AddValue( 0.5f, 255, Math::Interpolation::easeOutCirc<float,float> ); introOverTime->AddValue( 3.5f, 255 ); introOverTime->AddValue( 5.0f, 0, Math::Interpolation::easeInCirc<float,float> ); auto& levelStartOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_LEVEL_START ); levelStartOverTime->AddValue( 0.0f, m_iScreenH ); levelStartOverTime->AddValue( 1.5f, m_iScreenH/2 - 32, Math::Interpolation::easeOutCirc<float,float> ); levelStartOverTime->AddValue( 3.5f, m_iScreenH/2 - 32 ); levelStartOverTime->AddValue( 5.0f, -64, Math::Interpolation::easeInCirc<float,float> ); } // Load menu sprites using Factory pattern { ImageAlphaFactory::Instance()->Get( RESOURCE::MENU_TEXT )->Load( "Assets/Menu/texts.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::MENU_TEXT_SELECTED )->Load( "Assets/Menu/texts_selected.png" ); AnimationFactory::Instance()->Get( RESOURCE::MENU_TEXT )->LoadAnimation( "Assets/Menu/texts.anim" ); } // load backgrounds using Factory pattern { ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_INTRO )->Load( "Assets/Backgrounds/intro_screen.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_TITLE )->Load( "Assets/Backgrounds/title_screen.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_DEATH )->Load( "Assets/Backgrounds/death.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_HELP1 )->Load( "Assets/Backgrounds/help1.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_HELP2 )->Load( "Assets/Backgrounds/help2.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_MOONSURFACE )->Load( "Assets/Backgrounds/moon.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_CLOUDS1 )->Load( "Assets/Backgrounds/clouds1_tr50.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_CLOUDS2 )->Load( "Assets/Backgrounds/clouds2_tr50.png" ); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_MOONSURFACE )->SetAlpha(255); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_CLOUDS1 )->SetAlpha(0); ImageAlphaFactory::Instance()->Get( RESOURCE::BACKGROUND_CLOUDS2 )->SetAlpha(0); // Create layers and set the bitmaps ScrollingBackgroundFactory::Instance()->Get( RESOURCE::SCROLLING_MOONSURFACE )->Initialize(1); ScrollingBackgroundFactory::Instance()->Get( RESOURCE::SCROLLING_CLOUDS )->Initialize(2); auto& moonSurfaceLayer = ScrollingBackgroundFactory::Instance()->Get( RESOURCE::SCROLLING_MOONSURFACE ); moonSurfaceLayer->SetLayer( 0, RESOURCE::BACKGROUND_MOONSURFACE ); moonSurfaceLayer->SetLayerSpeed( 0, 8, 8 ); // 1:15 movement speed moonSurfaceLayer->SetSpeed( 0, -250 ); auto& cloudsLayers = ScrollingBackgroundFactory::Instance()->Get( RESOURCE::SCROLLING_CLOUDS ); cloudsLayers->SetLayer( 0, RESOURCE::BACKGROUND_CLOUDS1 ); cloudsLayers->SetLayer( 1, RESOURCE::BACKGROUND_CLOUDS2 ); cloudsLayers->SetLayerSpeed( 0, 4, 4 ); // 1:7 movement speed cloudsLayers->SetLayerSpeed( 1, 1, 1 ); // 1:1 movement speed cloudsLayers->SetSpeed( 0, -250 ); } // Load fonts using Factory pattern { FontFactory::Instance()->Get( RESOURCE::FONT_INFO )->Load( "Assets/Fonts/failed.ttf", 24 ); FontFactory::Instance()->Get( RESOURCE::FONT_SCORE )->Load( "Assets/Fonts/digital-7_mono.ttf", 32 ); FontFactory::Instance()->Get( RESOURCE::FONT_SMALL )->Load( "Assets/Fonts/ProFontWindows.ttf", 9 ); FontFactory::Instance()->Get( RESOURCE::FONT_MENU )->Load( "Assets/Fonts/impact.ttf", 35 ); } // Load sounds using Factory pattern { SoundFactory::Instance()->Get( RESOURCE::SOUND_INTRO_AMIGADISKFX )->Load( "Assets/Sounds/intro_disksound.ogg" ); SoundFactory::Instance()->Get( RESOURCE::SOUND_PLAYER_FIRE )->Load( "Assets/Sounds/laser.ogg" ); SoundFactory::Instance()->Get( RESOURCE::SOUND_ENEMY_FIRE )->Load( "Assets/Sounds/machinegun2.ogg" ); SoundFactory::Instance()->Get( RESOURCE::SOUND_EXPLOSION1 )->Load( "Assets/Sounds/explosion_1.ogg" ); SoundFactory::Instance()->Get( RESOURCE::SOUND_EXPLOSION2 )->Load( "Assets/Sounds/explosion_2.ogg" ); } // Preload musics using Factory pattern { MusicFactory::Instance()->Get( RESOURCE::MUSIC_SPLASH )->Load( "Assets/Musics/cdk_-_Song_Of_Peace.ogg" ); MusicFactory::Instance()->Get( RESOURCE::MUSIC_INGAME )->Load( "Assets/Musics/Astroboy_Sprung-160.ogg" ); MusicFactory::Instance()->Get( RESOURCE::MUSIC_GAMEOVER )->Load( "Assets/Musics/Syenta_-_Cytheres_Reves_(Cytheres_Dreams)_2.ogg" ); } // Create texts using Factory pattern { auto& fontSmall = FontFactory::Instance()->Get( RESOURCE::FONT_SMALL ); auto& fontInfo = FontFactory::Instance()->Get( RESOURCE::FONT_INFO ); auto& fontMenu = FontFactory::Instance()->Get( RESOURCE::FONT_MENU ); TextFactory::Instance()->Get( RESOURCE::TEXT_BETA_BUILD_NOTE )->Create( fontSmall, "Space Attackers : Beta build, not for distribution! // Programming by Mika Luoma-aho <*****@*****.**>", 80, 128, 75, 64 ); TextFactory::Instance()->Get( RESOURCE::TEXT_STARTGAME )->Create( fontInfo, "< Press space to start a new game or ESC to quit >" ); TextFactory::Instance()->Get( RESOURCE::TEXT_SPACE_TO_CONTINUE )->Create( fontInfo, "< Press space to continue >" ); TextFactory::Instance()->Get( RESOURCE::TEXT_ENTER_TO_CONTINUE )->Create( fontInfo, "< Press enter to continue >" ); TextFactory::Instance()->Get( RESOURCE::TEXT_HIGHSCORES )->Create( fontMenu, "< HI-SCORES >" ); TextFactory::Instance()->Get( RESOURCE::TEXT_LEVEL_STARTING )->Create( fontMenu, "Get ready for" ); TextFactory::Instance()->Get( RESOURCE::TEXT_GAMEOVER_SCORE )->Create( fontMenu, "SCORE" ); TextFactory::Instance()->Get( RESOURCE::TEXT_GAMEOVER_ENTERYOURNAME )->Create( fontMenu, "ENTER YOUR NAME", 255, 220, 100 ); TextFactory::Instance()->Get( RESOURCE::TEXT_GAMEOVER_NAME )->Create( fontMenu, "" ); TextFactory::Instance()->Get( RESOURCE::TEXT_GAMEOVER_NAME_PROMPT )->Create( fontMenu, "_" /*«*/ ); } // Create particle effects { // Create Explosion { auto& velocityOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_EXPLOSION_VELOCITY ); velocityOverTime->AddValue( 0.0f, 20.0f ); velocityOverTime->AddValue( 0.7f, 10.5f, Math::Interpolation::easeOutCirc<float,float> ); auto& alphaOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_EXPLOSION_ALPHA ); alphaOverTime->AddValue( 0.0f, 1.0f ); alphaOverTime->AddValue( 1.0f, 0.0f, Math::Interpolation::linearTween<float,float> ); auto& sizeOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_EXPLOSION_SIZE ); sizeOverTime->AddValue( 0.0f, 3.0f ); sizeOverTime->AddValue( 1.0f, 1.0f, Math::Interpolation::linearTween<float,float> ); // Flame colors // http://kuler.adobe.com/#themeID/177302 // Math::Colors::HSV h1, h2, h3, h4, h5; h1 = { 41, 0.84f, 1.0f }; h2 = { 43, 0.70f, 1.0f }; h3 = { 63, 0.37f, 0.97f }; h4 = { 30, 0.85f, 1.0f }; h5 = { 17, 0.95f, 0.73f }; auto& colorOverTime = SDLColorInterpolationSetFactory::Instance()->Get( RESOURCE::IS_EXPLOSION_COLOR ); colorOverTime->AddValue( 0.0f, Math::Colors::HSV2SDLColor(h1) ); colorOverTime->AddValue( 0.2f, Math::Colors::HSV2SDLColor(h2) ); colorOverTime->AddValue( 0.4f, Math::Colors::HSV2SDLColor(h3) ); colorOverTime->AddValue( 0.6f, Math::Colors::HSV2SDLColor(h4) ); colorOverTime->AddValue( 0.8f, Math::Colors::HSV2SDLColor(h5) ); // Set parameters auto& psExplosion = ExplosionSystemFactory::Instance()->Get( RESOURCE::PS_EXPLOSION ); psExplosion->Initialize( 500 ); psExplosion->SetVelocityOverTime( RESOURCE::IS_EXPLOSION_VELOCITY ); psExplosion->SetAlphaOverTime( RESOURCE::IS_EXPLOSION_ALPHA ); psExplosion->SetColorOverTime( RESOURCE::IS_EXPLOSION_COLOR ); psExplosion->SetSizeOverTime( RESOURCE::IS_EXPLOSION_SIZE ); psExplosion->SetPrimitiveType( 2 ); psExplosion->SetTrails( false ); } // Create Smoke { auto& velocityOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_SMOKE_VELOCITY ); velocityOverTime->AddValue( 0.0f, 15.0f ); velocityOverTime->AddValue( 1.0f, 0.0f, Math::Interpolation::linearTween<float,float> ); auto& alphaOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_SMOKE_ALPHA ); alphaOverTime->AddValue( 0.0f, 0.5f ); alphaOverTime->AddValue( 1.0f, 0.1f, Math::Interpolation::easeInCirc<float,float> ); auto& sizeOverTime = InterpolationSetFactory::Instance()->Get( RESOURCE::IS_SMOKE_SIZE ); sizeOverTime->AddValue( 0.0f, 1.0f ); sizeOverTime->AddValue( 1.0f, 3.0f, Math::Interpolation::linearTween<float,float> ); // Smoke colors // http://kuler.adobe.com/#themeID/1262268 // Math::Colors::HSV h1, h2, h3, h4; h1 = { 226, 0.25f, 0.16f }; h2 = { 235, 0.07f, 0.34f }; h3 = { 40, 0.08f, 0.41f }; h4 = { 43, 0.15f, 0.53f }; auto& colorOverTime = SDLColorInterpolationSetFactory::Instance()->Get( RESOURCE::IS_SMOKE_COLOR ); colorOverTime->AddValue( 0.0f, Math::Colors::HSV2SDLColor(h1) ); colorOverTime->AddValue( 0.3f, Math::Colors::HSV2SDLColor(h2) ); colorOverTime->AddValue( 0.6f, Math::Colors::HSV2SDLColor(h3) ); colorOverTime->AddValue( 1.0f, Math::Colors::HSV2SDLColor(h4) ); // Set parameters auto& psSmoke = SmokeSystemFactory::Instance()->Get( RESOURCE::PS_SMOKE ); psSmoke->Initialize( 300 ); psSmoke->SetVelocityOverTime( RESOURCE::IS_SMOKE_VELOCITY ); psSmoke->SetAlphaOverTime( RESOURCE::IS_SMOKE_ALPHA ); psSmoke->SetColorOverTime( RESOURCE::IS_SMOKE_COLOR ); psSmoke->SetSizeOverTime( RESOURCE::IS_SMOKE_SIZE ); psSmoke->SetPrimitiveType( 2 ); psSmoke->SetTrails( false ); } } // Create explosion thread to be used in highscore screen { ExplosionThreadFactory::Instance()->Get( RESOURCE::THREAD_EXPLOSION )->SetExplosion( RESOURCE::PS_EXPLOSION ); } // Create note { auto& noteText = TextFactory::Instance()->Get( RESOURCE::TEXT_BETA_BUILD_NOTE ); m_noteImgWidth = noteText->GetSurface()->w; } // Load scenes into memory and set first scene as running { unique_ptr<CScene> SplashScene = unique_ptr<SceneSplashScreen>(new SceneSplashScreen); unique_ptr<CScene> Level1Scene = unique_ptr<SceneLevel>(new SceneLevel); unique_ptr<CScene> GameOverScene = unique_ptr<SceneGameOver>(new SceneGameOver); unique_ptr<CScene> HighscoresScene = unique_ptr<SceneHighscores>(new SceneHighscores); unique_ptr<CScene> HelpScene = unique_ptr<SceneHelp>(new SceneHelp); // Add scenes (order is also the render order!) AddScene( SCENE_0_Intro, SplashScene ); AddScene( SCENE_1_Game, Level1Scene ); AddScene( SCENE_2_GameOver, GameOverScene ); AddScene( SCENE_3_Highscores, HighscoresScene ); AddScene( SCENE_4_Help, HelpScene ); } // Load and run the first scene //#ifdef DEBUG_SCENE1 //LoadAndRunScene( SCENE_1_Game ); //SetState( (int)STATE::GAME ); auto& properties = CSingleton<CProperties>::Instance(); #ifdef DEBUG_GAMEOVER properties->Property( "Player", "Name" ) = (std::string)""; properties->Property( "Player", "Score" ) = static_cast<int>(1234567); properties->Property( "Player", "Fired" ) = static_cast<int>(1000); properties->Property( "Player", "Kills" ) = static_cast<int>(20); properties->Property( "Player", "Accuracy" ) = static_cast<int>(98); properties->Property( "Player", "Level" ) = static_cast<int>(27); LoadAndRunScene( SCENE_2_GameOver ); SetState( (int)STATE::GAME_OVER ); #else properties->Property( "Player", "Name" ) = (std::string)""; LoadAndRunScene( SCENE_0_Intro ); SetState( (int)STATE::SPLASH_SCREEN ); #endif // Default to 60fps SDL_initFramerate( &m_fpsManager ); SDL_setFramerate( &m_fpsManager, 60 ); // Initialize state handlers InitHandlers(); }
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; }
bool Initialize (int w, int h, bool fullScreen, System::State* StartingState, int FrameRate, std::string windowTitle, std::string iconFile){ // Initiate SDL if ( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0 ){ fprintf( stderr, "Video query failed: %s\n", SDL_GetError()); exit(1); return false; } atexit(SDL_Quit); // At quit, destroy SDL int flags; if(fullScreen) flags = SDL_HWSURFACE | SDL_HWACCEL | SDL_DOUBLEBUF | SDL_FULLSCREEN; else flags = SDL_HWSURFACE | SDL_HWACCEL | SDL_DOUBLEBUF; Screen = SDL_SetVideoMode(w, h, 32, flags); if(Screen == NULL){ fprintf( stderr, "Video mode set failed: %s\nWidth(%d), Height(%d)\n", SDL_GetError(), w, h); exit(1); return false; } /* // Set up the window and video mode if(fullScreen) Screen = SDL_SetVideoMode(w,h,32,SDL_OPENGL|SDL_HWSURFACE|SDL_NOFRAME|SDL_DOUBLEBUF|SDL_FULLSCREEN|SDL_OPENGL); else Screen = SDL_SetVideoMode(w,h,32,SDL_OPENGL|SDL_HWSURFACE|SDL_NOFRAME|SDL_DOUBLEBUF|SDL_OPENGL); if ( Screen == NULL ) return false; */ // Set the caption of the window SDL_WM_SetCaption(windowTitle.c_str(), NULL); // Set the window icon if(iconFile != ""){ SDL_Surface* WindowIcon = IMG_Load(iconFile.c_str()); if(WindowIcon){ SDL_SetColorKey(WindowIcon, SDL_SRCCOLORKEY, SDL_MapRGB(WindowIcon->format, 255, 0, 255)); SDL_WM_SetIcon(WindowIcon, NULL); SDL_FreeSurface(WindowIcon); } else { fprintf( stderr, "Error loading window icon file \"%s\"\n", iconFile.c_str()); } } // Input System::Input::Initialize(); // Math System::Math::Initialize(); // Text if(System::Text::Initialize() == false){ fprintf( stderr, "Error initializing text\n"); } // Framerate SDL_initFramerate(&fpsm); if(FrameRate < 0) FrameRate = 1; SDL_setFramerate(&fpsm, FrameRate); // Default values Width = w; Height = h; Title = windowTitle; SetState(StartingState); Going = true; return true; }
void fps_sethz(int hz) { fpsHz = hz; SDL_setFramerate(&fpsManager, hz); }
/*! * \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; }
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); } }