//Frees media and shuts down SDL void Application::close() { //Destroy window SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gWindow = NULL; gRenderer = NULL; //Free the loaded sounds Mix_FreeChunk(beep); beep = NULL; Mix_FreeChunk(go); go = NULL; Mix_FreeMusic(menuBackgroundSound); menuBackgroundSound = NULL; freeButtonPointers(); freeTextPointers(); //Quit SDL subsystems IMG_Quit(); SDL_Quit(); Mix_Quit(); }
// Called before quitting bool j1Audio::CleanUp() { if(!active) return true; LOG("Freeing sound FX, closing Mixer and Audio subsystem \n"); if(music != NULL) { Mix_FreeMusic(music); } list<Mix_Chunk*>::iterator item; for(item = fx.begin(); item != fx.end(); ++item) Mix_FreeChunk(*item); fx.clear(); Mix_CloseAudio(); Mix_Quit(); SDL_QuitSubSystem(SDL_INIT_AUDIO); return true; }
// Called before quitting bool j1Audio::CleanUp() { if(!active) return true; LOG("Freeing sound FX, closing Mixer and Audio subsystem"); if(music != NULL) { Mix_FreeMusic(music); } p2List_item<Mix_Chunk*>* item; for(item = fx.start; item != NULL; item = item->next) Mix_FreeChunk(item->data); fx.clear(); Mix_CloseAudio(); Mix_Quit(); SDL_QuitSubSystem(SDL_INIT_AUDIO); return true; }
/* -------------------------------------------------------------------------------- CLOSE -------------------------------------------------------------------------------- * Close everything, quit SDL */ void close( void ) { /* Free graphical textures */ delete gAButton; gAButton = NULL; /* Free text textures */ delete gIntroText; delete gIntroTextShadow; delete gCreditsText1; delete gCreditsText2; delete gCreditsText3; gIntroText = NULL; gIntroTextShadow = NULL; gCreditsText1 = NULL; gCreditsText2 = NULL; gCreditsText3 = NULL; /* Free the objects */ kill_objects(); /* Write the high score to disk and delete the files object */ gFiles->write_score(); delete gFiles; gFiles = NULL; /* Free the sound effects */ if( Mix_Playing( -1 ) > 0 ) Mix_HaltChannel( -1 ); Mix_FreeChunk( gFaceKilled ); Mix_FreeChunk( gFlap ); Mix_FreeChunk( gScore ); gFaceKilled = NULL; gFlap = NULL; gScore = NULL; /* Free the music */ if( Mix_PlayingMusic() > 0 ) Mix_HaltMusic(); Mix_FreeMusic( gMusic ); gMusic = NULL; /* Free the fonts */ TTF_CloseFont( gFont ); TTF_CloseFont( gFontSmall ); TTF_CloseFont( gFontTiny ); gFont = NULL; gFontSmall = NULL; gFontTiny = NULL; /* Kill the renderer and window */ SDL_DestroyRenderer( gRenderer ); SDL_DestroyWindow( gWindow ); gRenderer = NULL; gWindow = NULL; /* Kill the joystick */ SDL_JoystickClose( gPad1 ); gPad1 = NULL; /* Quit SDL and its subsystems */ TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); }
// main for normal game usage int main(int argc, char *argv[]) { #if defined(__MINGW32__) // load mingw crash handler. Won't fail if dll is not present. // may load libray from current dir, it may not same as program dir LoadLibrary("exchndl.dll"); #endif selfName = argv[0]; parseOptions(argc, argv); if (settings.options.printHelp) { printHelp(); _exit(0); } else if (settings.options.printVersion) { printVersion(); _exit(0); } #ifdef ANDROID mkdir_r(getSdStoragePath().c_str()); #endif PhysFs::init(argv[0]); XML::initXML(); #if SDL_IMAGE_VERSION_ATLEAST(1, 2, 11) IMG_Init(IMG_INIT_PNG); #endif #if SDL_MIXER_VERSION_ATLEAST(1, 2, 11) Mix_Init(MIX_INIT_OGG); #endif #ifdef WIN32 SetCurrentDirectory(PhysFs::getBaseDir()); #endif setPriority(true); client = new Client; int ret = 0; if (!settings.options.testMode) { client->gameInit(); ret = client->gameExec(); } else { client->testsInit(); ret = client->testsExec(); } delete2(client); #if SDL_MIXER_VERSION_ATLEAST(1, 2, 11) Mix_Quit(); #endif #if SDL_IMAGE_VERSION_ATLEAST(1, 2, 11) IMG_Quit(); #endif #ifdef DUMP_LEAKED_RESOURCES reportRWops(); #endif #ifdef DEBUG_PHYSFS reportPhysfsLeaks(); #endif return ret; }
static mrb_value mrb_sdl2_mixer_quit(mrb_state *mrb, mrb_value self) { Mix_Quit(); return mrb_nil_value(); }
int main(int argc, char *argv[]) { atexit(SDL_Quit); srand(time(NULL)); if(SDL_Init(SDL_INIT_EVERYTHING) == 1){ std::cerr << "Error initializing SDL\n"; return -1; } SDL_WM_SetCaption("SDL Puyo Puyo", NULL); SDL_Surface *screen = SDL_SetVideoMode(SCR_W, SCR_H, SCR_BPP, SDL_SWSURFACE ); if(screen == NULL){ std::cerr << "Error in SetVideoMode\n"; return -1; } SDL_Event event; Uint32 last_tick = SDL_GetTicks(); /* Holy f*****g sound initialization batman. */ int mix_flags = MIX_INIT_MP3; int init_mix = Mix_Init(mix_flags); int audio_rate = 22050; Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */ int audio_channels = 2; int audio_buffers = 4096; if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) { std::cerr << "Unable to open audio\n"; mixer_on = false; } else { if(mix_flags & init_mix != mix_flags){ std::cerr << "Failed to init mp3 support, bg music disabled :(\n"; std::cerr << "mixer error: " << Mix_GetError() << std::endl; mixer_on = false; } else{ mixer_on = true; } } /* Init TTF */ if(TTF_Init() == -1){ std::cerr << "Could not initialize TTF subsystem :(\n"; font_on = false; } else { font_on = true; } GameState *gs = InitNewGame(); if(gs == NULL){ std::cerr << "Error initializing new game.\n"; return -1; } gameloop: while(gs->playing) { while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) return 0; if(event.type == SDL_KEYDOWN) { if(event.key.keysym.sym == SDLK_ESCAPE) return 0; HandleInput(gs, event); } } if(SDL_GetTicks() - last_tick > 1000/60){ UpdateTick(gs); last_tick = SDL_GetTicks(); } RenderTick(screen, gs); SDL_Flip(screen); } RenderTick(screen, gs); SDL_Delay(5000); CleanGameState(gs); gs = InitNewGame(); goto gameloop; if(screen) SDL_FreeSurface(screen); TTF_Quit(); Mix_Quit(); return 0; }
GameEngine::~GameEngine() { Mix_Quit(); IMG_Quit(); SDL_Quit(); }
//---------------------------------------------------------------------------------------------------------------------- int main() { // initialize SDL's video and audio subsystem if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)<0) { // or die on error SDLErrorExit("Unable to initialize SDL"); } /// The following section is modified from :- /// Lazy Foo' Productions (2014). SDL Sound Effects and Music [online]. [Accessed 2014]. /// Available from: <http://lazyfoo.net/tutorials/SDL/21_sound_effects_and_music/index.php>. // initialize SDL_mixer if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048 )<0) { printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); // or die on error SDLErrorExit("Unable to initialize SDL_mixer"); } /// end of Citation // now get the size of the display and create a window we need to init the video SDL_Rect rect; SDL_GetDisplayBounds(0,&rect); // now create our window to be most of the screen's size SDL_Window *window=SDL_CreateWindow("SDLNGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, rect.w/1.2, rect.h/1.2, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE ); // check to see if that worked or exit if (!window) { SDLErrorExit("Unable to create window"); } // create our opengl context and attach it to our window SDL_GLContext glContext=createOpenGLContext(window); if(!glContext) { SDLErrorExit("Problem creating OpenGL context"); } // make this our current GL context (we can have more than one window but in this case not) SDL_GL_MakeCurrent(window, glContext); // this makes our buffer swap syncronized with the monitor's vertical refresh SDL_GL_SetSwapInterval(1); // we need to initialise the NGL lib which will load all of the OpenGL functions, this must // be done once we have a valid GL context but before we call any GL commands, else // everything will crash ngl::NGLInit::instance(); // now clear the screen and swap whilst NGL inits (which may take time) glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapWindow(window); // flag to indicate if we need to exit bool quit=false; // sdl event processing data structure SDL_Event event; // bind the mouse' movement to the game, force the game to interpret the mouse' movements // on mac the mouse is fully locked whilst on linux the mouse is free but movements // are still tied to the window SDL_SetRelativeMouseMode(SDL_TRUE); // now we create an instance of a game class, this will init NGL and setup basic // opengl stuff ext, and when this falls out of scope the dtor will be called and cleanup // our gl stuff Game _game; // resize the ngl to set the screen size and camera parameters _game.resize(rect.w,rect.h); // central opengl loop while(!quit) { while(SDL_PollEvent(&event)) { switch(event.type) { // this is the window x being clicked. case SDL_QUIT : quit = true; break; // process the mouse data by passing it to ngl class case SDL_MOUSEMOTION : _game.mouseMoveEvent(event.motion); break; // if the window is re-sized pass it to the ngl class to change gl viewport // note this is slow as the context is re-create by SDL each time // this shouldn't happen as the mouse is bound to the screen an the screen // shouldn't be resized case SDL_WINDOWEVENT : int w,h; // get the new window size SDL_GetWindowSize(window,&w,&h); _game.resize(w,h); break; // now we look for a keydown event case SDL_KEYDOWN: { switch( event.key.keysym.sym ) { // if it's the escape key quit case SDLK_ESCAPE : quit = true; break; // key for time-slowing case SDLK_s : _game.keyPressEvent(event.key.keysym); break; // key for attacking case SDLK_a : _game.keyPressEvent(event.key.keysym); break; // key for breaking tethers early case SDLK_f : _game.keyPressEvent(event.key.keysym); break; // key for creating a tether case SDLK_SPACE : _game.keyPressEvent(event.key.keysym); break; // key for beginning the game case SDLK_e : _game.keyPressEvent(event.key.keysym); break; default : break; } // end of key process } // end of keydown default : break; } // end of event switch } // end of poll events // all the updates _game.update(); // now we draw the game _game.draw(); // swap the buffers SDL_GL_SwapWindow(window); } // now tidy up and exit SDL and the SDL_mixer Mix_Quit(); SDL_Quit(); }
ZAudioManager::~ZAudioManager () { cout << "[INF] [CLOSING AUDIO]" << endl; Mix_Quit(); }
int main(int argc, char* argv[]) { //initialize and loading variables char *bgmm[11] = { "l1.mp3", "l2.mp3", "l3.mp3", "l4.mp3", "l5.mp3", "l6.mp3", "l7.mp3", "l8.mp3", "l9.mp3", "l10.mp3", "l11.mp3" }; char *bv[11] = { "can we live together.wav", "can't you just relax do you even remember.wav", "chage is good for you.wav", "grace and integrity are what define us.wav", "how do thrive and grow under pressure.wav", "i don't want you to keep going.wav", "i know sometimes it feels like you have no controle", "i want to help you but you need to let me.wav", "is there another way.wav", "once an action is done it cannot be undone.wav", "push any further and yu will break.wav" }; SDL_Color color; const point center = { 220.0, 350.0 }; int currenttick, score=0; short circleradius = 44,musicselect=0; boolean mainmenu = yes; double theta = 0.0,speed=0.09; //Uint8 alpha; SDL_Renderer *rendertarget = NULL; SDL_Rect rectangle1 = { 320, 0, 100, 20 }, rectangle2 = { 230, rectangle1.y-80, 100, 20 }; SDL_Rect littlerectangle1 = { 310, rectangle1.y - 165, 50, 20 }; SDL_Rect cube1 = { 300, rectangle1.y - 270, 40, 40 }, cube2 = { 310, cube1.y - 90, 40, 40 }, cube3 = { 305, cube2.y - 90, 40, 40 }; SDL_Rect redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 }; SDL_Rect blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 }; const Uint8 *keystate; SDL_Window *window = NULL; SDL_Texture *redball = NULL, *blueball = NULL, *box = NULL; //gametexture // Initialize SDL2 SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2560); Mix_Music *bgm = Mix_LoadMUS("l1.mp3"); Mix_Chunk *voice = Mix_LoadWAV("trust your instincts.wav"), *hitsound = Mix_LoadWAV("Samples/3816133910831170.wav"); Mix_PlayChannel(2,voice,0); Mix_PlayMusic(bgm, -1); // Create an application window with the following settings: window = SDL_CreateWindow("An SDL2 window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 440, 480, SDL_WINDOW_SHOWN ); rendertarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); box = loadTexture("box.png", rendertarget); redball = loadTexture("redball.png", rendertarget); blueball = loadTexture("bleuball.png", rendertarget); //SDL_SetRenderDrawColor(rendertarget, 0x23, 0x23, 0x23, 0x23); SDL_SetRenderDrawColor(rendertarget, 0x99, 0x99, 0xF8, 0x23); color.r = 0x99; color.g = 0x99; color.b = 0xF8; color.a = 0x23; option select = exitgame; //gameloop boolean gamerunning = yes, programruns = yes; SDL_Event e; while (programruns == yes){ while (gamerunning == yes && select == startgame){ while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) gamerunning = no; }; srand(time(0)); currenttick = SDL_GetTicks(); if (e.key.keysym.scancode == SDL_SCANCODE_ESCAPE){ SDL_RenderClear(rendertarget); SDL_RenderPresent(rendertarget); //SDL_RenderCopy(rendertarget, gameTitle, NULL, &Gametitleposition); //update(gameTitle, Gametitleposition); SDL_RenderPresent(rendertarget); mainmenu = yes; break; //code to stop game and get back to menu } keystate = SDL_GetKeyboardState(NULL); if (keystate[SDL_SCANCODE_LEFT]) { theta += speed; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_RIGHT]){ theta -= speed; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_UP]){ circleradius += 2; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_DOWN]){ circleradius -= 2; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } movebox(rectangle1); srand(currenttick); movebox(rectangle2); srand(currenttick); movebox(littlerectangle1); srand(currenttick); movebox(cube1); srand(currenttick); movebox(cube2); srand(currenttick); movebox(cube3); SDL_RenderClear(rendertarget); update(redball, redballposition); update(blueball, blueballposition); update(box, rectangle1); update(box, rectangle2); update(box, littlerectangle1); update(box, cube1); update(box, cube2); update(box, cube3); SDL_RenderPresent(rendertarget); if (aBallhit(rectangle1) || aBallhit(rectangle2) || aBallhit(littlerectangle1) || aBallhit(cube1) || aBallhit(cube2) || aBallhit(cube3)){ Mix_PlayChannel(1, hitsound, 0); //reinitialize Game //rectangle1 = { 220, 0, 100, 20 }; rectangle1.x= 220; rectangle1.y= 0; rectangle1.w= 100; rectangle1.h= 20; //rectangle2 = { 130, rectangle1.y - 80, 100, 20 }; rectangle2.x= 130; rectangle2.y= rectangle1.y - 80; rectangle2.w= 100; rectangle2.h= 20; //littlerectangle1 = { 210, rectangle1.y - 165, 50, 20 }; littlerectangle1.x= 210; littlerectangle1.y= rectangle1.y - 165; littlerectangle1.w= 50; littlerectangle1.h= 20; //cube1 = { 200, rectangle1.y - 270, 40, 40 }; cube1.x= 200; cube1.y= rectangle1.y - 270; cube1.w= 40; cube1.h= 40; //cube2 = { 210, cube1.y - 90, 40, 40 }; cube2.x= 210; cube2.y= cube1.y - 90; cube2.w= 40; cube2.h= 40; //cube3 = { 205, cube2.y - 90, 40, 40 }; cube3.x= 205; cube3.y= cube2.y - 90; cube3.w= 40; cube3.h= 40; //redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 }; redballposition.x= center.x + circleradius*sin(theta); redballposition.y= center.y + circleradius*cos(theta); redballposition.w= 25; redballposition.h= 25; //blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 }; blueballposition.x= center.x - circleradius*sin(theta); blueballposition.y= center.y - circleradius*cos(theta); blueballposition.w= 25; blueballposition.h= 25; circleradius = 44; gamerunning = yes; mainmenu = yes; printf("\n your score is: %d", score); score = 0; Mix_HaltMusic(); Mix_FreeMusic(bgm); if (musicselect == 10) musicselect = 0; else musicselect += 1; bgm = Mix_LoadMUS(bgmm[musicselect]); voice = Mix_LoadWAV(bv[musicselect]); Mix_PlayMusic(bgm,-1); Mix_PlayChannel(2, voice, 0); srand(currenttick); color.b = rand(); srand(currenttick*100); color.a = rand(); srand(currenttick*1000); color.g = rand(); srand(currenttick*10000); color.r = rand(); SDL_SetRenderDrawColor(rendertarget, color.r, color.g, color.b, color.a); break; //insert code when collision happens } if (musicselect == 6 ){ color.b = rand(); srand(currenttick * 100); color.r = rand(); srand(currenttick * 1000); color.g = rand(); SDL_SetTextureColorMod(box, color.r, color.g, color.b); } else if (musicselect == 7){ //SDL_SetTextureColorMod(box, 0, 0, 0); } //if (rectangle1.y >= 200){ // alpha = 20; // SDL_SetTextureAlphaMod(box,alpha); //} //else // alpha=100; if( (notout(redballposition,blueballposition))&&(rectangle1.y == 400 || rectangle2.y == 400 || littlerectangle1.y == 400 || cube1.y == 400 || cube2.y == 400 || cube3.y == 400)){ score += 1; // printf("\n score = %d", score); } if (SDL_GetTicks() - currenttick<1000.0 / 60)/*60 FPS*/ { SDL_Delay(1000 / 60 - SDL_GetTicks() + currenttick); } } runmenu(&programruns,&mainmenu,rendertarget,&select); } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); IMG_Quit(); Mix_Quit(); SDL_DestroyTexture(redball); SDL_DestroyTexture(blueball); SDL_DestroyTexture(box); SDL_DestroyRenderer(rendertarget); redball = NULL; blueball = NULL; box = NULL; rendertarget = NULL; return 0; }
bool nnb::SDL_MixerSubsystem::quit() { Mix_Quit(); return nnb::SUCCESS; }
int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_11.html if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "main: SDL_mixer Error: %s\n", Mix_GetError() ); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } /** closing **/ // Deallocate textures texture_free(&g_current_texture); // joystick // SDL_JoystickClose(g_gamepad); // g_gamepad = 0; // sfx Mix_FreeChunk( g_scratch ); Mix_FreeChunk( g_hig ); Mix_FreeChunk( g_med ); Mix_FreeChunk( g_low ); g_scratch = 0; g_hig = 0; g_med = 0; g_low = 0; // music Mix_FreeMusic( g_music ); g_music = 0; SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
int main(int argc, char **argv) { int audio_rate,audio_channels; Uint16 audio_format; Uint32 t; Mix_Music *music; int volume=SDL_MIX_MAXVOLUME; /* initialize SDL for audio and video */ if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO)<0) cleanExit("SDL_Init"); atexit(SDL_Quit); int initted=Mix_Init(0); printf("Before Mix_Init SDL_mixer supported: "); print_init_flags(initted); initted=Mix_Init(~0); printf("After Mix_Init SDL_mixer supported: "); print_init_flags(initted); Mix_Quit(); if(argc<2 || argc>4) { fprintf(stderr,"Usage: %s filename [depth] [any 3rd argument...]\n" " filename is any music file supported by your SDL_mixer library\n" " depth is screen depth, default is 8bits\n" " if there is a third argument given, we go fullscreen for maximum fun!\n", *argv); return 1; } /* open a screen for the wav output */ if(!(s=SDL_SetVideoMode(W,H,(argc>2?atoi(argv[2]):8),(argc>3?SDL_FULLSCREEN:0)|SDL_HWSURFACE|SDL_DOUBLEBUF))) cleanExit("SDL_SetVideoMode"); SDL_WM_SetCaption("sdlwav - SDL_mixer demo","sdlwav"); /* hide the annoying mouse pointer */ SDL_ShowCursor(SDL_DISABLE); /* get the colors we use */ white=SDL_MapRGB(s->format,0xff,0xff,0xff); black=SDL_MapRGB(s->format,0,0,0); /* initialize sdl mixer, open up the audio device */ if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,BUFFER)<0) cleanExit("Mix_OpenAudio"); /* we play no samples, so deallocate the default 8 channels... */ Mix_AllocateChannels(0); /* print out some info on the formats this run of SDL_mixer supports */ { int i,n=Mix_GetNumChunkDecoders(); printf("There are %d available chunk(sample) decoders:\n",n); for(i=0; i<n; ++i) printf(" %s\n", Mix_GetChunkDecoder(i)); n = Mix_GetNumMusicDecoders(); printf("There are %d available music decoders:\n",n); for(i=0; i<n; ++i) printf(" %s\n", Mix_GetMusicDecoder(i)); } /* print out some info on the audio device and stream */ Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); bits=audio_format&0xFF; sample_size=bits/8+audio_channels; rate=audio_rate; printf("Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate, bits, audio_channels>1?"stereo":"mono", BUFFER ); /* calculate some parameters for the wav display */ dy=s->h/2.0/(float)(0x1<<bits); /* load the song */ if(!(music=Mix_LoadMUS(argv[1]))) cleanExit("Mix_LoadMUS(\"%s\")",argv[1]); { Mix_MusicType type=Mix_GetMusicType(music); printf("Music type: %s\n", type==MUS_NONE?"MUS_NONE": type==MUS_CMD?"MUS_CMD": type==MUS_WAV?"MUS_WAV": /*type==MUS_MOD_MODPLUG?"MUS_MOD_MODPLUG":*/ type==MUS_MOD?"MUS_MOD": type==MUS_MID?"MUS_MID": type==MUS_OGG?"MUS_OGG": type==MUS_MP3?"MUS_MP3": type==MUS_MP3_MAD?"MUS_MP3_MAD": type==MUS_FLAC?"MUS_FLAC": "Unknown"); } /* set the post mix processor up */ Mix_SetPostMix(postmix,argv[1]); SDL_FillRect(s,NULL,black); SDL_Flip(s); SDL_FillRect(s,NULL,black); SDL_Flip(s); /* start playing and displaying the wav */ /* wait for escape key of the quit event to finish */ t=SDL_GetTicks(); if(Mix_PlayMusic(music, 1)==-1) cleanExit("Mix_PlayMusic(0x%p,1)",music); Mix_VolumeMusic(volume); while((Mix_PlayingMusic() || Mix_PausedMusic()) && !done) { SDL_Event e; while(SDL_PollEvent(&e)) { switch(e.type) { case SDL_KEYDOWN: switch(e.key.keysym.sym) { case SDLK_ESCAPE: done=1; break; case SDLK_LEFT: if(e.key.keysym.mod&KMOD_SHIFT) { Mix_RewindMusic(); position=0; } else { int pos=position/audio_rate-1; if(pos<0) pos=0; Mix_SetMusicPosition(pos); position=pos*audio_rate; } break; case SDLK_RIGHT: switch(Mix_GetMusicType(NULL)) { case MUS_MP3: Mix_SetMusicPosition(+5); position+=5*audio_rate; break; case MUS_OGG: case MUS_FLAC: case MUS_MP3_MAD: /*case MUS_MOD_MODPLUG:*/ Mix_SetMusicPosition(position/audio_rate+1); position+=audio_rate; break; default: printf("cannot fast-forward this type of music\n"); break; } break; case SDLK_UP: volume=(volume+1)<<1; if(volume>SDL_MIX_MAXVOLUME) volume=SDL_MIX_MAXVOLUME; Mix_VolumeMusic(volume); break; case SDLK_DOWN: volume>>=1; Mix_VolumeMusic(volume); break; case SDLK_SPACE: if(Mix_PausedMusic()) Mix_ResumeMusic(); else Mix_PauseMusic(); break; default: break; } break; case SDL_QUIT: done=1; break; default: break; } } /* the postmix processor tells us when there's new data to draw */ if(need_refresh) refresh(); SDL_Delay(0); } t=SDL_GetTicks()-t; /* free & close */ Mix_FreeMusic(music); Mix_CloseAudio(); SDL_Quit(); /* show a silly statistic */ printf("fps=%.2f\n",((float)flips)/(t/1000.0)); return(0); }
int main(int argc, char *args[]) { SDL_Init(SDL_INIT_EVERYTHING); //Init SDL Mix_Init(MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG); //Init SDL Mixer Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096); //Open audiostream int temp = officalDelay; //The delay it will play int holder = -1; //Hold which sound it played before int counter = 0; //How many soundclips have been played //Create window and check if it's loaded SDL_Window *win = SDL_CreateWindow("Omvand Synestesi", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_SHOWN); if (win == NULL) { std::cout << "Couldn't create window, unkown error." << std::endl; } //Make a renderer SDL_Renderer *renderer = SDL_CreateRenderer(win, 0, SDL_RENDERER_ACCELERATED); //Create a texture, load it. Check if it's loaded SDL_Texture *texture = load_texture("get.bmp", renderer); if(texture == NULL) { std::cout << "Couldn't load picture, check so it's named get.bmp" << std::endl; } //Loads a surface, this is the picture it will take and make sound of. SDL_Surface *image = SDL_LoadBMP("get.bmp"); if (image == NULL) { std::cout << "Couldn't load picture until surface. Check the name so it is get.bmp" << std::endl; } //Load soundfiles Mix_Music *sound[15]; for (int i = 1; i < 16; i++) { std::string path = "sound/get" + convertInt(i) + ".wav"; sound[i] = Mix_LoadMUS(path.c_str()); std::cout << "Loaded soundfile: " << path << std::endl; if (sound[i] == NULL) { std::cout << "Couldn't load soundfile " << path << ". Check so the name is get" << i << ".wav" << std::endl; } } //Loop through the whole picture for (int y = 0; y < size_h; y++) { for (int x = 0; x < size_w; x++) { Uint32 pix = getPixel(image, x, y); SDL_RenderClear(renderer); //Clear the screen SDL_RenderCopy(renderer, texture, NULL, NULL); //Print out the picture SDL_RenderPresent(renderer); //Actually render the picture int npix = pix % 16 + 1; //Get's a value from the pixel and makes it so it's just 1 to 16 std::cout << "!-- " << pix << " --! " << npix << " | " << counter << "/1296" << std::endl; //Prints out some stuff so you can see for debugging mostly //If the same value is again, make a longer delay before playing next song, and if not, go back to standard delay if (npix == holder) { temp = temp + 120; } else { temp = officalDelay; } //Play right soundfile from value of pixel for (int i = 1; i < 15; i++) { int newi = i + 1; if (i == npix) { Mix_PlayMusic(sound[newi], 0); SDL_Delay(temp); holder = i; } } //If value is 16, don't play a sound and make a 3sec long delay. if (npix == 16) { std::cout << std::endl << "-----" << std::endl << std::endl; SDL_Delay(3000); } counter++; } } SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_DestroyWindow(win); for (int i = 1; i < 16; i++) { Mix_FreeMusic(sound[i]); } Mix_Quit(); SDL_Quit(); return 0; }
int main(int argc, char** argv) { srand(1707801); Server* server = NULL; Client* lan = NULL; if (argc > 1) { try { if (argv[1][0] == 's') { server = new Server(); server->correr(); } } catch ( ConnectionProblem &e ) { return -1; } } if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { return -1; } else if (server == NULL) { TTF_Init(); //Inicializo el Mixer: if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0){ printf ("Error al inicializar SDL_mixer. Error: %s\n", Mix_GetError()); SDL_Quit(); IMG_Quit(); TTF_Quit(); return -1; } EstadoFinVentana estado = OK; VentanaEspera *ventanaEspera = NULL; ObjetivoEscenario modoDeJuego = MODO_DEFAULT; if (argc > 1) { try { if (argv[1][0] == 'c') { //ventanaEspera = new VentanaEspera(std::pair<int,int>(640,800)); // hardcode sabroso //estado = ventanaEspera->run(); lan = new Client(); // Se conecta. modoDeJuego = Proxy::clienteEsperarComienzoYModoDeJuego(lan); // Espera comienzo de juego. } } catch ( ConnectionProblem &e ) { return -1; } } Controller *controller = new Controller(lan, modoDeJuego); // Carga el juego (modelo) delete ventanaEspera; if (estado == OK){ if (estado == OK){ VentanaJuego *ventanaJuego = new VentanaJuego(controller); // Carga y mantiene la vista. estado = ventanaJuego->run(); delete ventanaJuego; } // Meter una ventana de resultado de la partida (GANADO - PERDIDO) } delete controller; Mix_Quit(); TTF_Quit(); IMG_Quit(); SDL_Quit(); } delete server; delete lan; return 0; }
int main(int argc, char *argv[]) { Matrix projectionMatrix; Matrix modelMatrix; Matrix viewMatrix; init(); ShaderProgram program(RESOURCE_FOLDER "vertex_textured.glsl", RESOURCE_FOLDER "fragment_textured.glsl"); glUseProgram(program.programID); float lastFrameTicks = 0.0f; // float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; // float texCoords[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; // float vertices[] = {-0.09, -0.09, 0.09, -0.09, 0.09, 0.09, -0.09, -0.09, 0.09, 0.09, -0.09, 0.09}; Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 4096 ); SDL_Event event; bool done = false; /* Sprites courtesy of http://gooperblooper22.deviantart.com/art/Space-Invaders-Sprite-Sheet-135338373 */ GLuint spriteSheetTexture = LoadTexture("space_invaders_sprite_sheet_by_gooperblooper22.png"); GLuint white = LoadTexture("white.png"); GLuint textTexture = LoadTexture("font1.png"); Mix_Music *bgm = Mix_LoadMUS("bgm.mp3"); Mix_Chunk *missile = Mix_LoadWAV("157439__nengisuls__misslie-1.wav"); bool pressed = false; int score = 0; int currentIndex = 0; int state; const int numFrames = 2; float animation[] = {(74.0f/617.0f),(107.0f/617.0f)}; float animationElapsed = 0.0f; float framesPerSecond = 0.0004f; std::vector<SheetSprite> aliens; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } program.setProjectionMatrix(projectionMatrix); program.setModelMatrix(modelMatrix); program.setViewMatrix(viewMatrix); float ticks = (float)SDL_GetTicks()/1000; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; animationElapsed += 1/elapsed; if(animationElapsed > 1.0/framesPerSecond) { currentIndex++; animationElapsed = 0.0; if(currentIndex > numFrames-1) { currentIndex = 0; } } glClear(GL_COLOR_BUFFER_BIT); score = ticks; SheetSprite menu(spriteSheetTexture, 160.0f/617.0f, 1.0f/2035.0f, 250.0f/617.0f, 171.0f/2035.0f, 0.5); Entity text; Player cannon(spriteSheetTexture, 277.0f/617.0f, 227.0f/2035.0f, 26.0f/617.0f, 17.0f/2035.0f, 0.05); SheetSprite alien(spriteSheetTexture, animation[currentIndex], (225.0f/2035.0f), 22.0f/617.0f, 16.0f/2035.0f, 0.05); const Uint8 *keys = SDL_GetKeyboardState(NULL); switch (state) { case STATE_MAIN_MENU: menu.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, true); menu.draw(program); if (!Mix_PlayingMusic()) { Mix_PlayMusic(bgm, -1); } if (keys[SDL_SCANCODE_RETURN]) { state++; } break; case STATE_GAME_LEVEL: text.DrawText(program, textTexture, "Score:" + std::to_string(score), 0.075, 0, -0.23, 0.9); cannon.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, white, alien); cannon.draw(program); alien.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, false); alien.draw(program); if (keys[SDL_SCANCODE_SPACE]) { Mix_PlayChannel( -1, missile, 0); Mix_VolumeChunk(missile, 15); } if (keys[SDL_SCANCODE_ESCAPE] && (state == 1)) { pressed = true; state++; } break; case STATE_PAUSE: if (Mix_PlayingMusic()) { Mix_PausedMusic(); } text.DrawText(program, textTexture, "Paused", 0.1, 0, -0.23, 0); if (keys[SDL_SCANCODE_ESCAPE] && pressed) { pressed = false; state--; } break; } SDL_GL_SwapWindow(displayWindow); } Mix_FreeMusic(bgm); Mix_FreeChunk(missile); Mix_Quit(); cleanup(); return 0; }
int main(int argc, char **argv) { const SDL_Color whitecol = {255,255,255,255}; srand(time(NULL)); // a quick 'n dirty way of initializing random seed // load scores #ifdef WINDOWS FILE *scorefil = fopen("score.dat","rb"); #else char filen[256]; snprintf(filen,256,"%s/.nasuscore",getenv("HOME")); FILE *scorefil = fopen(filen,"rb"); chdir("/usr/share/games/nasu"); #endif if ( scorefil == NULL ) score = 0; else { fread((void *)&score,sizeof(unsigned long int),1,scorefil); fclose(scorefil); } // parameter parsing // -fullscreen specifies that the game is fullscreen // -res WxH specifies resolution // -noscale does not scale virtual screen float ScreenMult = 2; int resx = 640, resy = 480; bool bIsFullscreen = false; bool bNoScale = false; bool bNoSound = false; for ( int i=1; i<argc; i++ ) { if ( strcasecmp(argv[i],"-fullscreen") == 0 ) bIsFullscreen = true; else if ( strcasecmp(argv[i],"-res") == 0 ) { // expect next parameter to be a resolution in format WxH if ( argc <= i ) { fprintf(stderr,"Expected video resolution for parameter -res in format WxH\n"); return 1; } else { sscanf(argv[i+1],"%dx%d",&resx,&resy); if ( resx < 320 ) resx = 320; if ( resy < 240 ) resy = 240; } } else if ( strcasecmp(argv[i],"-noscale") == 0 ) bNoScale = true; else if ( strcasecmp(argv[i],"-nosound") == 0 ) bNoSound = true; } // calculate screen mult based on specified resolution int sm[2]; sm[0] = floor(resx/320); sm[1] = floor(resy/240); ScreenMult = (sm[0]>sm[1])?sm[1]:sm[0]; if ( bNoScale ) ScreenMult = 1; atexit(savescore); if ( SDL_Init(SDL_INIT_EVERYTHING) == -1 ) { fprintf(stderr,"couldn't initialize SDL (%s)\n", SDL_GetError()); return 1; } Uint8 blankcursor = 0; Uint8 blankcursormask = 0; SDL_Cursor *blankcur = SDL_CreateCursor(&blankcursor,&blankcursormask,1,1,0,0); SDL_SetCursor(blankcur); // load program icon SDL_Surface *icone = IMG_Load("nasuicon.png"); if ( icone != NULL ) SDL_WM_SetIcon(icone,NULL); SDL_WM_SetCaption("NASU","NASU"); // I don't really know why the two parameters but oh well~ SDL_Surface *mainscreen = NULL; // Create window. If SDL can't set a fullscreen mode it'll fall back to windowed if ( bIsFullscreen && (SDL_VideoModeOK(resx,resy,32,SDL_SWSURFACE|SDL_FULLSCREEN) != 0) ) mainscreen = SDL_SetVideoMode(resx,resy,32,SDL_SWSURFACE|SDL_FULLSCREEN); else { bIsFullscreen = false; mainscreen = SDL_SetVideoMode(resx,resy,32,SDL_SWSURFACE); } if ( mainscreen == NULL ) { fprintf(stderr,"couldn't create window (%s)\n", SDL_GetError()); fflush(stderr); return 1; } SDL_Rect scrrect; SDL_GetClipRect(mainscreen,&scrrect); // real screen that will be resized to fit SDL_Surface *_realscreen = SDL_CreateRGBSurface(SDL_SWSURFACE,320,240,mainscreen->format->BitsPerPixel,mainscreen->format->Rmask,mainscreen->format->Gmask,mainscreen->format->Bmask,mainscreen->format->Amask); SDL_Surface *realscreen = SDL_DisplayFormatAlpha(_realscreen); SDL_FreeSurface(_realscreen); SDL_Rect rscrrect; SDL_GetClipRect(realscreen,&rscrrect); // load up player SDL_Surface *_playersprites = IMG_Load("player.png"); SDL_Surface *playersprites = SDL_DisplayFormatAlpha(_playersprites); SDL_FreeSurface(_playersprites); NASU_Player player; player.graph = playersprites; player.res.w = 24; player.res.h = 24; player.pivot.x = 12.f; player.pivot.y = 12.f; player.pos.x = 160.f; player.pos.y = 149.f; player.vel.x = 0.f; player.vel.y = 0.f; player.tbox.x1 = -12.f; player.tbox.y1 = -4.f; player.tbox.x2 = 12.f; player.tbox.y2 = 12.f; player.dim.w = 24.f; player.dim.h = 24.f; player.scale = 1; player.bIsJumping = false; player.animframe = 0; player.bLeft = false; // load up main frame SDL_Surface *_mainframeimg = IMG_Load("mainscreen.png"); SDL_Surface *mainframeimg = SDL_DisplayFormatAlpha(_mainframeimg); SDL_FreeSurface(_mainframeimg); NASU_Actor mainframe; mainframe.graph = mainframeimg; mainframe.res.w = 320; mainframe.res.h = 240; mainframe.pivot.x = 0.f; mainframe.pivot.y = 0.f; mainframe.pos.x = 0.f; mainframe.pos.y = 0.f; mainframe.vel.x = 0.f; mainframe.vel.y = 0.f; mainframe.tbox.x1 = 0.f; mainframe.tbox.y1 = 0.f; mainframe.tbox.x2 = 320.f; mainframe.tbox.y2 = 240.f; mainframe.dim.w = 320.f; mainframe.dim.h = 240.f; mainframe.scale = 1; mainframe.animframe = 0; // load up game screen SDL_Surface *_gamescreenimg = IMG_Load("gamescreen.png"); SDL_Surface *gamescreenimg = SDL_DisplayFormatAlpha(_gamescreenimg); SDL_FreeSurface(_gamescreenimg); NASU_Actor gamescreen; gamescreen.graph = gamescreenimg; gamescreen.res.w = 184; gamescreen.res.h = 130; gamescreen.pivot.x = 0.f; gamescreen.pivot.y = 0.f; gamescreen.pos.x = 68.f; gamescreen.pos.y = 47.f; gamescreen.vel.x = 0.f; gamescreen.vel.y = 0.f; gamescreen.tbox.x1 = 0.f; gamescreen.tbox.y1 = 0.f; gamescreen.tbox.x2 = 320.f; gamescreen.tbox.y2 = 240.f; gamescreen.dim.w = 184.f; gamescreen.dim.h = 130.f; gamescreen.scale = 1; gamescreen.animframe = 0; // load up eggplants SDL_Surface *_nasuimg = IMG_Load("nasu.png"); SDL_Surface *nasuimg = SDL_DisplayFormatAlpha(_nasuimg); SDL_FreeSurface(_nasuimg); NASU_Actor nasu; nasu.graph = nasuimg; nasu.res.w = 8; nasu.res.h = 8; nasu.pivot.x = 4.f; nasu.pivot.y = 4.f; nasu.pos.x = 4.f; nasu.pos.y = 4.f; nasu.vel.x = 0.f; nasu.vel.y = 0.f; nasu.tbox.x1 = -3.f; nasu.tbox.y1 = -3.f; nasu.tbox.x2 = 3.f; nasu.tbox.y2 = 3.f; nasu.dim.w = 8.f; nasu.dim.h = 8.f; nasu.scale = 1; nasu.animframe = 0; NASU_Actor nasu_b; nasu_b.graph = nasuimg; nasu_b.res.w = 8; nasu_b.res.h = 8; nasu_b.pivot.x = 4.f; nasu_b.pivot.y = 4.f; nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; nasu_b.vel.x = 0.f; nasu_b.vel.y = 0.f; nasu_b.tbox.x1 = -3.f; nasu_b.tbox.y1 = -3.f; nasu_b.tbox.x2 = 3.f; nasu_b.tbox.y2 = 3.f; nasu_b.dim.w = 8.f; nasu_b.dim.h = 8.f; nasu_b.scale = 1; nasu_b.animframe = 1; TTF_Init(); // load up score text TTF_Font *basefont = TTF_OpenFont("04B.TTF",8); NASU_ScrnText scoretxt; scoretxt.font = basefont; memset(&scoretxt.text,0,256); scoretxt.pos.x = 192.f; scoretxt.pos.y = 164.f; scoretxt.colr = whitecol; NASU_ScrnText scorenumtxt; scorenumtxt.font = basefont; memset(&scorenumtxt.text,0,256); scorenumtxt.pos.x = 240.f; scorenumtxt.pos.y = 164.f; scorenumtxt.colr = whitecol; NASU_ScrnText fpsnum; fpsnum.font = basefont; memset(&fpsnum.text,0,256); fpsnum.pos.x = 4.f; fpsnum.pos.y = 4.f; fpsnum.colr = whitecol; // load up the start/game over/paused text SDL_Surface *_textyimg = IMG_Load("texty.png"); SDL_Surface *textyimg = SDL_DisplayFormatAlpha(_textyimg); SDL_FreeSurface(_textyimg); NASU_Actor texty; texty.graph = textyimg; texty.res.w = 72; texty.res.h = 8; texty.pivot.x = 36.f; texty.pivot.y = 4.f; texty.pos.x = 160.f; texty.pos.y = 120.f; texty.vel.x = 0.f; texty.vel.y = 0.f; texty.tbox.x1 = 0.f; texty.tbox.y1 = 0.f; texty.tbox.x2 = 0.f; texty.tbox.y2 = 0.f; texty.dim.w = 72.f; texty.dim.h = 8.f; texty.scale = 1; texty.animframe = 2; // load up score sprites SDL_Surface *_pointsimg = IMG_Load("scores.png"); SDL_Surface *pointsimg = SDL_DisplayFormatAlpha(_pointsimg); SDL_FreeSurface(_pointsimg); NASU_Actor points1; points1.graph = pointsimg; points1.res.w = 40; points1.res.h = 12; points1.pivot.x = 20.f; points1.pivot.y = 6.f; points1.pos.x = 16.f; points1.pos.y = 16.f; points1.vel.x = 0.f; points1.vel.y = 0.f; points1.tbox.x1 = 0.f; points1.tbox.y1 = 0.f; points1.tbox.x2 = 0.f; points1.tbox.y2 = 0.f; points1.dim.w = 40.f; points1.dim.h = 12.f; points1.scale = 1; points1.animframe = 0; NASU_Actor points2; points2.graph = pointsimg; points2.res.w = 40; points2.res.h = 12; points2.pivot.x = 20.f; points2.pivot.y = 6.f; points2.pos.x = 16.f; points2.pos.y = 32.f; points2.vel.x = 0.f; points2.vel.y = 0.f; points2.tbox.x1 = 0.f; points2.tbox.y1 = 0.f; points2.tbox.x2 = 0.f; points2.tbox.y2 = 0.f; points2.dim.w = 40.f; points2.dim.h = 12.f; points2.scale = 1; points2.animframe = 1; NASU_Actor points3; points3.graph = pointsimg; points3.res.w = 40; points3.res.h = 12; points3.pivot.x = 20.f; points3.pivot.y = 6.f; points3.pos.x = 16.f; points3.pos.y = 48.f; points3.vel.x = 0.f; points3.vel.y = 0.f; points3.tbox.x1 = 0.f; points3.tbox.y1 = 0.f; points3.tbox.x2 = 0.f; points3.tbox.y2 = 0.f; points3.dim.w = 40.f; points3.dim.h = 12.f; points3.scale = 1; points3.animframe = 2; // load up sounds // TODO Pitch modification // step sounds: 1.1, 0.9, 1.5 // nasu get sounds: 1.0, 1.1, 1.5 Mix_Chunk *stepsnd[3]; Mix_Chunk *getsnd[3]; Mix_Chunk *losesnd; Mix_Music *titlemus; Mix_Music *gamemus; Mix_Music *losemus; if ( !bNoSound ) { Mix_Init(MIX_INIT_OGG); Mix_OpenAudio(44100,AUDIO_S16SYS,2,1024); Mix_AllocateChannels(8); stepsnd[0] = Mix_LoadWAV("nasustep1.ogg"); Mix_VolumeChunk(stepsnd[0], MIX_MAX_VOLUME*0.75f); stepsnd[1] = Mix_LoadWAV("nasustep2.ogg"); Mix_VolumeChunk(stepsnd[1], MIX_MAX_VOLUME*0.75f); stepsnd[2] = Mix_LoadWAV("nasustep3.ogg"); Mix_VolumeChunk(stepsnd[2], MIX_MAX_VOLUME*0.75f); getsnd[0] = Mix_LoadWAV("nasuget1.ogg"); Mix_VolumeChunk(getsnd[0], MIX_MAX_VOLUME); getsnd[1] = Mix_LoadWAV("nasuget2.ogg"); Mix_VolumeChunk(getsnd[1], MIX_MAX_VOLUME); getsnd[2] = Mix_LoadWAV("nasuget3.ogg"); Mix_VolumeChunk(getsnd[2], MIX_MAX_VOLUME); losesnd = Mix_LoadWAV("nasulose.ogg"); Mix_VolumeChunk(losesnd, MIX_MAX_VOLUME); titlemus = Mix_LoadMUS("nasutitle.ogg"); gamemus = Mix_LoadMUS("nasugame.ogg"); losemus = Mix_LoadMUS("nasuover.ogg"); Mix_VolumeMusic(MIX_MAX_VOLUME*0.35f); } // game variables float pts1time = 0.f, pts2time = 0.f, pts3time = 0.f; unsigned long int cscore = 0; unsigned short int GameState = 0; float TimeUntilNextNasu = 2.0f, TimeUntilNextNasuB = 25.f; bool bLostGame = false; float blink = 0.f; unsigned short int blinkcounter = 0; bool bDerp = false; NASU_Vect Nasupos, Nasubpos; float deltatime = 0.f, calfps = 0.f; bool bShowFPS = false; float difficulty = 0.f; uint32_t lastframe = 0; char scrname[256]; // start main loop! if ( !bNoSound ) Mix_PlayMusic(titlemus,-1); bool bQueriedQuit = false; lastframe = SDL_GetTicks(); while (!bQueriedQuit) { // input event polling SDL_Event Event; while ( SDL_PollEvent(&Event) ) { switch (Event.type) { case SDL_QUIT: bQueriedQuit = true; break; case SDL_KEYDOWN: switch (Event.key.keysym.sym) { case SDLK_ESCAPE: bQueriedQuit = true; break; case SDLK_F12: #ifdef WINDOWS SDL_SaveBMP(realscreen,"screenshot.bmp"); #else snprintf(scrname,256,"%s/nasu_screenshot.bmp",getenv("HOME")); SDL_SaveBMP(realscreen,scrname); #endif break; case SDLK_F10: bIsFullscreen = !bIsFullscreen; SDL_FreeSurface(mainscreen); mainscreen = NULL; if ( bIsFullscreen && (SDL_VideoModeOK(resx,resy,32,SDL_SWSURFACE|SDL_FULLSCREEN) != 0) ) mainscreen = SDL_SetVideoMode(resx,resy,32,SDL_SWSURFACE|SDL_FULLSCREEN); else { bIsFullscreen = false; mainscreen = SDL_SetVideoMode(resx,resy,32,SDL_SWSURFACE); } break; case SDLK_F11: bShowFPS = !bShowFPS; break; case SDLK_RETURN: if (GameState == 0) { if ( !bNoSound ) Mix_HaltMusic(); GameState = 3; texty.animframe = 3; } break; case SDLK_p: if ( (GameState == 1) && !bLostGame ) { GameState = 4; if ( !bNoSound ) Mix_PauseMusic(); texty.animframe = 4; } else if ( GameState == 4 ) { GameState = 1; if ( !bNoSound ) Mix_ResumeMusic(); texty.animframe = 3; } break; case SDLK_LEFT: case SDLK_a: if ( !bLostGame && (GameState == 1) && (player.pos.x+player.tbox.x1 > gamescreen.pos.x) ) { player.bLeft = true; player.vel.x = -60.f; } break; case SDLK_RIGHT: case SDLK_d: if ( !bLostGame && (GameState == 1) && (player.pos.x+player.tbox.x2 < gamescreen.pos.x+gamescreen.dim.w) ) { player.bLeft = false; player.vel.x = 60.f; } break; case SDLK_UP: case SDLK_w: case SDLK_z: case SDLK_LSHIFT: if ( !bLostGame && (GameState == 1) && !player.bIsJumping ) { player.bIsJumping = true; player.vel.y = -80.f; if ( !bNoSound ) Mix_PlayChannel(-1,stepsnd[2],0); } break; default: break; } break; case SDL_KEYUP: switch (Event.key.keysym.sym) { case SDLK_LEFT: case SDLK_a: if ( !bLostGame && (GameState == 1) ) player.vel.x = 0.f; break; case SDLK_RIGHT: case SDLK_d: if ( !bLostGame && (GameState == 1) ) player.vel.x = 0.f; break; default: break; } break; default: break; } } // clear screen SDL_FillRect(mainscreen,&scrrect,SDL_MapRGB(mainscreen->format,0,0,0)); SDL_FillRect(realscreen,&rscrrect,SDL_MapRGB(realscreen->format,0,0,0)); // process game logic switch (GameState) { case 0: // Title screen gamescreen.animframe = 2; RenderActor(realscreen,&gamescreen); snprintf(scorenumtxt.text,256,"%9u",score); scorenumtxt.pos.x = 320.f-(112.f+CalcTextW(&scorenumtxt)); scorenumtxt.pos.y = 144.f; scoretxt.pos.x = 112.f; scoretxt.pos.y = 144.f; snprintf(scoretxt.text,256,"Hi Score:"); RenderScrnText(realscreen,&scoretxt); RenderScrnText(realscreen,&scorenumtxt); break; case 2: // Lose screen gamescreen.animframe = 3; RenderActor(realscreen,&gamescreen); blink += deltatime; if ( blink >= 7.f ) { if ( !bNoSound ) Mix_PlayMusic(titlemus,-1); GameState = 0; } texty.animframe = 2; snprintf(scorenumtxt.text,256,"%9lu",cscore); scorenumtxt.pos.x = 320.f-(80.f+CalcTextW(&scorenumtxt)); scorenumtxt.pos.y = 164.f; scoretxt.pos.x = 168.f; scoretxt.pos.y = 164.f; snprintf(scoretxt.text,256,"Score:"); RenderScrnText(realscreen,&scoretxt); RenderScrnText(realscreen,&scorenumtxt); RenderActor(realscreen,&texty); break; case 3: // Game preparation gamescreen.animframe = 0; RenderActor(realscreen,&gamescreen); blink += deltatime; if ( blink > 0.25f ) { blinkcounter++; blink = 0.f; bDerp = !bDerp; if ( !bDerp ) texty.animframe = 3; else { if ( blinkcounter < 7 ) texty.animframe = 0; else texty.animframe = 1; } } if ( blinkcounter >= 8 ) { bDerp = false; blinkcounter = 0; GameState = 1; if ( !bNoSound ) Mix_PlayMusic(gamemus,-1); } difficulty = 0.f; cscore = 0; TimeUntilNextNasu = 2.0f; TimeUntilNextNasuB = 25.f; bLostGame = false; pts1time = 0.f; pts2time = 0.f; pts3time = 0.f; player.animframe = 0; player.bLeft = 0; player.bIsJumping = 0; player.pos.x = 160.f; player.pos.y = 149.f; nasu.pos.x = 4.f; nasu.pos.y = 4.f; nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; points1.pos.x = 16.f; points1.pos.y = 16.f; points2.pos.x = 16.f; points2.pos.y = 32.f; points3.pos.x = 16.f; points3.pos.y = 48.f; RenderPlayer(realscreen,&player); snprintf(scorenumtxt.text,256,"%9lu",cscore); scorenumtxt.pos.x = 320.f-(80.f+CalcTextW(&scorenumtxt)); scorenumtxt.pos.y = 164.f; scoretxt.pos.x = 168.f; scoretxt.pos.y = 164.f; snprintf(scoretxt.text,256,"Score:"); RenderScrnText(realscreen,&scoretxt); RenderScrnText(realscreen,&scorenumtxt); RenderActor(realscreen,&texty); break; case 4: // Paused RenderActor(realscreen,&gamescreen); RenderPlayer(realscreen,&player); RenderActor(realscreen,&nasu); RenderActor(realscreen,&nasu_b); snprintf(scorenumtxt.text,256,"%9lu",cscore); scorenumtxt.pos.x = 320.f-(80.f+CalcTextW(&scorenumtxt)); scorenumtxt.pos.y = 164.f; scoretxt.pos.x = 168.f; scoretxt.pos.y = 164.f; snprintf(scoretxt.text,256,"Score:"); RenderScrnText(realscreen,&scoretxt); RenderScrnText(realscreen,&scorenumtxt); RenderActor(realscreen,&texty); break; default: // Main game if ( bLostGame ) { player.vel.x = 0.f; player.vel.y = 0.f; blink += deltatime; if ( blink > 0.125f ) { blinkcounter++; blink = 0.f; bDerp = !bDerp; if ( bDerp ) gamescreen.animframe = 0; else gamescreen.animframe = 1; } if ( blinkcounter >= 12 ) { blinkcounter = 0; if ( !bNoSound ) Mix_PlayMusic(losemus,0); blink = 0.f; GameState = 2; bDerp = false; } } else { gamescreen.animframe = 0; blink += deltatime; if ( blink > 0.125f ) { bDerp = !bDerp; blink = 0.f; if ( !bNoSound ) { if ( player.vel.x != 0.f && !player.bIsJumping ) { if ( bDerp ) Mix_PlayChannel(-1,stepsnd[0],0); else Mix_PlayChannel(-1,stepsnd[1],0); } } } if ( TimeUntilNextNasu > 0.f ) { TimeUntilNextNasu -= deltatime; nasu.pos.x = 4.f; nasu.pos.y = 4.f; if ( TimeUntilNextNasu <= 0.f ) { TimeUntilNextNasu = 0.f; nasu.pos.x = (float)(rand()%160+80); nasu.pos.y = 0.f; nasu.vel.y = 50.f+difficulty*0.3f; } } else { MoveActor(&nasu,deltatime); Nasupos = nasu.pos; if ( CollidePlayer(&nasu,&player) && player.bIsJumping ) { if ( (rand()%(30+(int)(difficulty*0.35f))) == 0 ) { cscore += 1000; if ( cscore > score ) score = cscore; TimeUntilNextNasu = 2.f-(difficulty*0.03f); if ( TimeUntilNextNasu <= 0.1f ) TimeUntilNextNasu = 0.1f; nasu.pos.x = 4.f; nasu.pos.y = 4.f; if ( !bNoSound ) Mix_PlayChannel(-1,getsnd[2],0); pts3time += 0.75f; points3.pos = Nasupos; points3.vel.y = -50.f; difficulty += 7.5f; } else { cscore += 10; if ( cscore > score ) score = cscore; TimeUntilNextNasu = 2.f-(difficulty*0.03f); if ( TimeUntilNextNasu <= 0.1f ) TimeUntilNextNasu = 0.1f; nasu.pos.x = 4.f; nasu.pos.y = 4.f; if ( !bNoSound ) Mix_PlayChannel(-1,getsnd[0],0); pts1time += 0.75f; points1.pos = Nasupos; points1.vel.y = -50.f; difficulty += 1.f; } } else if ( nasu.pos.y >= 160.f ) { if ( !bNoSound ) { Mix_HaltMusic(); Mix_PlayChannel(-1,losesnd,0); } bLostGame = true; } } if ( TimeUntilNextNasuB > 0.f ) { TimeUntilNextNasuB -= deltatime; nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; if ( TimeUntilNextNasuB <= 0.f ) { TimeUntilNextNasuB = 0.f; int decideposb = rand()%2; switch (decideposb) { case 0: nasu_b.vel.x = (50.f+difficulty*0.15f); nasu_b.vel.y = 0.f; nasu_b.pos.x = 0.f; nasu_b.pos.y = 160.f; nasu_b.animframe = 2; break; default: nasu_b.vel.x = -(50.f+difficulty*0.15f); nasu_b.vel.y = 0.f; nasu_b.pos.x = 320.f; nasu_b.pos.y = 160.f; nasu_b.animframe = 1; break; } } } else { nasu_b.vel.y += (120.f+difficulty*0.75f)*deltatime; MoveActor(&nasu_b,deltatime); Nasubpos = nasu_b.pos; if ( CollidePlayer(&nasu_b,&player) && player.bIsJumping ) { cscore += 300; if ( cscore > score ) score = cscore; TimeUntilNextNasuB = 25.f+(difficulty*0.1f); nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; if ( !bNoSound ) Mix_PlayChannel(-1,getsnd[1],0); pts2time += 0.75f; points2.pos = Nasubpos; points2.vel.y = -50.f; difficulty += 2.5f; } if ( (nasu_b.vel.x > 0.f) && (nasu_b.pos.x > gamescreen.pos.x+gamescreen.dim.w) ) { TimeUntilNextNasuB = 25.f+(difficulty*0.15f); nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; } if ( (nasu_b.vel.x < 0.f) && (nasu_b.pos.x < gamescreen.pos.x) ) { TimeUntilNextNasuB = 25.f+(difficulty*0.15f); nasu_b.pos.x = 12.f; nasu_b.pos.y = 4.f; } if ( nasu_b.pos.y >= 160.f ) nasu_b.vel.y = -(80.f+difficulty*0.65f); } MovePlayer(&player,deltatime); if ( player.bIsJumping ) player.vel.y += 480.f*deltatime; if ( player.pos.y >= 149.f ) { player.pos.y = 149.f; player.bIsJumping = false; } if ( player.pos.x+player.tbox.x1 <= gamescreen.pos.x ) { player.pos.x = gamescreen.pos.x-player.tbox.x1; player.vel.x = 0; } if ( player.pos.x+player.tbox.x2 >= gamescreen.pos.x+gamescreen.dim.w ) { player.pos.x = (gamescreen.pos.x+gamescreen.dim.w)+player.tbox.x1; player.vel.x = 0; } if ( player.bIsJumping ) player.animframe = 3; else if ( player.vel.x != 0.f ) { if ( bDerp ) player.animframe = 2; else player.animframe = 1; } else player.animframe = 0; if ( pts1time > 0.f ) { pts1time -= deltatime; MoveActor(&points1,deltatime); if ( pts1time <= 0 ) { points1.vel.y = 0.f; points1.pos.x = 16.f; points1.pos.y = 16.f; } } if ( pts2time > 0.f ) { pts2time -= deltatime; MoveActor(&points2,deltatime); if ( pts2time <= 0 ) { points2.vel.y = 0.f; points2.pos.x = 16.f; points2.pos.y = 32.f; } } if ( pts3time > 0.f ) { pts3time -= deltatime; MoveActor(&points3,deltatime); if ( pts3time <= 0 ) { points3.vel.y = 0.f; points3.pos.x = 16.f; points3.pos.y = 48.f; } } } RenderActor(realscreen,&gamescreen); RenderPlayer(realscreen,&player); RenderActor(realscreen,&nasu); RenderActor(realscreen,&nasu_b); RenderActor(realscreen,&points1); RenderActor(realscreen,&points2); RenderActor(realscreen,&points3); snprintf(scorenumtxt.text,256,"%9lu",cscore); scorenumtxt.pos.x = 320.f-(80.f+CalcTextW(&scorenumtxt)); scorenumtxt.pos.y = 164.f; scoretxt.pos.x = 168.f; scoretxt.pos.y = 164.f; snprintf(scoretxt.text,256,"Score:"); RenderScrnText(realscreen,&scoretxt); RenderScrnText(realscreen,&scorenumtxt); break; } // render frame RenderActor(realscreen,&mainframe); // blit frame to screen SDL_Surface *resizedframe = Upscale(realscreen,ScreenMult); BlitAt(resizedframe,NULL,mainscreen,resx/2,resy/2,true,true); SDL_FreeSurface(resizedframe); // flip screen and calculate fps calfps = 1000.f/(SDL_GetTicks()-lastframe); deltatime = 1.f/calfps; snprintf(fpsnum.text,256,"%.2f",calfps); fpsnum.pos.x = resx-(4+CalcTextW(&fpsnum)); fpsnum.pos.y = 4.f; if ( bShowFPS ) RenderScrnText(mainscreen,&fpsnum); if (SDL_Flip(mainscreen) == -1) { fprintf(stderr,"error updating screen (%s)\n", SDL_GetError()); return 1; } lastframe = SDL_GetTicks(); } if ( !bNoSound ) { // Free audio Mix_FreeChunk(stepsnd[0]); Mix_FreeChunk(stepsnd[1]); Mix_FreeChunk(stepsnd[2]); Mix_FreeChunk(getsnd[0]); Mix_FreeChunk(getsnd[1]); Mix_FreeChunk(getsnd[2]); Mix_FreeChunk(losesnd); Mix_FreeMusic(titlemus); Mix_FreeMusic(gamemus); Mix_FreeMusic(losemus); Mix_AllocateChannels(0); Mix_CloseAudio(); } // Free surfaces SDL_FreeSurface(playersprites); SDL_FreeSurface(mainframeimg); SDL_FreeSurface(gamescreenimg); SDL_FreeSurface(nasuimg); SDL_FreeSurface(textyimg); // Free font TTF_CloseFont(basefont); // Quit stuff Mix_Quit(); TTF_Quit(); SDL_Quit(); return EXIT_SUCCESS; }
int main(int argc, char** argv){ //First we need to start up SDL, and make sure it went ok if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } //Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 800, 600, SDL_WINDOW_SHOWN); //Make sure creating our window went ok if (win == NULL){ std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return 1; } int mixRet = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY,MIX_DEFAULT_FORMAT,MIX_DEFAULT_CHANNELS,4096); if (mixRet != 0) return mixRet; mixRet = Mix_Init(MIX_INIT_MOD); if (mixRet != MIX_INIT_MOD) { cout << "SDLmixer Initiazation Error: " << Mix_GetError() << endl; return mixRet; } Mix_Music *altSamba = Mix_LoadMUS("Resources\\music\\alternativesamba.mod"); if (!altSamba) { cout << "alternativesamba.mod is not loaded. Exiting..." << Mix_GetError() << endl; return 1987; } Mix_PlayMusic(altSamba,-1); bool isRunning = true; SDL_Event gameLoop; SDL_Rect cameraRect; cameraRect.x = 0; cameraRect.y = 0; cameraRect.w = 800; cameraRect.h = 600; int xVel = 0; int yVel = 0; SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL){ std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; return 1; } SDL_TMXMap Map("Resources\\Test.tmx"); Map.Populate_Map(ren); while (isRunning) { while (SDL_PollEvent(&gameLoop)) { if (gameLoop.type == SDL_QUIT) isRunning = false; if ( gameLoop.key.state == SDL_PRESSED ) switch (gameLoop.key.keysym.sym){ case SDLK_UP: yVel = -16; break; case SDLK_DOWN: yVel = 16; break; case SDLK_LEFT: xVel = -16; break; case SDLK_RIGHT: xVel = 16; break; } } cameraRect.x +=xVel; if (cameraRect.x < 0) cameraRect.x = 0; else if (cameraRect.x > (Map.getWidth() * Map.getTileWidth()) - cameraRect.w) cameraRect.x = (Map.getWidth() * Map.getTileWidth()) - cameraRect.w; cameraRect.y +=yVel; if (cameraRect.y < 0) cameraRect.y = 0; else if (cameraRect.y >= (Map.getHeight() * Map.getTileHeight()) - cameraRect.h) cameraRect.y = (Map.getHeight() * Map.getTileHeight()) - cameraRect.h; SDL_SetRenderDrawColor(ren,255,0,255,SDL_ALPHA_OPAQUE); SDL_RenderClear(ren); Map.Render_Map(ren , &cameraRect); SDL_RenderPresent(ren); } SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); Mix_CloseAudio(); Mix_Quit(); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { // Something went very wrong in initialisation, all we can do is exit Utility::log(Utility::E,"Whoops! Something went very wrong, cannot initialise SDL"); return -1; } TTF_Init(); Mix_Init(MIX_INIT_OGG | MIX_INIT_MP3); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { Utility::log(Utility::E, "SDL_mixer init failed: " + std::string(Mix_GetError())); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); int winPosX = SDL_WINDOWPOS_CENTERED; int winPosY = SDL_WINDOWPOS_CENTERED; int winWidth = 640; int winHeight = 480; SDL_Window *window = SDL_CreateWindow("PGG Assignment 2 by Richard Hancock", // The first parameter is the window title winPosX, winPosY, winWidth, winHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); SDL_GLContext glcontext = SDL_GL_CreateContext(window); // Call our initialisation function to set up GLEW and print out some GL info to console if (!InitGL()) { return -1; } unsigned int lastTime = SDL_GetTicks(); glEnable(GL_DEPTH_TEST); Utility::randomInit(); //Create the Resource manager that loads resources ResourceManager* resourceManager = new ResourceManager(renderer); StateManager* manager = new StateManager(winWidth, winHeight); manager->addState(new PlayState(manager, resourceManager)); bool go = true; while (go) { unsigned int current = SDL_GetTicks(); float deltaTs = (float)(current - lastTime) / 1000.0f; // Now that we've done this we can use the current time as the next frame's previous time lastTime = current; //Event Handling go = manager->eventHandler(); //Update Utility::Timer::update(deltaTs); manager->update(deltaTs); // Draw our world // // Specify the colour to clear the framebuffer to glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This writes the above colour to the colour part of the framebuffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); manager->render(); // This tells the renderer to actually show its contents to the screen // We'll get into this sort of thing at a later date - or just look up 'double buffering' if you're impatient :P SDL_GL_SwapWindow(window); // Limiter in case we're running really quick if (deltaTs < (1.0f / 50.0f)) // not sure how accurate the SDL_Delay function is.. { SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTs)*1000.0f)); } } // If we get outside the main game loop, it means our user has requested we exit manager->popLastState(); delete manager; delete resourceManager; // Our cleanup phase, hopefully fairly self-explanatory ;) IMG_Quit(); Mix_CloseAudio(); Mix_Quit(); SDL_GL_DeleteContext(glcontext); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
static int lua_Mixer_Quit(State & state){ Mix_Quit(); return 0; }
TRBgm::~TRBgm() { Mix_CloseAudio(); Mix_Quit(); }
void Audio::quit(){ SDL_QuitSubSystem(SDL_INIT_AUDIO); Mix_Quit(); }
int init() { SDL_DisplayMode mode; // Initialize SDL itself printf("SDL_Init()\n"); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) { printf("SDL_Init error: %s\n", SDL_GetError()); return 0; } // Get the current display mode printf("SDL_GetCurrentDisplayMode()\n"); if(SDL_GetCurrentDisplayMode( 0, &mode ) != 0) { printf("SDL_GetCurrentDisplayMode error: %s\n", SDL_GetError()); SDL_Quit(); return 0; } rect_screen.w = mode.w; rect_screen.h = mode.h; //Create a new full-screen window printf("SDL_CreateWindow()\n"); window = SDL_CreateWindow("Multiplatform Base Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, rect_screen.w, rect_screen.h, SDL_WINDOW_SHOWN); if(!window) { printf("SDL_CreateWindow error: %s\n", SDL_GetError()); SDL_Quit(); return 0; } // Create a renderer printf("SDL_CreateRenderer()\n"); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!renderer) { printf("SDL_CreateRenderer error: %s\n", SDL_GetError()); SDL_DestroyWindow(window); SDL_Quit(); return 0; } // Init audio printf("Mix_Init()\n"); if(Mix_Init(MIX_INIT_OGG) != MIX_INIT_OGG) { printf("Mix_Init error: %s\n", Mix_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } // Open audio device printf("Mix_OpenAudio()\n"); if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) != 0) { printf("Mix_OpenAudio error: %s\n", Mix_GetError()); Mix_Quit(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } return 1; }
int main(int argc, char** argv){ //ShowWindow(GetForegroundWindow(), SW_HIDE); Display display(WIDTH, HEIGHT, "OpenGL"); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0){ std::cout << "ERROR: MixOpenAudio: " << Mix_GetError() << std::endl; } World world; Shader* shader = world.GetShader(); Brush br(24, 6, 24, &world, "./res/tex/pxl_cuboid.jpg"); br.Move(-2, 0, -2); Brush c1(1, 0.5, 3, &world, "./res/tex/pxl_cuboid.jpg"); c1.Move(2, 0, 2); Brush c2(1, 1.0, 3, &world, "./res/tex/pxl_cuboid.jpg"); c2.Move(3, 0, 2); Brush c3(1, 0.2, 1.5, &world, "./res/tex/pxl_cuboid.jpg"); c3.Move(6, 0.9, 2); Brush c4(1, 0.2, 1.5, &world, "./res/tex/pxl_cuboid.jpg"); c4.Move(6, 1.1, 3.5); Brush box(1, 1, 1, &world, "./res/tex/pxl_cuboid.jpg"); box.Move(6, 0.5, 6); Player player(shader); display.SetPlayer(player); Camera cammy; cammy.Init(glm::vec3(0, 0, 0), 70.0f, 1600 / 900, 0.01f, 1000.0f); Ambient amb1; shader->AddAmbient(&amb1); amb1.m_range = 3; amb1.m_intensity = 0.2; Ambient amb2; shader->AddAmbient(&amb2); amb2.SetPosition(1, 1, 1); Ambient amb3; shader->AddAmbient(&amb3); amb3.SetPosition(15, 1, 10); amb3.SetColor(0.2, 0.5, 0.7); Prop prop(world.GetMesh("./res/models/cucco.obj"), world.GetTexture("./res/models/cucco.jpg"), shader); world.AddProp(&prop); Prop stone(world.GetMesh("./res/models/salesman.obj"), world.GetTexture("./res/models/salesman.jpg"), shader); world.AddProp(&stone); stone.Scale(0.01); stone.Teleport(0, -10, 0); Sound laugh; laugh.Init("./res/sounds/sale_laugh.wav", 0.7); laugh.Load(); player.SetListener(Player_OnClick, OnClick); float count = 0.0f; while (!display.IsClosed()){ display.Clear(0.1f, 0.3f, 0.8f, 1.0f); world.Draw(&player.GetCamera()); player.DrawHUD(); display.Update(); laugh.Update(player.GetCamera().GetPos()); if (count >= 2 * PI){ count = 0; } count += 0.05f; c4.Rotate(0, 1, 0); if (glm::distance(prop.position, player.GetCamera().GetPos()) >= 2){ prop.velocity = (player.GetCamera().GetPos() - prop.position) / 64.0f; prop.velocity.y = 0; prop.SetRotate(0, PI / 2 - GetAngleRad(glm::vec2(0, 0), GetXZ(prop.velocity)), 0); } else{ prop.velocity *= 0; } prop.Rotate(0, sin(count) * PI / 360, 0); amb1.m_position = player.GetCamera().GetPos(); if (player.mouse_buttons[0]){//Left Clicking player.mouse_buttons[0] = false; stone.Teleport(world.GetAimPoint(&player)); stone.SetRotate(0, PI / 2 - GetAngleRad(glm::vec2(0, 0), GetXZ(player.GetCamera().GetPos() - stone.position)), 0); laugh.pos = stone.position; laugh.Emit(player.GetCamera().GetPos()); } world.Update(); player.Update(); world.IsCollide(&player); player.CommenceVelocity(); } Mix_CloseAudio(); Mix_Quit(); return 0; }
void CDAudio_Shutdown(void) { Mix_CloseAudio(); Mix_Quit(); }
int main(int argc, char **argv){ if(argc != 2){ printf("Usage: Chip8 <ROM Name>.ch8"); return 1; } // Setup Graphics if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { return 2; } SDL_Window* window = SDL_CreateWindow("Chipy8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL); SDL_GL_CreateContext(window); SDL_GL_SwapWindow(window); glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0); glClearColor(0, 0, 0, 1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glShadeModel(GL_FLAT); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_DITHER); glDisable(GL_BLEND); if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) { printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); return 1; } //Load sound effects soundBeep = Mix_LoadWAV( "Beep.wav" ); if(soundBeep == NULL ) { printf("Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError()); return 3; } // Init the CPU and load the game myChip8.Init(); if(!myChip8.LoadGame(argv[1])) return 1; bool quit = false; SDL_Event e; char fps = 60; int numOpCodes = 600; int numFrame = numOpCodes / fps; float interval = 1000; interval /= fps; unsigned int time2 = SDL_GetTicks(); //Emulation loop for(;;){ while(SDL_PollEvent(&e) != 0){ //User requests quit if(e.type == SDL_QUIT) { quit = true; } else if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP){ handleInput(&e); } } unsigned int current = SDL_GetTicks(); if((time2 + interval) < current){ myChip8.DecreaseTimers( ) ; if(myChip8.soundTimer == 1) Mix_PlayChannel( -1, soundBeep, 0 ); for (int i = 0 ; i < numFrame; i++) myChip8.EmualteCycle(); time2 = current; //If draw flag is set update screen if(myChip8.drawFlag){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRasterPos2i(-1, 1); glPixelZoom(1, -1); for(unsigned char y = 0; y < 32; y++){ unsigned short resY = y * 10; for(unsigned char x = 0; x < 64; x++){ unsigned short resX = x * 10; if(myChip8.gfx[(y * 64) + x] == 0){ for(unsigned char i = 0; i < 10; i++) for(unsigned char j = 0; j < 10; j++) screenData[resY + i][resX + j][0] = screenData[resY + i][resX + j][1] = screenData[resY + i][resX + j][2] = 0; // Disabled } else{ for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) screenData[resY + i][resX + j][0] = screenData[resY + i][resX + j][1] = screenData[resY + i][resX + j][2] = 255; // Enabled } } } glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, screenData); SDL_GL_SwapWindow(window); glFlush(); myChip8.drawFlag = false; } } if(quit){ SDL_DestroyWindow(window); Mix_FreeChunk(soundBeep); Mix_Quit(); SDL_Quit(); break; } } return 0; }
/* * R2D::Window#show */ static VALUE r2d_show(VALUE self) { // SDL Inits ///////////////////////////////////////////////////////////////// SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); TTF_Init(); // Create SDL window and configure /////////////////////////////////////////// char* win_title = RSTRING_PTR(rb_iv_get(self, "@title")); int win_width = NUM2INT(rb_iv_get(self, "@width")); int win_height = NUM2INT(rb_iv_get(self, "@height")); int fps_cap = NUM2INT(rb_iv_get(self, "@fps_cap")); bool vsync = RTEST(rb_iv_get(self, "@vsync")); SDL_Window *window = SDL_CreateWindow( win_title, // title SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, // window position win_width, win_height, // window size SDL_WINDOW_OPENGL // flags ); // Check if windows was successfully created if (!window) { printf("R2D Error: Could not create window: %s\n", SDL_GetError()); return 1; } // Enable VSync if (vsync) { if (!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1")) { printf("R2D Warning: VSync cannot be enabled!"); } } // OpenGL Inits ////////////////////////////////////////////////////////////// SDL_GLContext glcontext = SDL_GL_CreateContext(window); initGL(win_width, win_height); // Create SDL Renderer for Accelerated 2D //////////////////////////////////// SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); // Setting up variables int cursor_x, cursor_y; // Cursor positions const Uint8 *key_state; Uint32 frames = 0; // Total frames since start Uint32 start_ms = SDL_GetTicks(); // Elapsed time since start Uint32 begin_ms = start_ms; // TIme at beginning of loop Uint32 end_ms; // Time at end of loop Uint32 total_ms; // Total elapsed time Uint32 loop_ms; // Elapsed time of loop int delay_ms; // Amount of delay to achieve desired frame rate double fps; // The actual frame rate // Main Event Loop /////////////////////////////////////////////////////////// bool quit = false; while (!quit) { // Set FPS ///////////////////////////////////////////////////////////////// frames++; end_ms = SDL_GetTicks(); total_ms = end_ms - start_ms; fps = frames / (total_ms / 1000.0); loop_ms = end_ms - begin_ms; delay_ms = (1000 / fps_cap) - loop_ms; if (delay_ms < 0) { delay_ms = 0; } // loop_ms + delay_ms => should equal (1000 / fps_cap) // Store FPS info rb_iv_set(self, "@frames", INT2NUM(frames)); rb_iv_set(self, "@total_ms", INT2NUM(total_ms)); rb_iv_set(self, "@loop_ms", INT2NUM(loop_ms)); rb_iv_set(self, "@fps", DBL2NUM(fps)); SDL_Delay(delay_ms); begin_ms = SDL_GetTicks(); // Handle Input //////////////////////////////////////////////////////////// SDL_Event e; while (SDL_PollEvent(&e)) { switch(e.type) { case SDL_KEYDOWN: rb_funcall(self, rb_intern("on_key_callback"), 1, rb_str_new2(SDL_GetScancodeName(e.key.keysym.scancode)) ); break; case SDL_QUIT: quit = true; break; } } int num_keys; key_state = SDL_GetKeyboardState(&num_keys); for (int i = 0; i < num_keys; i++) { if (key_state[i] == 1) { rb_funcall(self, rb_intern("keys_down_callback"), 1, rb_str_new2(SDL_GetScancodeName(i)) ); } } // Store the cursor position SDL_GetMouseState(&cursor_x, &cursor_y); rb_iv_set(self, "@cursor_x", INT2NUM(cursor_x)); rb_iv_set(self, "@cursor_y", INT2NUM(cursor_y)); // Update Application State //////////////////////////////////////////////// // Call update proc, `window.update` rb_funcall(self, rb_intern("update_callback"), 0); // Draw Objects //////////////////////////////////////////////////////////// glClear(GL_COLOR_BUFFER_BIT); // Read window objects VALUE objects = rb_iv_get(self, "@objects"); int num_objects = NUM2INT(rb_funcall(objects, rb_intern("count"), 0)); // Switch on each object type for (int i = 0; i < num_objects; ++i) { VALUE el = rb_ary_entry(objects, i); int type_id = NUM2INT(rb_iv_get(el, "@type_id")); // Switch on the object's type_id switch(type_id) { case TRIANGLE: { VALUE c1 = rb_iv_get(el, "@c1"); VALUE c2 = rb_iv_get(el, "@c2"); VALUE c3 = rb_iv_get(el, "@c3"); draw_triangle( NUM2DBL(rb_iv_get(el, "@x1")), NUM2DBL(rb_iv_get(el, "@y1")), NUM2DBL(rb_iv_get(c1, "@r")), NUM2DBL(rb_iv_get(c1, "@g")), NUM2DBL(rb_iv_get(c1, "@b")), NUM2DBL(rb_iv_get(c1, "@a")), NUM2DBL(rb_iv_get(el, "@x2")), NUM2DBL(rb_iv_get(el, "@y2")), NUM2DBL(rb_iv_get(c2, "@r")), NUM2DBL(rb_iv_get(c2, "@g")), NUM2DBL(rb_iv_get(c2, "@b")), NUM2DBL(rb_iv_get(c2, "@a")), NUM2DBL(rb_iv_get(el, "@x3")), NUM2DBL(rb_iv_get(el, "@y3")), NUM2DBL(rb_iv_get(c3, "@r")), NUM2DBL(rb_iv_get(c3, "@g")), NUM2DBL(rb_iv_get(c3, "@b")), NUM2DBL(rb_iv_get(c3, "@a")) ); } break; case QUAD: { VALUE c1 = rb_iv_get(el, "@c1"); VALUE c2 = rb_iv_get(el, "@c2"); VALUE c3 = rb_iv_get(el, "@c3"); VALUE c4 = rb_iv_get(el, "@c4"); draw_triangle( NUM2DBL(rb_iv_get(el, "@x1")), NUM2DBL(rb_iv_get(el, "@y1")), NUM2DBL(rb_iv_get(c1, "@r")), NUM2DBL(rb_iv_get(c1, "@g")), NUM2DBL(rb_iv_get(c1, "@b")), NUM2DBL(rb_iv_get(c1, "@a")), NUM2DBL(rb_iv_get(el, "@x2")), NUM2DBL(rb_iv_get(el, "@y2")), NUM2DBL(rb_iv_get(c2, "@r")), NUM2DBL(rb_iv_get(c2, "@g")), NUM2DBL(rb_iv_get(c2, "@b")), NUM2DBL(rb_iv_get(c2, "@a")), NUM2DBL(rb_iv_get(el, "@x3")), NUM2DBL(rb_iv_get(el, "@y3")), NUM2DBL(rb_iv_get(c3, "@r")), NUM2DBL(rb_iv_get(c3, "@g")), NUM2DBL(rb_iv_get(c3, "@b")), NUM2DBL(rb_iv_get(c3, "@a")) ); draw_triangle( NUM2DBL(rb_iv_get(el, "@x3")), NUM2DBL(rb_iv_get(el, "@y3")), NUM2DBL(rb_iv_get(c3, "@r")), NUM2DBL(rb_iv_get(c3, "@g")), NUM2DBL(rb_iv_get(c3, "@b")), NUM2DBL(rb_iv_get(c3, "@a")), NUM2DBL(rb_iv_get(el, "@x4")), NUM2DBL(rb_iv_get(el, "@y4")), NUM2DBL(rb_iv_get(c4, "@r")), NUM2DBL(rb_iv_get(c4, "@g")), NUM2DBL(rb_iv_get(c4, "@b")), NUM2DBL(rb_iv_get(c4, "@a")), NUM2DBL(rb_iv_get(el, "@x1")), NUM2DBL(rb_iv_get(el, "@y1")), NUM2DBL(rb_iv_get(c1, "@r")), NUM2DBL(rb_iv_get(c1, "@g")), NUM2DBL(rb_iv_get(c1, "@b")), NUM2DBL(rb_iv_get(c1, "@a")) ); } break; case IMAGE: { if (rb_iv_get(el, "@data") == Qnil) { VALUE data = init_image( renderer, RSTRING_PTR(rb_iv_get(el, "@path")) ); rb_iv_set(el, "@data", data); } draw_image( el, NUM2DBL(rb_iv_get(el, "@x")), NUM2DBL(rb_iv_get(el, "@y")) ); } break; case TEXT: { if (rb_iv_get(el, "@data") == Qnil) { VALUE data = init_text( renderer, RSTRING_PTR(rb_iv_get(el, "@font")), RSTRING_PTR(rb_iv_get(el, "@text")), NUM2DBL(rb_iv_get(el, "@size")) ); rb_iv_set(el, "@data", data); } // // TODO: Set color of text // VALUE c = rb_iv_get(el, "@c"); // NUM2DBL(rb_iv_get(c, "@r")), // NUM2DBL(rb_iv_get(c, "@g")), // NUM2DBL(rb_iv_get(c, "@b")), draw_text( el, RSTRING_PTR(rb_iv_get(el, "@text")), NUM2DBL(rb_iv_get(el, "@x")), NUM2DBL(rb_iv_get(el, "@y")) ); } break; } } // Draw frame SDL_GL_SwapWindow(window); } // Clean up IMG_Quit(); Mix_Quit(); SDL_GL_DeleteContext(glcontext); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { (void) argc; (void) argv; if (SDL_Init(SDL_INIT_EVERYTHING) == -1) std::cout << "Failed to initialize SDL" << SDL_GetError() << std::endl; std::cout << "Hello SDL!" << std::endl; // Display SDL version information SDL_version compiled; SDL_version linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); logSDLVersion(std::cout, "SDL", compiled, linked, SDL_GetRevision()); // Initialize SDL_image and display version information int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG; int imgFlagsInit = IMG_Init(imgFlags); if ((imgFlagsInit & imgFlags) != imgFlags) std::cout << "Failed to initialize SDL_image:" << IMG_GetError() << std::endl; std::cout << "Hello SDL_image!" << std::endl; SDL_IMAGE_VERSION(&compiled); logSDLVersion(std::cout, "SDL_image", compiled, *IMG_Linked_Version(), ""); // Initialize SDL_mixer and display version information int mixFlags = MIX_INIT_OGG; int mixFlagsInit = Mix_Init(mixFlags); if ((mixFlagsInit & mixFlags) != mixFlags) { std::cout << "Failed to initialize SDL_mixer" << Mix_GetError() << std::endl; } if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == -1) { std::cout << "Failed to acquire sound device" << Mix_GetError() << std::endl; } std::cout << "Hello SDL_mixer!" << std::endl; SDL_MIXER_VERSION(&compiled); logSDLVersion(std::cout, "SDL_mixer", compiled, *Mix_Linked_Version(), ""); logSDLMixerMediaInfo(std::cout); // Initialize SDL_mixer and display version information if (TTF_Init() != 0) std::cout << "Failed to initialize SDL_ttf:" << SDL_GetError() << std::endl; std::cout << "Hello SDL_ttf!" << std::endl; SDL_TTF_VERSION(&compiled); logSDLVersion(std::cout, "SDL_ttf", compiled, *TTF_Linked_Version(), ""); // Create a window and OpenGL glContext using SDL and GLEW SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_Window* window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); SDL_GLContext glContext = nullptr; const std::pair<int, int> glVersions[11] {{4, 4}, {4, 3}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2}, {3, 1}, {3, 0}, {2, 1}, {2, 0} }; const std::string glName = "OpenGL"; for (auto& glVersion : glVersions) { std::cout << "Trying to create " << glName << " " << glVersion.first << "." << glVersion.second << " glContext" << std::endl; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, glVersion.first); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, glVersion.second); glContext = SDL_GL_CreateContext(window); if (glContext != nullptr) break; } if (glContext == nullptr) std::cout << "Failed to create OpenGL Context " << std::endl; bool isOk = SDL_GL_MakeCurrent(window, glContext) <= 0; if (!isOk) std::cout << "Failed to set OpenGL context" << SDL_GetError() << std::endl; glewExperimental = true; if (glewInit() != GLEW_OK) std::cout << "Failed to initialize GLEW" << std::endl; logAcquiredGlVersion(std::cout, glName); logOpenGLContextInfo(std::cout); logGraphicsDriverInfo(std::cout); glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SDL_GL_SwapWindow(window); // Wait for user event before closing bool isRunning = true; SDL_Event event; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN && event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) isRunning = false; else if (event.type == SDL_QUIT) isRunning = false; } SDL_Delay(30); } // Cleanup SDL_DestroyWindow(window); SDL_GL_DeleteContext(glContext); IMG_Quit(); const int nOpenAudio = Mix_QuerySpec(nullptr, nullptr, nullptr); for (int i = 0 ; i < nOpenAudio ; ++i) Mix_CloseAudio(); while (Mix_Init(0)) Mix_Quit(); TTF_Quit(); SDL_Quit(); return 0; }
void ShutdownSDL() { Mix_Quit(); IMG_Quit(); SDL_Quit(); };