int main(int argc, char *argv[]) { SDL_Event event; /* nacteni modelu */ polymodel = modLoad((argc == 2) ? argv[1] : DEFAULT_MODEL); IZG_CHECK(polymodel, "Failed to read input model"); /* vytvoreni SW rendereru */ #ifdef USE_STUDENT_RENDERER renderer = studrenCreate(); #else renderer = renCreate(); #endif /* USE_STUDENT_RENDERER */ /* pocatecni velikost bufferu */ renderer->createBuffersFunc(renderer, DEFAULT_WIDTH, DEFAULT_HEIGHT); /* inicializace SDL knihovny */ if( SDL_Init(SDL_INIT_VIDEO) == -1 ) { IZG_SDL_ERROR("Could not initialize SDL library"); } /* nasteveni okna */ SDL_WM_SetCaption(PROGRAM_TITLE, 0); /* screen */ screen = SDL_SetVideoMode(DEFAULT_WIDTH, DEFAULT_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE); /* enable Unicode translation */ SDL_EnableUNICODE(1); /* kreslime dokud nenarazime na SDL_QUIT event */ while( !quit ) { /* vycteni udalosti */ while( SDL_PollEvent(&event) ) { switch( event.type ) { /* udalost klavesnice */ case SDL_KEYDOWN: onKeyboard(&event.key); break; /* zmena velikosti okna */ case SDL_VIDEORESIZE: onResize(&event.resize); break; /* udalost mysi */ case SDL_MOUSEMOTION: onMouseMotion(&event.motion); break; /* SDL_QUIT event */ case SDL_QUIT: quit = 1; break; default: break; } } /* vykresleni pres SDL knihovnu */ draw(); } /* ukonceni SDL */ SDL_FreeSurface(screen); /* shutdown all SDL subsystems */ SDL_Quit(); /* zrusime co jsme vytvorili a ukoncime program */ modRelease(&polymodel); renderer->releaseFunc(&renderer); return 0; }
void conn::conecta(std::string server,std::string port){ bot::team_id id = 1000; boost::asio::io_service io_service; tcp::resolver resolver(io_service); auto endpoint_iterator = resolver.resolve({ server, port }); std::shared_ptr<tcp::socket> socket(new tcp::socket(io_service)); boost::asio::connect(*socket, endpoint_iterator); bot::field_size field_width; bot::field_size field_height; int win_width = 500; int win_height = 500; bots Mundo; boost::mutex state_mutex; SDL_Init(SDL_INIT_VIDEO); atexit(SDL_Quit); SDL_WM_SetCaption("Superbots", "Superbots"); SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); MYscreen.set_screen(win_width, win_height); SDL_Event event; bool gameover = false; bool connected = false; boost::thread t = boost::thread([this,socket, &state_mutex, &gameover, &connected, &Mundo, &id, &field_width, &field_height, &win_width, &win_height] () { game_thread(socket, gameover, Mundo, id, state_mutex, field_width, field_height, win_width, win_height, connected); } ); while (!gameover) { if(connected) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: gameover = true; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: case SDLK_q: gameover = true; break; default: break; } break; case SDL_VIDEORESIZE: win_width = event.resize.w; win_height = event.resize.h; MYscreen.set_screen(win_width, win_height, field_width, field_height); break; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); { boost::mutex::scoped_lock lock(state_mutex); Mundo.for_each_bot([&Mundo] (const bot & the_bot) { auto t = the_bot.get_team() + 1; glColor3f(t * 0.2, 1 - t * 0.3, t * 0.1); const bot::position & pos = the_bot.get_position(); glLoadIdentity(); glTranslatef(pos.first, pos.second, 0); glBegin(GL_QUADS); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glEnd(); }); } SDL_GL_SwapBuffers(); } } if(Mundo.bot_count().size() != 1) { std::cout << "Shit!" << std::endl; } else { for(auto inmortal : Mundo.bot_count()) { std::cout << inmortal.first << " se ha pulido a todos!" << std::endl; } } }
SDL_Surface *initialization(int flags) { const SDL_VideoInfo* info = 0; int bpp = 0; SDL_Surface *screen; rg = new TRanrotBGenerator(0); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing SDL\n"); #endif if (SDL_Init(SDL_INIT_VIDEO | (sound ? SDL_INIT_AUDIO : 0) | SDL_INIT_JOYSTICK | SDL_INIT_EVENTTHREAD) < 0) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video initialization failed: %s\n", SDL_GetError()); #endif return 0; } #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("SDL initialized\n"); #endif info = SDL_GetVideoInfo(); if (!info) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video query failed: %s\n", SDL_GetError()); #endif return 0; } if (fullscreen) { bpp = COLOUR_DEPTH; } else { bpp = info->vfmt->BitsPerPixel; } desktopW = info->current_w; desktopH = info->current_h; #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Setting OpenGL attributes\n"); #endif #ifndef HAVE_GLES SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("OpenGL attributes set\n"); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing video mode\n"); #endif #ifdef HAVE_GLES fullscreen = true; flags = SDL_FULLSCREEN; #else flags = SDL_OPENGL | flags; #endif screen = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, bpp, flags); if (screen == 0) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video mode set failed: %s\n", SDL_GetError()); #endif return 0; } #ifdef HAVE_GLES EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #endif #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Video mode initialized\n"); #endif calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_WM_SetIcon(SDL_LoadBMP("graphics/f1sicon.bmp"), NULL); SDL_ShowCursor(SDL_DISABLE); if (sound) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing Audio\n"); #endif N_SFX_CHANNELS = Sound_initialization(N_SFX_CHANNELS, 0); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Audio initialized\n"); #endif } // Network: #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Initializing SDL_net...\n"); #endif if (SDLNet_Init() == -1) { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Error initializing SDL_net: %s.\n", SDLNet_GetError()); #endif network = false; } else { #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("SDL_net initialized.\n"); #endif network = true; } SDL_EnableUNICODE(1); glGetIntegerv(GL_STENCIL_BITS, &g_stencil_bits); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("OpenGL stencil buffer bits: %i\n", g_stencil_bits); #endif return screen; } /* initialization */
void CAppStateIntro::OnActivate() { //Surf_Logo = CSurface::OnLoad("test.bmp"); StartTime = SDL_GetTicks(); SDL_WM_SetCaption("Intro State", NULL); }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_WM_SetCaption("La grue !", NULL); SDL_SetVideoMode(LARGEUR_ECRAN, HAUTEUR_ECRAN, 32, SDL_OPENGL); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, LARGEUR_ECRAN, 0, HAUTEUR_ECRAN); bool continuer = true; SDL_Event event; SDLMod mod = KMOD_NONE; int angle_grand_bras = 45; int angle_petit_bras = -10; int longueur_fils = 50; while (continuer) { SDL_WaitEvent(&event); mod = SDL_GetModState(); switch(event.type) { case SDL_QUIT: continuer = false; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: /* Appui sur la touche Echap, on arrête le programme */ continuer = false; break; case SDLK_UP: if (longueur_fils > LONGUEUR_FILS_MIN) longueur_fils -= 1; break; case SDLK_DOWN: if (longueur_fils < LONGUEUR_FILS_MAX) longueur_fils += 1; break; case SDLK_LEFT: if (mod & KMOD_SHIFT) { if (angle_grand_bras < ANGLE_GD_BRAS_MAX) angle_grand_bras += 5; } else { if (angle_petit_bras < ANGLE_PT_BRAS_MAX) angle_petit_bras += 5; } break; case SDLK_RIGHT: if (mod & KMOD_SHIFT) { if (angle_grand_bras > ANGLE_GD_BRAS_MIN) angle_grand_bras -= 5; } else { if (angle_petit_bras > ANGLE_PT_BRAS_MIN) angle_petit_bras -= 5; } break; case SDLK_h: /* dessinerRepere(50); */ break; default: break; } break; default: break; } /* efface le tampon d'affichage */ glClear(GL_COLOR_BUFFER_BIT); /* dessine */ /* base */ glPushMatrix(); glTranslated(20, 20, 0); glBegin(GL_QUADS); glColor3ub(255, 150, 0); glVertex2d(0, 0); glVertex2d(0, 40); glVertex2d(100, 40); glVertex2d(100, 0); glEnd(); glPopMatrix(); /* grand bras */ glPushMatrix(); glTranslated(70, 60, 0); glRotated(angle_grand_bras, 0, 0, 1); glBegin(GL_QUADS); glColor3ub(255, 250, 0); glVertex2d(0, -15); glVertex2d(0, 15); glVertex2d(LONGUEUR_GD_BRAS, 15); glVertex2d(LONGUEUR_GD_BRAS, -15); glEnd(); /* petit bras */ glTranslated(LONGUEUR_GD_BRAS, 0, 0); glRotated(angle_petit_bras, 0, 0, 1); glBegin(GL_QUADS); glColor3ub(50, 250, 50); glVertex2d(0, -10); glVertex2d(0, 10); glVertex2d(LONGUEUR_PT_BRAS, 10); glVertex2d(LONGUEUR_PT_BRAS, -10); glEnd(); /* fils */ glTranslated(LONGUEUR_PT_BRAS, 0, 0); glRotated(-90 + (angle_petit_bras * -1) + (angle_grand_bras * -1), 0, 0, 1); glBegin(GL_LINES); glColor3ub(255, 255, 255); glVertex2d(0, 0); glVertex2d(longueur_fils, 0); glEnd(); /* caisse */ glTranslated(longueur_fils, 0, 0); glBegin(GL_QUADS); glColor3ub(255, 0, 0); glVertex2d(0, (TAILLE_CAISSE / 2)); glVertex2d(TAILLE_CAISSE, (TAILLE_CAISSE / 2)); glVertex2d(TAILLE_CAISSE, -(TAILLE_CAISSE / 2)); glVertex2d(0, -(TAILLE_CAISSE / 2)); glEnd(); /* Restore la matrice de base pour que les modifications qui viennent d'être effectuées ne s'ajoutent pas à chaque fois que les éléments se redessine */ glPopMatrix(); /* s'assure que toutes les cmd opengl ont été exécutées */ glFlush(); /* échange des buffers back et front */ SDL_GL_SwapBuffers(); } SDL_Quit(); return 0; }
int main(int argc, char** argv) { /* Init SDL */ if ( SDL_Init(SDL_INIT_TIMER|SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't load SDL: %s\n", SDL_GetError()); exit(1); } /* Clean up on exit */ atexit(SDL_Quit); /* Set window title */ SDL_WM_SetCaption("Input Deluxe", "input deluxe"); /* Initialize the display */ SDL_Surface *screen; screen = SDL_SetVideoMode(600, 400, 0, SDL_SWSURFACE); if ( screen == NULL ) { fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); exit(1); } sge_Update_OFF(); SDL_EnableUNICODE(1); //This is VERY important!! //Init our text sprites sge_TextSprite text(screen,"Edit Me!",20,90); text.show_cursor(true); sge_TextSprite text2(screen,"Hello World!",100,25); text.show_cursor(true); //Set and draw the border box SDL_Rect r; r.x=1; r.y=81; r.w=598; r.h=318; text.set_border(r); sge_Rect(screen,0,80, 599,399, 255,0,0); //Open a TT font if(sge_TTF_Init()!=0){fprintf(stderr,"TT error: %s\n",SDL_GetError());exit(1);} sge_TTFont *font; font=sge_TTF_OpenFont("/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf", 25); if(font==NULL){fprintf(stderr,"TT error: %s\n",SDL_GetError());exit(1);} text.set_ttFont(font,0,255,0); //Use our font text2.set_ttFont(font,50,50,200); text.set_pps(60,60); //set speed (pixels/second) text2.set_pps(-170,0); text.border_warp(true); //WARP! text2.border_warp(true); SDL_UpdateRect(screen, 0,0,0,0); //Update whole screen //Keyrepeat SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL+50); SDL_Event event; do{ //SDL_Delay(1); /* Check events */ if(SDL_PollEvent(&event)==1){ if(event.type==SDL_QUIT){break;} if(event.type==SDL_KEYDOWN && event.key.keysym.sym==SDLK_ESCAPE){break;} text.check(&event); //Let our text sprite handle the event (editing the text) } if(text.update()){ //update() calculates the new pos and returns true if we need to redraw text.clear(0); //clear text area text.draw(); //draw text at new pos sge_Update_ON(); text.UpdateRects(); //Update screen (old pos + new pos) sge_Update_OFF(); } if(text2.update()){ //Same thing for the other sprite text2.clear(0); text2.draw(); sge_Update_ON(); text2.UpdateRects(); sge_Update_OFF(); } }while(true); sge_TTF_CloseFont(font); return 0; }
Window::Window() { // Set window title SDL_WM_SetCaption("RoboHockey",NULL); // Create surfaces mainSurface = SDL_SetVideoMode(1024, 768, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_SRCALPHA); rinkSurface = IMG_Load("data/surfaces/rink.png"); SDL_SetColorKey(rinkSurface, SDL_RLEACCEL, rinkSurface->format->colorkey); statSurface = IMG_Load("data/surfaces/stat.png"); puck = IMG_Load("data/objects/puck.png"); SDL_SetColorKey(puck, SDL_RLEACCEL, puck->format->colorkey); greenPlayer = IMG_Load("data/objects/green_player.png"); SDL_SetColorKey(greenPlayer, SDL_RLEACCEL, greenPlayer->format->colorkey); bluePlayer = IMG_Load("data/objects/blue_player.png"); SDL_SetColorKey(bluePlayer, SDL_RLEACCEL, bluePlayer->format->colorkey); // Blit the surfaces SDL_BlitSurface(rinkSurface, NULL, mainSurface, NULL); // Statistics surface statRect.x = rinkSurface->w; statRect.w = mainSurface->w - rinkSurface->w; statRect.y = 0; statRect.h = mainSurface->h; SDL_BlitSurface(statSurface, NULL, mainSurface, &statRect); // Puck updatePuck(); // Create Font(s) arcade = TTF_OpenFont("data/fonts/arcade.ttf", 72); arcadeSmall = TTF_OpenFont("data/fonts/arcade.ttf", 48); nameFont = TTF_OpenFont("data/fonts/sb.ttf", 12); // Players withPuck.x = 44; withPuck.y = 0; withPuck.w = 44; withPuck.h = 44; withoutPuck.x = 0; withoutPuck.y = 0; withoutPuck.w = 44; withoutPuck.h = 44; updatePlayers(); // Set up text rectangles clockRect.x = 695; clockRect.y = 65; clockRect.w = 154; clockRect.h = 34; homeScore.x = 605; homeScore.y = 175; homeScore.w = 33; homeScore.h = 34; period.x = 753; period.y = 195; period.w = 33; period.h = 34; awayScore.x = 902; awayScore.y = 175; awayScore.w = 33; awayScore.h = 34; homeShots.x = 660; homeShots.y = 340; homeShots.w = 22; homeShots.h = 23; awayShots.x = 852; awayShots.y = 340; awayShots.w = 22; awayShots.h = 23; // Default texts drawText(&clockRect, arcade, (Game::instance()->getClock()).c_str()); drawText(&homeScore, arcade, "0"); drawText(&period, arcade, "1"); drawText(&awayScore, arcade, "0"); drawText(&homeShots, arcadeSmall, "0"); drawText(&awayShots, arcadeSmall, "0"); // Swap buffers to show the whole thing SDL_Flip(mainSurface); }
main (int argc, char **argv) { SDL_Surface *screen; SDL_Surface *picture, *convert; struct warp *w; int xw, yw, cw, tval; void (*doWarp)(struct warp *w, int xw, int yw, int cw); if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); exit(2); } atexit(SDL_Quit); /* Load the picture that will be warped */ if ( argv[1] == NULL ) { argv[1] = "leeloo.bmp"; } picture = SDL_LoadBMP(argv[1]); if ( picture == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", argv[1], SDL_GetError()); exit(1); } /* Since doWarp() is mucking with the pixels directly, it's almost always faster to create the surface in system memory and let SDL perform a blit than to go over the video bus for each pixel. */ screen = SDL_SetVideoMode(picture->w, picture->h, 8, (SDL_ANYFORMAT|SDL_FULLSCREEN|SDL_DOUBLEBUF)); if ( screen == NULL ) { fprintf(stderr, "Couldn't set video mode %dx%d: %s\n", picture->w, picture->h, SDL_GetError()); SDL_FreeSurface(picture); exit(3); } SDL_WM_SetCaption("Warp Demo by Emmanuel Marty", "warp"); /* Seed the palette, don't worry if it doesn't take */ if ( picture->format->palette ) { SDL_SetColors(screen, picture->format->palette->colors, 0, picture->format->palette->ncolors); } /* Convert the picture to the display format for speed */ convert = SDL_ConvertSurface(picture, screen->format, SDL_SWSURFACE); SDL_FreeSurface(picture); if ( convert == NULL ) { fprintf(stderr, "Couldn't convert image: %s\n", SDL_GetError()); exit(3); } picture = convert; /* Ignore app focus and mouse motion events */ SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE); SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); /* Warp the image until we get an event (button, key, quit) */ w = initWarp(picture); if ( w == NULL ) { fprintf(stderr, "Couldn't initialize warp structure\n"); SDL_FreeSurface(picture); exit(4); } w->dst = screen; switch (screen->format->BytesPerPixel) { case 1: doWarp = doWarp8bpp; break; case 2: doWarp = doWarp16bpp; break; case 3: doWarp = doWarp24bpp; break; case 4: doWarp = doWarp32bpp; break; default: fprintf(stderr, "Unknown BytesPerPixel: %d\n", screen->format->BytesPerPixel); exit(3); } tval = 0; while ( SDL_PollEvent(NULL) == 0 ) { /* Lock the video surface */ if ( SDL_LockSurface(screen) < 0 ) { continue; } /* Calculate the next warp step */ xw = (int) (sin((tval+100)*M_PI/128) * 30); yw = (int) (sin((tval)*M_PI/256) * -35); cw = (int) (sin((tval-70)*M_PI/64) * 50); xw += (int) (sin((tval-10)*M_PI/512) * 40); yw += (int) (sin((tval+30)*M_PI/512) * 40); /* Get the current framebuffer pointer */ w->framebuf = (Uint8 *)screen->pixels; /* WARP! (assuming display bpp hasn't changed) */ doWarp(w, xw, yw, cw); /* Unlock and update the screen */ SDL_UnlockSurface(screen); SDL_Flip(screen); /* Update tval for the next round... */ tval = (tval+1) & 511; } SDL_FreeSurface(picture); exit(0); }
void GraphicsManager::setWindowTitle(const Common::UString &title) { SDL_WM_SetCaption(title.c_str(), 0); }
void start() { SDL_WM_SetCaption("Tennis game over", 0); }
int main(int argc, char *argv[]) { // Erectin' a display SDL_Surface *screen; SDL_Init(SDL_INIT_EVERYTHING); screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE); SDL_WM_SetCaption("Smuggler Demo", "Smuggler Demo"); bool quit = false; // Setting up text TTF_Font* Font=NULL; TTF_Init(); SDL_Surface* TextSurface = NULL; Font=TTF_OpenFont("DejaVuSansMono.ttf",16); SDL_Color color; color.r=255; color.g=255; color.b=255; int FontSize = 10; bool growing = true; // Rendering surfaces // Set background surface to display optimized SDL_Surface *background; SDL_Surface *oldface; oldface = IMG_Load("backimage.png"); background = SDL_DisplayFormat(oldface); SDL_FreeSurface(oldface); // Set player's image to Player player1("ana.png"); Player player2("character.png"); player2.coordX(500); player2.coordY(500); // Load overlay surface and set transparency color to 0 SDL_Surface *overlay = &map(); SDL_SetColorKey(overlay, SDL_SRCCOLORKEY,0); // Instantiate timer object Timer fps; int walkFrames = 2; while(!quit){ // Start the timer for frame rate limiting fps.start(); // The input handling function returns a bool. While quit == false, the game will continue to run quit = input(&player1, movementspeed); // This function animates through the cycle, using an iterating number that triggers the different frames // TODO: The walkframes integer should be tucked into the object it is manipulating, in this case, player. walkFrames=animate(player1.xvel(), player1.yvel(), movementspeed, walkFrames, walkFrameInterval, &player1); // Renders the background on the bottom SDL_BlitSurface(background, NULL, screen, NULL); // Puts the player underneath the overlay, which is basically the map SDL_BlitSurface(&player1.image(), &player1.frame(), screen, &player1.location()); // Checks for collisions if (collision(&player1.image(), player1.coordX(), player1.coordY(), 100, &player2.image(), player2.coordX(), player2.coordY(), 100)) { cout << "COLLIDE!\n"; player2.xvel(0); player2.yvel(0); } else { cout << "NO COLLIDE!\n"; player2.ai(player1); } // Puts the NPC underneath the overlay walkFrames=animate(player2.xvel(), player2.yvel(), movementspeed/2, walkFrames, walkFrameInterval, &player2); SDL_BlitSurface(&player2.image(), &player2.frame(), screen, &player2.location()); // Renders the map SDL_BlitSurface(overlay, NULL, screen, NULL); // Renders the text if (growing == true) { FontSize ++; } else { FontSize --; } if (FontSize == 25) { growing = false; } if (FontSize == 1) { growing = true; } Font=TTF_OpenFont("DejaVuSansMono.ttf",FontSize); TextSurface=TTF_RenderText_Solid(Font,"I love poop!!",color); SDL_BlitSurface(TextSurface, NULL, screen, &player2.speech_bubble()); TTF_CloseFont(Font); SDL_FreeSurface(TextSurface); // Renders it all to the display SDL_Flip(screen); // For performance measuring purposes, this line spits out the max framerate possible if this rate of animation is sustained. // printf("Max Frames per second: %d\n", 1000/fps.get_ticks()); // Hard locks the frame rate to 60 frames per second or less if(fps.get_ticks() < 1000 / FPS) { SDL_Delay ((1000/FPS) - fps.get_ticks()); } } SDL_Quit(); }
int main( int argc, char* argv[] ) { /* Information about the current video settings. */ const SDL_VideoInfo* info = NULL; g_Time = InitTime(); /* First, initialize SDL's video subsystem. */ if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { /* Failed, exit. */ fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } /* Let's get some video information. */ info = SDL_GetVideoInfo( ); if( !info ) { /* This should probably never happen. */ fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } g_bpp = info->vfmt->BitsPerPixel; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); g_flags = SDL_OPENGL|SDL_HWPALETTE|/*SDL_NOFRAME|*/SDL_HWSURFACE/*|SDL_RESIZABLE*//*| SDL_FULLSCREEN*/; /* * Set the video mode */ if( SDL_SetVideoMode( g_width, g_height, g_bpp, g_flags ) == 0 ) { /* * This could happen for a variety of reasons, * including DISPLAY not being set, the specified * resolution not being available, etc. */ fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } /* * At this point, we should have a properly setup * double-buffered window for use with OpenGL. */ setup_opengl( g_width, g_height ); GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); quit_tutorial(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); if (!GLEW_ARB_vertex_program || !GLEW_ARB_vertex_program) { fprintf(stderr, "No shader program support\n"); quit_tutorial(1); } if (glewIsSupported("GL_VERSION_2_0")) printf("Ready for OpenGL 2.0\n"); else { printf("OpenGL 2.0 not supported\n"); quit_tutorial(1); } /* * Init OpenGL text driver which will * be used by GraphicsConsole */ g_pTextDriver = new OGLTextDriver(); if( false == g_pTextDriver->init("FixedWidth.bmp", 8, 16, 16, g_width, g_height)) quit_tutorial( 1 ); register_commands(); GraphicsConsole::Instance().setTextDriver(g_pTextDriver); SDL_EnableKeyRepeat(500, 30); draw_velocity = glsl_program::makeProgram("drawVelocity", DATA_PATH"quad.vs", DATA_PATH"draw_velocity.fs"); draw_fluids = glsl_program::makeProgram("drawFluids", DATA_PATH"quad.vs", DATA_PATH"draw_fluids.fs"); assert(draw_velocity); start_time = time(0); g_fluids.createShaders(); g_fluids.createBuffers(); UI::Init(g_width, g_height); g_fluids.createUI(); SDL_WM_SetCaption("console", 0); /* * Now we want to begin our normal app process-- * an event loop with a lot of redrawing. */ while( !g_exit ) { UpdateTime(&g_Time); /* Process incoming events. */ process_events( ); /* Draw the screen. */ draw_screen( ); } quit_tutorial(0); return 0; }
int main(int argc, char** argv) { // Create a configuration object, and set the values to the defaults configuration config; config.num_threads = NUM_THREADS; config.video.screen_width = SCREEN_WIDTH; config.video.screen_height = SCREEN_HEIGHT; config.video.screen_depth = SCREEN_DEPTH; config.video.frames_per_second = FPS; config.input.influence_radius = INFLUENCE_RADIUS; config.flock.size = NUM_BOIDS; config.flock.max_velocity = MAX_BOID_VELOCITY; config.flock.min_separation = MIN_BOID_SEPARATION; config.flock.max_steering_force = MAX_BOID_STEERING_FORCE; config.flock.neighborhood_radius = NEIGHBORHOOD_RADIUS; // Parse arguments int i; for(i = 1; i < argc; i++) { if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) return print_help(); else if(strcmp(argv[i], "--width") == 0) config.video.screen_width = atoi(argv[++i]); else if(strcmp(argv[i], "--height") == 0) config.video.screen_height = atoi(argv[++i]); else if(strcmp(argv[i], "--depth") == 0) config.video.screen_depth = atoi(argv[++i]); else if(strcmp(argv[i], "--fps") == 0) config.video.frames_per_second = atoi(argv[++i]); else if(strcmp(argv[i], "-ir") == 0 || strcmp(argv[i], "--influence-radius") == 0) config.input.influence_radius = atoi(argv[++i]); else if(strcmp(argv[i], "-fc") == 0 || strcmp(argv[i], "--flock-count") == 0) config.flock.size = atoi(argv[++i]); else if(strcmp(argv[i], "-fs") == 0 || strcmp(argv[i], "--flock-separation") == 0) config.flock.min_separation = atoi(argv[++i]); else if(strcmp(argv[i], "-fv") == 0 || strcmp(argv[i], "--flock-velocity") == 0) config.flock.max_velocity = atoi(argv[++i]); else if(strcmp(argv[i], "-fn") == 0 || strcmp(argv[i], "--flock-neighborhood") == 0) config.flock.neighborhood_radius = atoi(argv[++i]); else if(strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--num-threads") == 0) config.num_threads = atoi(argv[++i]); } srand(time(NULL)); // Init SDL and create our screen if(SDL_Init(SDL_INIT_VIDEO) < 0) printf("Unable to initialize SDL. %s\n", SDL_GetError()); SDL_Event event; int flags = SDL_OPENGL; // Attempt to set the video mode SDL_Surface* screen = SDL_SetVideoMode(config.video.screen_width, config.video.screen_height, config.video.screen_depth, flags); if(!screen) printf("Unable to set video mode.\n"); // Set the window caption SDL_WM_SetCaption("tinyflock", NULL); // Create our flock boid* flock = create_flock(&config); init_gl(config.video.screen_width, config.video.screen_height); vector cursor_pos; vector_init_scalar(&cursor_pos, 0); int cursor_interaction = 0; int run = 1; int update_count = 0; int frame_count = 0; flock_update_args update_args = {&run, flock, &config, &cursor_pos, &cursor_interaction, &update_count }; SDL_Thread* update = SDL_CreateThread(flock_update_thread, (void*)&update_args); status_args stat_args = {&run, &frame_count, &update_count}; SDL_Thread* status = SDL_CreateThread(status_thread, (void*)&stat_args); // If the frame limit is not greater than 0, don't delay between frames at all. float delay = (1000 / config.video.frames_per_second); while(run) { run = handle_events(&event, &cursor_pos, &cursor_interaction); flock_render(flock, &config, screen); SDL_Delay(delay); frame_count++; } SDL_WaitThread(update, NULL); SDL_WaitThread(status, NULL); destroy_flock(flock); SDL_Quit(); return 0; }
void graphics_viewport_set_title(char* title) { SDL_WM_SetCaption(title, title); }
int main(int argc, char *argv[]) { SDL_Surface *screen, *sprite, *door; SDL_Rect rcSprite, rcWall, rcFloor, rcStatus; TTF_Font *fntText; SDL_Surface *sText; SDL_Rect rcText = { 5, 290, 0, 0 }; SDL_Color clrText = { 192, 192, 192, 0 }; char debug[100]; unsigned int colorkey; /* Initialize the SDL library: */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { printf("%s: SDL_Init(): %s\n", argv[0], SDL_GetError()); exit(EXIT_FAILURE); } /* Clean up SDL on exit: */ if (atexit(SDL_Quit) != 0) { printf("%s: Cannot register exit function SDL_Quit().\n", argv[0]); exit(EXIT_FAILURE); } /* Initialize SDL TTF engine: */ if (TTF_Init() != 0) { printf("%s: TTF_Init(): %s\n", argv[0], TTF_GetError()); exit(EXIT_FAILURE); } /* Clean up TTF on exit: */ if (atexit(TTF_Quit) != 0) { printf("%s: Cannot register exit function TTF_Quit().\n", argv[0]); exit(EXIT_FAILURE); } /* Set up video: */ screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0); if (screen == NULL) { printf("%s: SDL_SetVideoMode: %s\n", argv[0], SDL_GetError()); exit(EXIT_FAILURE); } /* Set the title bar: */ SDL_WM_SetCaption("Open Paradise Cafe", NULL); /* set keyboard repeat */ SDL_EnableKeyRepeat(70, 70); /* load sprite damatta */ sprite = load_surface("sprites.bmp"); /* load door */ door = load_surface("porta.bmp"); /* setup sprite colorkey and turn on RLE */ colorkey = SDL_MapRGB(screen->format, 255, 0, 255); SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); SDL_SetColorKey(door, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); /* posicao inicial do damatta */ rcSprite.x = 150; rcSprite.y = 150; /* define o tamanho e o *frame* do boneco */ rcSrc.x = 0; rcSrc.y = 0; rcSrc.w = SPRITE_WIDTH; rcSrc.h = SPRITE_HEIGHT; /*printf("sprite w=%d %d h=%d %d\n", sprite->w, SPRITE_WIDTH, sprite->h, SPRITE_HEIGHT);*/ /* define o tamanho das portas */ rcSrcDoor.x = 0; rcSrcDoor.y = 0; rcSrcDoor.w = 56; /* so a primeira frame */ rcSrcDoor.h = door->h; /*printf("door w=%d h=%d\n", door->w, door->h);*/ /* posicao inicial da porta */ rcDoor.x = 350; rcDoor.y = 126; /* Wall: */ rcWall.x = 0; rcWall.y = 0; rcWall.w = SCREEN_WIDTH; rcWall.h = SCREEN_HEIGHT; /* Floor: */ rcFloor.x = 0; rcFloor.y = 262; rcFloor.w = SCREEN_WIDTH; rcFloor.h = 24; /* Status: */ rcStatus.x = 0; rcStatus.y = 262 + 24; rcStatus.w = SCREEN_WIDTH; rcStatus.h = SCREEN_HEIGHT - 262 - 24; /* load a font and give it a point-size */ fntText = TTF_OpenFont("arial.ttf", 12); if (fntText == NULL) { printf("TTF_OpenFont: %s\n", TTF_GetError()); exit(EXIT_FAILURE); } gameover = 0; /* usada pra sair */ jewish_param.lol = SDLK_RIGHT; jewish_timer = SDL_AddTimer(100, jewish_timer_callback, &jewish_param); while (!gameover) { SDL_Event event; SDL_WaitEvent(NULL); /* para nao consumir 100% do cpu */ /* /!\ ACHTUNG: DOOR /!\ */ if (rcSprite.x + SPRITE_WIDTH == rcDoor.x && door_closed) { door_closed = 0; door_param.frame = 1; door_param.timer = SDL_AddTimer(250, door_timer_callback, &door_param); SDL_RemoveTimer(jewish_timer); jewish_timer = NULL; event.type = SDL_USEREVENT; event.user.code = USEREVENT_DOOR; event.user.data1 = 0; event.user.data2 = 0; SDL_PushEvent(&event); } /* Ao sair da porta a porta tem que se fechar */ if (rcSprite.x == rcDoor.x + 50) { printf("dead by dawn"); } /* look for an event */ if (SDL_PollEvent(&event)) HandleEvent(event); /* Draw the wall (red): */ SDL_FillRect(screen, &rcWall, SDL_MapRGB(screen->format, 0xc8, 0x41, 0x34)); /* Draw the floor (purple f*g): */ SDL_FillRect(screen, &rcFloor, SDL_MapRGB(screen->format, 0xc6, 0x0, 0xc6)); /* Draw the status line (blue): */ SDL_FillRect(screen, &rcStatus, SDL_MapRGB(screen->format, 0x0, 0x0, 0xc6)); /* Draw the door: */ SDL_BlitSurface(door, &rcSrcDoor, screen, &rcDoor); /* Draw the sprite: */ SDL_BlitSurface(sprite, &rcSrc, screen, &rcSprite); /* render text to an SDL_Surface */ sprintf(debug, "src(x=%d y=%d) door(x=%d y=%d w=%d h=%d) srcdoor(x=%d y=%d w=%d h=%d)", rcSrc.x, rcSrc.y, rcDoor.x, rcDoor.y, rcDoor.w, rcDoor.h, rcSrcDoor.x, rcSrcDoor.y, rcSrcDoor.w, rcSrcDoor.h); sText = TTF_RenderText_Solid(fntText, debug, clrText); SDL_BlitSurface(sText, NULL, screen, &rcText); /* Update the screen: */ SDL_UpdateRect(screen, 0, 0, 0, 0); } /* Clean up: */ SDL_FreeSurface(sprite); SDL_FreeSurface(door); return 0; }
int main(int argc, char* argv[]) { // Init initPath(argv[0]); SDL_Surface* screen = NULL; SDL_Event event; int *seed; srand((int)seed); int previousTime = 0, currentTime = 0; Events *flags = createEventFlags(); SDL_Init(SDL_INIT_VIDEO); SDL_SetEventFilter(eventFilter); screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_DOUBLEBUF | SDL_NOFRAME); SDL_WM_SetCaption("Tower Defense", NULL); Action *actionList = initAction(); Map* map = createMap(getPath("resources/Forest.png")); _map = map; SDL_Rect surface = {0, 0, 720, 600}; Viewport* viewport = createViewport(screen, surface, map); _viewport = viewport; // FIXME uh? what's this thing? surface.x = 800 - 80; surface.y = 0; surface.h = 80; surface.w = 600; // Creation of the enemies TypeEn *whiteCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/white_transparent_cat.png")); TypeEn *blackCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/black_transparent_cat.png")); Enemy *cat1 = createEnemy(1,1,whiteCat); Enemy *cat2 = createEnemy(1,10,whiteCat); Enemy *cat3 = createEnemy(5,5,blackCat); Enemy *cat4 = createEnemy(21,4,blackCat); TypeEn *zombie = createTypeEn(100,5,false,true,true,false,1,getPath("resources/zombie.png")); Enemy *zombie1 = createEnemy(4,4,zombie); Enemy *zombie2 = createEnemy(9,4,zombie); Enemy *zombie3 = createEnemy(9,9,zombie); Enemy *zombie4 = createEnemy(7,14,zombie); //Add enemy in the List List *catList = newList(cat4); pushList((void*)catList,cat2); pushList((void*)catList,cat3); // pushList((void*)catList,cat1); List *zombieList = newList(zombie1); /* pushList((void*)zombieList,zombie2);*/ /* pushList((void*)zombieList,zombie3);*/ /* pushList((void*)zombieList,zombie4);*/ // removeEnemyFromList(cat4,catList); //TOWER TypeBul *bullet = createTypeBul(getPath("resources/bullet.png"), 1); TypeTo *tower = createTypeTo(0,5,0,0,false,false,false,false,bullet,NULL,getPath("resources/tower.png")); upgradeTypeTo(tower,0.5,getPath("resources/towerUP.png")); flags->selectedTower = tower->nextType; Tower *tower1 = createTower(7,7,tower); List *towerList = newList(tower1); flags->towerList = towerList; // Create and Renders the right panel game menu SDL_Rect surfaceMenu = {720, 0, 800, 600}; Menu* menu = menu_create(screen, surfaceMenu); menu_loadBackground(menu, "resources/enemyFont.gif"); // For testing only, we add a few random buttons menu_addButton(menu, button_createBuildButton(tower)); menu_addButton(menu, button_createBuildButton(tower)); menu_addButton(menu, button_createBuildButton(tower)); menu_render(menu); _cell = *getCase(20,11); // Main loop while(actionList[QUIT].boolean == NULL) { // Managing the events manageEvents(viewport, flags,actionList); for(int i=1; i<ACTION_LENGTH; i++) { if(actionList[i].boolean) { int repeat = (*actionList[i].action)(viewport,flags,actionList[i].boolean); if(!repeat) { actionList[i].boolean = NULL; } } } // Redraws the map (viewport contents) before blitting stuff on it updateViewport(viewport); ///////////////////////////// DEBUG WALL ///////////////////////////// SDL_Rect position; for(int i=0; i < _map->nbCaseW; i++) { for(int j=0; j < _map->nbCaseH; j++) { Case cell = *getCase(i,j); position.x = cell.x; position.y = cell.y; if(map->matrice[i][j].hasTower == 2) { SDL_Surface *wall = IMG_Load(getPath("resources/brick.png")); blitToViewport(viewport, wall, NULL, &position); } } } position.x = _cell.x; position.y = _cell.y; blitToViewport(viewport, IMG_Load(getPath("resources/candy_cane.png")), NULL, &position); ///////////////////////////////////////////////////////////////////// // Move enemies if(flags->enemy_Path_Calculation) { pathReCalculation(catList); pathReCalculation(zombieList); flags->enemy_Path_Calculation = false; } moveEnemyList(zombieList); moveEnemyList(catList); // Blit enemies drawEnemyList(zombieList); drawEnemyList(catList); //Blit TOWER /* if(event.key.keysym.sym == SDLK_u){*/ /* upgrade(tower1);*/ /* }*/ Bullet *bullet1 = createBullet(tower1); animateBullet(bullet1); drawTowerList(towerList); /* This should be handled by event.c switch(event.key.keysym.sym){ case SDLK_a: flags->selectedTower = tower; break; case SDLK_b: flags->selectedTower = tower->nextType; break; default: break; }*/ /* */ // Ask SDL to swap framebuffers to update the displayed screen SDL_Flip(screen); // Managing frames currentTime = SDL_GetTicks(); if (currentTime - previousTime <= 20) { SDL_Delay(20 - (currentTime - previousTime)); } // DEBUG printf("Frame %i : %ims\n", framecounter++, currentTime - previousTime); previousTime = SDL_GetTicks(); } free(actionList); SDL_Quit(); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { /* Check command line arguments */ argv += get_video_args(argv, &w, &h, &bpp, &flags); /* Initialize SDL */ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); return(1); } /* Initialize the display, always use hardware palette */ screen = SDL_SetVideoMode(w, h, bpp, flags | SDL_HWPALETTE); if ( screen == NULL ) { fprintf(stderr, "Couldn't set %dx%d video mode: %s\n", w, h, SDL_GetError()); quit(1); } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL gamma test", "testgamma"); /* Set the desired gamma, if any */ gamma = 1.0f; if ( *argv ) { gamma = (float)atof(*argv); } if ( SDL_SetGamma(gamma, gamma, gamma) < 0 ) { fprintf(stderr, "Unable to set gamma: %s\n", SDL_GetError()); quit(1); } #if 0 /* This isn't supported. Integrating the gamma ramps isn't exact */ /* See what gamma was actually set */ float real[3]; if ( SDL_GetGamma(&real[0], &real[1], &real[2]) < 0 ) { printf("Couldn't get gamma: %s\n", SDL_GetError()); } else { printf("Set gamma values: R=%2.2f, G=%2.2f, B=%2.2f\n", real[0], real[1], real[2]); } #endif /* Do all the drawing work */ image = SDL_LoadBMP("sample.bmp"); if ( image ) { SDL_Rect dst; dst.x = (screen->w - image->w)/2; dst.y = (screen->h - image->h)/2; dst.w = image->w; dst.h = image->h; SDL_BlitSurface(image, NULL, screen, &dst); SDL_UpdateRects(screen, 1, &dst); } /* Wait a bit, handling events */ then = SDL_GetTicks(); timeout = (5*1000); #ifndef EMSCRIPTEN while ( (SDL_GetTicks()-then) < timeout ) { #else emscripten_set_main_loop(&main_loop, 0, 1); } void main_loop() { if ( (SDL_GetTicks()-then) < timeout ) { #endif SDL_Event event; while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_QUIT: /* Quit now */ timeout = 0; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_SPACE: /* Go longer.. */ timeout += (5*1000); break; case SDLK_UP: gamma += 0.2f; SDL_SetGamma(gamma, gamma, gamma); break; case SDLK_DOWN: gamma -= 0.2f; SDL_SetGamma(gamma, gamma, gamma); break; case SDLK_ESCAPE: timeout = 0; break; default: break; } break; } } } #ifdef EMSCRIPTEN else { #endif /* Perform a gamma flash to red using color ramps */ while ( gamma < 10.0 ) { /* Increase the red gamma and decrease everything else... */ gamma += 0.1f; CalculateGamma(gamma, red_ramp); CalculateGamma(1.0/gamma, ramp); SDL_SetGammaRamp(red_ramp, ramp, ramp); } /* Finish completely red */ memset(red_ramp, 255, sizeof(red_ramp)); memset(ramp, 0, sizeof(ramp)); SDL_SetGammaRamp(red_ramp, ramp, ramp); /* Now fade out to black */ for ( i=(red_ramp[0] >> 8); i >= 0; --i ) { memset(red_ramp, i, sizeof(red_ramp)); SDL_SetGammaRamp(red_ramp, NULL, NULL); } #ifndef EMSCRIPTEN SDL_Delay(1*1000); #else emscripten_pause_main_loop(); emscripten_async_call(&end_main, 0, 1*1000); } } void end_main() { #endif SDL_Quit(); #ifndef EMSCRIPTEN return(0); #else exit(0); #endif }
int main ( int argc, char *argv[] ) #endif { SDL_Surface *screen; int w, h; int desired_bpp; Uint32 video_flags; int start; #ifdef WIN32 int argc; char **argv; argv = __argv; argc = __argc; #endif /* Title */ fprintf (stderr,"SDL_rotozoom test\n"); /* Set default options and check command-line */ w = 640; h = 480; desired_bpp = 0; video_flags = 0; start = 1; while ( argc > 1 ) { if ( strcmp(argv[1], "-start") == 0 ) { if ( argv[2] && ((start = atoi(argv[2])) > 0) ) { argv += 2; argc -= 2; } else { fprintf(stderr, "The -start option requires an argument\n"); exit(1); } } else if ( strcmp(argv[1], "-width") == 0 ) { if ( argv[2] && ((w = atoi(argv[2])) > 0) ) { argv += 2; argc -= 2; } else { fprintf(stderr, "The -width option requires an argument\n"); exit(1); } } else if ( strcmp(argv[1], "-height") == 0 ) { if ( argv[2] && ((h = atoi(argv[2])) > 0) ) { argv += 2; argc -= 2; } else { fprintf(stderr, "The -height option requires an argument\n"); exit(1); } } else if ( strcmp(argv[1], "-bpp") == 0 ) { if ( argv[2] ) { desired_bpp = atoi(argv[2]); argv += 2; argc -= 2; } else { fprintf(stderr, "The -bpp option requires an argument\n"); exit(1); } } else if ( strcmp(argv[1], "-warp") == 0 ) { video_flags |= SDL_HWPALETTE; argv += 1; argc -= 1; } else if ( strcmp(argv[1], "-hw") == 0 ) { video_flags |= SDL_HWSURFACE; argv += 1; argc -= 1; } else if ( strcmp(argv[1], "-fullscreen") == 0 ) { video_flags |= SDL_FULLSCREEN; argv += 1; argc -= 1; } else if (( strcmp(argv[1], "-help") == 0 ) || (strcmp(argv[1], "--help") == 0)) { printf ("Usage:\n"); printf (" -start # Set starting test number (1=8bit, 3=24bit, 5=32bit)\n"); printf (" -width # Screen width (Default: %i)\n",w); printf (" -height # Screen height (Default: %i)\n",h); printf (" -bpp # Screen bpp\n"); printf (" -warp Enable hardware palette\n"); printf (" -hw Enable hardware surface\n"); printf (" -fullscreen Enable fullscreen mode\n"); } else break; } /* Force double buffering */ video_flags |= SDL_DOUBLEBUF; /* Initialize SDL */ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); /* Clean up on exit */ /* Initialize the display */ screen = SDL_SetVideoMode(w, h, desired_bpp, video_flags); if ( screen == NULL ) { fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n", w, h, desired_bpp, SDL_GetError()); exit(1); } /* Show some info */ printf("Set %dx%dx%d mode\n", screen->w, screen->h, screen->format->BitsPerPixel); printf("Video surface located in %s memory.\n", (screen->flags&SDL_HWSURFACE) ? "video" : "system"); /* Check for double buffering */ if ( screen->flags & SDL_DOUBLEBUF ) { printf("Double-buffering enabled - good!\n"); } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL_rotozoom shrink test", "shrink"); /* Do all the drawing work */ Draw (screen, start); return(0); }
int main(int argc, char ** argv) { int finp = 0,first = 1; SDL_Surface * menu = NULL; SDL_Surface * ecran = NULL; SDL_Rect position_menu; SDL_Event event; FSOUND_STREAM * musique = NULL; SDL_Init(SDL_INIT_VIDEO); TTF_Init(); FSOUND_Init(44100,32,0); ecran = SDL_SetVideoMode(800,800,32,SDL_HWSURFACE | SDL_DOUBLEBUF); if(ecran == NULL) exit(EXIT_FAILURE); SDL_WM_SetCaption("Prozet zz1",NULL); menu = IMG_Load("./dessin/menu.jpg"); if(menu == NULL) exit(EXIT_FAILURE); position_menu.x = 0; position_menu.y = 0; musique = FSOUND_Stream_Open("./son/jourdefoot.mp3",0,0,0); if(musique == NULL) exit(EXIT_FAILURE); while(finp == 0) { if(first == 1) { SDL_BlitSurface(menu,NULL,ecran,&position_menu); SDL_Flip(ecran); FSOUND_Stream_Play(FSOUND_FREE,musique); first = 0; } SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: finp = 1; break; case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) { if(event.button.x >= 250 && event.button.x <= 550) { if(event.button.y >= 300 && event.button.y <= 400) { FSOUND_Stream_Stop(musique); mode_solo(ecran); first = 1; } else { if(event.button.y >= 450 && event.button.y <= 550) { FSOUND_Stream_Stop(musique); mode_local_serveur(ecran); first = 1; } else { if(event.button.y >= 600 && event.button.y <= 700) { FSOUND_Stream_Stop(musique); mode_local_client(ecran); first = 1; } } } } } break; } } FSOUND_Stream_Stop(musique); FSOUND_Stream_Close(musique); FSOUND_Close(); SDL_FreeSurface(menu); SDL_FreeSurface(ecran); TTF_Quit(); SDL_Quit(); return(EXIT_SUCCESS); }
void ONScripter::variableEditMode( SDL_KeyboardEvent *event ) { int i; const char *var_name; char var_index[12]; switch ( event->keysym.sym ) { case SDLK_m: if ( variable_edit_mode != EDIT_SELECT_MODE ) return; variable_edit_mode = EDIT_MP3_VOLUME_MODE; variable_edit_num = music_volume; break; case SDLK_s: if ( variable_edit_mode != EDIT_SELECT_MODE ) return; variable_edit_mode = EDIT_SE_VOLUME_MODE; variable_edit_num = se_volume; break; case SDLK_v: if ( variable_edit_mode != EDIT_SELECT_MODE ) return; variable_edit_mode = EDIT_VOICE_VOLUME_MODE; variable_edit_num = voice_volume; break; case SDLK_n: if ( variable_edit_mode != EDIT_SELECT_MODE ) return; variable_edit_mode = EDIT_VARIABLE_INDEX_MODE; variable_edit_num = 0; break; case SDLK_9: case SDLK_KP9: variable_edit_num = variable_edit_num * 10 + 9; break; case SDLK_8: case SDLK_KP8: variable_edit_num = variable_edit_num * 10 + 8; break; case SDLK_7: case SDLK_KP7: variable_edit_num = variable_edit_num * 10 + 7; break; case SDLK_6: case SDLK_KP6: variable_edit_num = variable_edit_num * 10 + 6; break; case SDLK_5: case SDLK_KP5: variable_edit_num = variable_edit_num * 10 + 5; break; case SDLK_4: case SDLK_KP4: variable_edit_num = variable_edit_num * 10 + 4; break; case SDLK_3: case SDLK_KP3: variable_edit_num = variable_edit_num * 10 + 3; break; case SDLK_2: case SDLK_KP2: variable_edit_num = variable_edit_num * 10 + 2; break; case SDLK_1: case SDLK_KP1: variable_edit_num = variable_edit_num * 10 + 1; break; case SDLK_0: case SDLK_KP0: variable_edit_num = variable_edit_num * 10 + 0; break; case SDLK_MINUS: case SDLK_KP_MINUS: if ( variable_edit_mode == EDIT_VARIABLE_NUM_MODE && variable_edit_num == 0 ) variable_edit_sign = -1; break; case SDLK_BACKSPACE: if ( variable_edit_num ) variable_edit_num /= 10; else if ( variable_edit_sign == -1 ) variable_edit_sign = 1; break; case SDLK_RETURN: case SDLK_KP_ENTER: switch( variable_edit_mode ){ case EDIT_VARIABLE_INDEX_MODE: variable_edit_index = variable_edit_num; variable_edit_num = script_h.getVariableData(variable_edit_index).num; if ( variable_edit_num < 0 ){ variable_edit_num = -variable_edit_num; variable_edit_sign = -1; } else{ variable_edit_sign = 1; } break; case EDIT_VARIABLE_NUM_MODE: script_h.setNumVariable( variable_edit_index, variable_edit_sign * variable_edit_num ); break; case EDIT_MP3_VOLUME_MODE: music_volume = variable_edit_num; Mix_VolumeMusic( music_volume * MIX_MAX_VOLUME / 100 ); break; case EDIT_SE_VOLUME_MODE: se_volume = variable_edit_num; for ( i=1 ; i<ONS_MIX_CHANNELS ; i++ ) if ( wave_sample[i] ) Mix_Volume( i, se_volume * MIX_MAX_VOLUME / 100 ); if ( wave_sample[MIX_LOOPBGM_CHANNEL0] ) Mix_Volume( MIX_LOOPBGM_CHANNEL0, se_volume * MIX_MAX_VOLUME / 100 ); if ( wave_sample[MIX_LOOPBGM_CHANNEL1] ) Mix_Volume( MIX_LOOPBGM_CHANNEL1, se_volume * MIX_MAX_VOLUME / 100 ); break; case EDIT_VOICE_VOLUME_MODE: voice_volume = variable_edit_num; if ( wave_sample[0] ) Mix_Volume( 0, se_volume * MIX_MAX_VOLUME / 100 ); default: break; } if ( variable_edit_mode == EDIT_VARIABLE_INDEX_MODE ) variable_edit_mode = EDIT_VARIABLE_NUM_MODE; else variable_edit_mode = EDIT_SELECT_MODE; break; case SDLK_ESCAPE: if ( variable_edit_mode == EDIT_SELECT_MODE ){ variable_edit_mode = NOT_EDIT_MODE; SDL_WM_SetCaption( DEFAULT_WM_TITLE, DEFAULT_WM_ICON ); SDL_Delay( 100 ); SDL_WM_SetCaption( wm_title_string, wm_icon_string ); return; } variable_edit_mode = EDIT_SELECT_MODE; default: break; } if ( variable_edit_mode == EDIT_SELECT_MODE ){ sprintf( wm_edit_string, "%s%s", EDIT_MODE_PREFIX, EDIT_SELECT_STRING ); } else if ( variable_edit_mode == EDIT_VARIABLE_INDEX_MODE ) { sprintf( wm_edit_string, "%s%s%d", EDIT_MODE_PREFIX, "Variable Index? %", variable_edit_sign * variable_edit_num ); } else if ( variable_edit_mode >= EDIT_VARIABLE_NUM_MODE ){ int p=0; switch( variable_edit_mode ){ case EDIT_VARIABLE_NUM_MODE: sprintf( var_index, "%%%d", variable_edit_index ); var_name = var_index; p = script_h.getVariableData(variable_edit_index).num; break; case EDIT_MP3_VOLUME_MODE: var_name = "MP3 Volume"; p = music_volume; break; case EDIT_VOICE_VOLUME_MODE: var_name = "Voice Volume"; p = voice_volume; break; case EDIT_SE_VOLUME_MODE: var_name = "Sound effect Volume"; p = se_volume; break; default: var_name = ""; } sprintf( wm_edit_string, "%sCurrent %s=%d New value? %s%d", EDIT_MODE_PREFIX, var_name, p, (variable_edit_sign==1)?"":"-", variable_edit_num ); } SDL_WM_SetCaption( wm_edit_string, wm_icon_string ); }
void render_window() { game_config = GetGameConfig(); game_levels = GetGameLevels(); game_levels_count = GetGameLevelsCount(); arguments = GetArguments(); user_set = GetUserSettings(); int start_level = get_start_level(); save_dir_full = GetSaveDir(); cache_dir_full = GetCacheDir(); can_cache = (save_dir_full && cache_dir_full); //------------------------------------------------------------------------------ ApplyArguments(); const SDL_VideoInfo *video_info = SDL_GetVideoInfo(); if (user_set->geom_x > 0 && user_set->geom_y > 0) { disp_x = user_set->geom_x; disp_y = user_set->geom_y; } else { disp_x = video_info->current_w; disp_y = video_info->current_h; } int probe_bpp = (user_set->bpp == 0 ? video_info->vfmt->BitsPerPixel : user_set->bpp); disp_bpp = (probe_bpp == 32 ? probe_bpp : 16); bool rot = TransformGeom(); //------------------------------------------------------------------------------ #define BTN_SPACE_KOEF 4.5 int btn_side = disp_y / 7; int btn_space = btn_side / BTN_SPACE_KOEF; int btns_padded_width = btn_side * 4 + btn_space * 5; if (btns_padded_width > disp_x) { //btn_side = ( wnd_w - 5 * ( btn_side / BTN_SPACE_KOEF ) ) / 4 btn_side = (int)(disp_x / (4 + 5 / BTN_SPACE_KOEF)); btn_space = btn_side / BTN_SPACE_KOEF; } int btns_width = btn_side * 4 + btn_space * 3; int font_height = btn_side / 3; int font_padding = font_height / 2; //-- font and labels ----------------------------------------------------------- TTF_Font *font = TTF_OpenFont(DEFAULT_FONT_FILE, font_height); if (!font) { log_error("Can't load font '%s'. Exiting.", DEFAULT_FONT_FILE); return; } SDL_Surface *levelTextSurface = NULL; SDL_Rect levelTextLocation; levelTextLocation.y = font_padding; SDL_Color fontColor = {0}; #ifndef RGBSWAP fontColor.r = 231; fontColor.g = 190; fontColor.b = 114; #else //--enable-rgb-swap fontColor.r = 114; fontColor.g = 190; fontColor.b = 231; #endif /* Window initialization */ ingame = true; Uint32 sdl_flags = SDL_SWSURFACE; if (user_set->fullscreen_mode != FULLSCREEN_NONE) sdl_flags |= SDL_FULLSCREEN; SDL_Surface *disp = SDL_SetVideoMode(disp_x, disp_y, disp_bpp, sdl_flags); if (disp == NULL) { log_error("Can't set video mode %dx%dx%dbpp. Exiting.", disp_x, disp_y, disp_bpp); return; } screen = disp; SDL_Surface *gui_surface = disp; SDL_WM_SetCaption("Mokomaze", "Mokomaze"); /* Draw loading screen */ SDL_Color whiteColor = {0}; whiteColor.r = whiteColor.g = whiteColor.b = 255; SDL_Surface *titleSurface = TTF_RenderText_Blended(font, "Loading...", whiteColor); SDL_Rect title_rect; title_rect.x = (disp_x - titleSurface->w) / 2; title_rect.y = (disp_y - titleSurface->h) / 2; title_rect.w = titleSurface->w; title_rect.h = titleSurface->h; SDL_BlitSurface(titleSurface, NULL, screen, &title_rect); SDL_UpdateRect(screen, title_rect.x, title_rect.y, title_rect.w, title_rect.h); SDL_FreeSurface(titleSurface); //-- load pictures ------------------------------------------------------------- SDL_Surface *back_pic = LoadSvg(MDIR "prev-main.svg", btn_side, btn_side, false, false); SDL_Surface *forward_pic = LoadSvg(MDIR "next-main.svg", btn_side, btn_side, false, false); SDL_Surface *settings_pic = LoadSvg(MDIR "settings-main.svg", btn_side, btn_side, false, false); SDL_Surface *exit_pic = LoadSvg(MDIR "close-main.svg", btn_side, btn_side, false, false); SDL_Surface *back_i_pic = LoadSvg(MDIR "prev-grey.svg", btn_side, btn_side, false, false); SDL_Surface *forward_i_pic = LoadSvg(MDIR "next-grey.svg", btn_side, btn_side, false, false); SDL_Surface *back_p_pic = LoadSvg(MDIR "prev-light.svg", btn_side, btn_side, false, false); SDL_Surface *forward_p_pic = LoadSvg(MDIR "next-light.svg", btn_side, btn_side, false, false); int tmpx = (rot ? game_config.wnd_h : game_config.wnd_w); int tmpy = (rot ? game_config.wnd_w : game_config.wnd_h); desk_pic = LoadSvg(MDIR "desk.svg", tmpx, tmpy, rot, true); wall_pic = LoadSvg(MDIR "wall.svg", tmpx, tmpy, rot, true); int hole_d = game_config.hole_r * 2; fin_pic = LoadSvg(MDIR "openmoko.svg", hole_d, hole_d, rot, false); if (LoadImgErrors > 0) { log_error("Some images were not loaded. Exiting."); return; } //-- positions of buttons ------------------------------------------------------ SDL_Rect gui_rect_1, gui_rect_2, gui_rect_3, gui_rect_4; gui_rect_1.y = gui_rect_2.y = gui_rect_3.y = gui_rect_4.y = levelTextLocation.y + font_height + font_padding; gui_rect_1.x = (disp_x - btns_width) / 2; gui_rect_2.x = gui_rect_1.x + btn_side + btn_space; gui_rect_3.x = gui_rect_2.x + btn_side + btn_space; gui_rect_4.x = gui_rect_3.x + btn_side + btn_space; //-- for click detection ------------------------------------------------------- Box gui_box_1, gui_box_2, gui_box_3, gui_box_4; gui_box_1.x1 = gui_rect_1.x; gui_box_1.y1 = gui_rect_1.y; gui_box_1.x2 = gui_rect_1.x + btn_side; gui_box_1.y2 = gui_rect_1.y + btn_side; gui_box_2.x1 = gui_rect_2.x; gui_box_2.y1 = gui_rect_2.y; gui_box_2.x2 = gui_rect_2.x + btn_side; gui_box_2.y2 = gui_rect_2.y + btn_side; gui_box_3.x1 = gui_rect_3.x; gui_box_3.y1 = gui_rect_3.y; gui_box_3.x2 = gui_rect_3.x + btn_side; gui_box_3.y2 = gui_rect_3.y + btn_side; gui_box_4.x1 = gui_rect_4.x; gui_box_4.y1 = gui_rect_4.y; gui_box_4.x2 = gui_rect_4.x + btn_side; gui_box_4.y2 = gui_rect_4.y + btn_side; //create surface for rendering the level render_pic = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp); if (user_set->scrolling) screen = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp); if (user_set->fullscreen_mode != FULLSCREEN_NONE) SDL_ShowCursor(!ingame); desk_rect.x = 0; desk_rect.y = 0; desk_rect.w = game_config.wnd_w; desk_rect.h = game_config.wnd_h; SDL_Rect ball_rect; int disp_scroll_border = min(disp_x, disp_y) * 0.27; SDL_Rect screen_rect; screen_rect.x = 0; screen_rect.y = 0; screen_rect.w = disp_x; screen_rect.h = disp_y; SDL_Rect disp_rect; disp_rect = screen_rect; SDL_Color ballColor = {0}; ballColor.r = 255; ballColor.g = 127; ballColor.b = 0; User user_set_new = *user_set; bool video_set_modified = false; /* Settings window initialization */ settings_init(disp, font_height, user_set, &user_set_new); /* Render initialization */ InitRender(); /* Input system initialization */ input_get_dummy(&input); SetInput(); /* Vibro system initialization */ vibro_get_dummy(&vibro); SetVibro(); /* MazeCore initialization */ maze_init(); maze_set_config(game_config); maze_set_vibro_callback(BumpVibrate); maze_set_levels_data(game_levels, game_levels_count); cur_level = start_level; RenderLevel(); RedrawDesk(); maze_set_level(cur_level); ResetPrevPos(); SDL_Event event; bool done = false; bool redraw_all = true; bool ingame_changed = false; int prev_ticks = SDL_GetTicks(); Point mouse = {0}; //== Game Loop ================================================================= while (!done) { bool wasclick = false; bool show_settings = false; while (SDL_PollEvent(&event)) { bool btndown = false; bool btnesc = false; if (event.type == SDL_QUIT) { done = true; } else if (event.type == SDL_ACTIVEEVENT) { int g = event.active.gain; int s = event.active.state; if (ingame && !g && ((s & SDL_APPINPUTFOCUS) || (s & SDL_APPACTIVE))) { btndown = true; } } else if (event.type == SDL_MOUSEMOTION) { mouse.x = event.motion.x; mouse.y = event.motion.y; } else if (event.type == SDL_MOUSEBUTTONUP) { StopFastChange(); } else if (event.type == SDL_MOUSEBUTTONDOWN) { btndown = true; } else if (event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_q: case SDLK_ESCAPE: btnesc = true; case SDLK_SPACE: case SDLK_p: case SDLK_PAUSE: btndown = true; break; default: break; } } else if (event.type == SDL_KEYUP) { switch(event.key.keysym.sym) { case SDLK_q: case SDLK_ESCAPE: if( !wasclick || ingame || show_settings ) StopFastChange(); else done = true; break; case SDLK_SPACE: case SDLK_p: case SDLK_PAUSE: StopFastChange(); break; default: break; } } if (btndown) { if (!ingame) { if (inbox(mouse.x, mouse.y, gui_box_1) && !btnesc) { if (cur_level > 0) { SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1); SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h); ChangeLevel(cur_level-1, &redraw_all, &wasclick); fastchange_step = -10; StopFastChange(); fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL); } continue; } else if (inbox(mouse.x, mouse.y, gui_box_2) && !btnesc) { if (cur_level < game_levels_count - 1) { SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2); SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h); ChangeLevel(cur_level+1, &redraw_all, &wasclick); fastchange_step = +10; StopFastChange(); fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL); } continue; } else if (inbox(mouse.x, mouse.y, gui_box_3) && !btnesc) { show_settings = true; RedrawDesk(); redraw_all = true; wasclick = true; continue; } else if (inbox(mouse.x, mouse.y, gui_box_4) || btnesc) { done = true; continue; } } ingame_changed = true; } //if (btndown) } if (ingame_changed) { ingame = !ingame; if (!ingame) { wasclick = true; } else { RedrawDesk(); redraw_all = true; } if (user_set->fullscreen_mode == FULLSCREEN_INGAME) SDL_WM_ToggleFullScreen(disp); if (user_set->fullscreen_mode != FULLSCREEN_NONE) SDL_ShowCursor(!ingame); prev_ticks = SDL_GetTicks(); ingame_changed = false; } if ((!ingame) && (!wasclick) && (must_fastchange)) { int new_cur_level = cur_level + fastchange_dostep; clamp_max(new_cur_level, game_levels_count - 1); clamp_min(new_cur_level, 0); if (new_cur_level != cur_level) { if (fastchange_dostep < 0) { SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1); SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h); } else { SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2); SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h); } ChangeLevel(new_cur_level, &redraw_all, &wasclick); } must_fastchange = false; } if (!ingame && !wasclick) { SDL_Delay(user_set->frame_delay); continue; } //-- physics step -------------------------------------------------------------- int ticks = SDL_GetTicks(); int delta_ticks = ticks - prev_ticks; prev_ticks = ticks; clamp_min(delta_ticks, 1); clamp_max(delta_ticks, 1000 / 15); float acx = 0, acy = 0; input.read(&acx, &acy, NULL); if (input_cal_cycle) input_cal_cycle = (input_calibration_sample(&user_set->input_calibration_data, &acx, &acy, NULL) < MAX_CALIBRATION_SAMPLES); input_calibration_adjust(&user_set->input_calibration_data, &acx, &acy, NULL); maze_set_speed(user_set->ball_speed); maze_set_tilt(acx, acy, 0); GameState game_state = maze_step(delta_ticks); const dReal *R; int tk_px, tk_py, tk_pz; maze_get_ball(&tk_px, &tk_py, &tk_pz, &R); maze_get_animations(&keys_anim, &final_anim); //------------------------------------------------------------------------------ //restore the background ball_rect.w = game_config.ball_r * 2; ball_rect.h = game_config.ball_r * 2; // ball_rect.x = prev_px - game_config.ball_r; ball_rect.y = prev_py - game_config.ball_r; SDL_BlitSurface(render_pic, &ball_rect, screen, &ball_rect); UpdateBufAnimation(); DrawBall(tk_px, tk_py, tk_pz, R, ballColor); //update the screen if (!redraw_all && !user_set->scrolling) { int min_px, max_px; int min_py, max_py; if (prev_px <= tk_px) { min_px = prev_px; max_px = tk_px; } else { min_px = tk_px; max_px = prev_px; } if (prev_py <= tk_py) { min_py = prev_py; max_py = tk_py; } else { min_py = tk_py; max_py = prev_py; } min_px -= game_config.ball_r; max_px += game_config.ball_r; min_py -= game_config.ball_r; max_py += game_config.ball_r; clamp_min(min_px, 0); clamp_max(max_px, game_config.wnd_w - 1); clamp_min(min_py, 0); clamp_max(max_py, game_config.wnd_h - 1); SDL_UpdateRect(screen, min_px, min_py, max_px - min_px, max_py - min_py); UpdateScreenAnimation(); } if (user_set->scrolling) { clamp_min(screen_rect.x, tk_px - disp_x + disp_scroll_border); clamp_max(screen_rect.x, tk_px - disp_scroll_border); clamp_min(screen_rect.y, tk_py - disp_y + disp_scroll_border); clamp_max(screen_rect.y, tk_py - disp_scroll_border); clamp(screen_rect.x, 0, game_config.wnd_w - disp_x); clamp(screen_rect.y, 0, game_config.wnd_h - disp_y); SDL_BlitSurface(screen, &screen_rect, disp, &disp_rect); } prev_px = tk_px; prev_py = tk_py; //-- GUI ----------------------------------------------------------------------- if (wasclick && !ingame && !show_settings) { char txt[32]; sprintf(txt, "Level %d/%d", cur_level + 1, game_levels_count); SDL_FreeSurface(levelTextSurface); levelTextSurface = TTF_RenderText_Blended(font, txt, fontColor); levelTextLocation.x = (disp_x - levelTextSurface->w) / 2; SDL_BlitSurface(levelTextSurface, NULL, gui_surface, &levelTextLocation); if (cur_level > 0) SDL_BlitSurface(back_pic, NULL, gui_surface, &gui_rect_1); else SDL_BlitSurface(back_i_pic, NULL, gui_surface, &gui_rect_1); if (cur_level < game_levels_count - 1) SDL_BlitSurface(forward_pic, NULL, gui_surface, &gui_rect_2); else SDL_BlitSurface(forward_i_pic, NULL, gui_surface, &gui_rect_2); SDL_BlitSurface(settings_pic, NULL, gui_surface, &gui_rect_3); SDL_BlitSurface(exit_pic, NULL, gui_surface, &gui_rect_4); redraw_all = true; } //------------------------------------------------------------------------------ //update the whole screen if needed if (user_set->scrolling) { SDL_Flip(disp); } else if (redraw_all) { SDL_Flip(screen); } redraw_all = false; if (show_settings) { bool _video_set_modified = false; bool _input_set_modified = false; bool _vibro_set_modified = false; settings_show(&input_cal_cycle, &_video_set_modified, &_input_set_modified, &_vibro_set_modified); if (input_cal_cycle) input_calibration_reset(); if (_video_set_modified) video_set_modified = true; if (_input_set_modified) SetInput(); if (_vibro_set_modified) SetVibro(); SDL_GetMouseState(&mouse.x, &mouse.y); ingame_changed = true; } switch (game_state) { case GAME_STATE_FAILED: RedrawDesk(); maze_restart_level(); ResetPrevPos(); redraw_all = true; break; case GAME_STATE_SAVED: RedrawDesk(); maze_reload_level(); ResetPrevPos(); redraw_all = true; break; case GAME_STATE_WIN: if (++cur_level >= game_levels_count) cur_level=0; RenderLevel(); RedrawDesk(); maze_set_level(cur_level); ResetPrevPos(); redraw_all = true; break; default: break; } SDL_Delay(user_set->frame_delay); } //============================================================================== if (video_set_modified) { user_set->scrolling = user_set_new.scrolling; user_set->geom_x = user_set_new.geom_x; user_set->geom_y = user_set_new.geom_y; user_set->bpp = user_set_new.bpp; user_set->fullscreen_mode = user_set_new.fullscreen_mode; user_set->frame_delay = user_set_new.frame_delay; } user_set->level = cur_level + 1; SaveUserSettings(); settings_shutdown(); SDL_FreeSurface(levelTextSurface); TTF_CloseFont(font); vibro.shutdown(); input.shutdown(); }
bool ONScripter::keyPressEvent( SDL_KeyboardEvent *event ) { current_button_state.button = 0; current_button_state.down_flag = false; if ( automode_flag ){ automode_flag = false; return false; } if ( event->type == SDL_KEYUP ){ if ( variable_edit_mode ){ variableEditMode( event ); return false; } if ( edit_flag && event->keysym.sym == SDLK_z ){ variable_edit_mode = EDIT_SELECT_MODE; variable_edit_sign = 1; variable_edit_num = 0; sprintf( wm_edit_string, "%s%s", EDIT_MODE_PREFIX, EDIT_SELECT_STRING ); SDL_WM_SetCaption( wm_edit_string, wm_icon_string ); } } if (event->type == SDL_KEYUP) skip_mode &= ~SKIP_NORMAL; if ( shift_pressed_status && event->keysym.sym == SDLK_q && current_mode == NORMAL_MODE ){ endCommand(); } if ( (trap_mode & TRAP_LEFT_CLICK) && (event->keysym.sym == SDLK_RETURN || event->keysym.sym == SDLK_KP_ENTER || event->keysym.sym == SDLK_SPACE ) ){ if (trapHandler()) return true; } else if ( (trap_mode & TRAP_RIGHT_CLICK) && (event->keysym.sym == SDLK_ESCAPE) ){ if (trapHandler()) return true; } if ( event_mode & WAIT_BUTTON_MODE && (((event->type == SDL_KEYUP || btndown_flag) && ((!getenter_flag && event->keysym.sym == SDLK_RETURN) || (!getenter_flag && event->keysym.sym == SDLK_KP_ENTER))) || ((spclclk_flag || !useescspc_flag) && event->keysym.sym == SDLK_SPACE)) ){ if ( event->keysym.sym == SDLK_RETURN || event->keysym.sym == SDLK_KP_ENTER || (spclclk_flag && event->keysym.sym == SDLK_SPACE) ){ current_button_state.button = current_over_button; if (current_over_button == 0) sprintf(current_button_state.str, "RETURN"); else sprintf(current_button_state.str, "S%d", current_over_button); if ( event->type == SDL_KEYDOWN ) current_button_state.down_flag = true; } else{ current_button_state.button = 0; sprintf(current_button_state.str, "SPACE"); } playClickVoice(); stopAnimation( clickstr_state ); return true; } if ( event->type == SDL_KEYDOWN ) return false; if ( ( event_mode & (WAIT_INPUT_MODE | WAIT_BUTTON_MODE) ) && ( autoclick_time == 0 || (event_mode & WAIT_BUTTON_MODE)) ){ if ( !useescspc_flag && event->keysym.sym == SDLK_ESCAPE){ current_button_state.button = -1; sprintf(current_button_state.str, "RCLICK"); if (rmode_flag && event_mode & WAIT_TEXT_MODE){ if (root_rmenu_link.next) system_menu_mode = SYSTEM_MENU; else system_menu_mode = SYSTEM_WINDOWERASE; } } else if ( useescspc_flag && event->keysym.sym == SDLK_ESCAPE ){ current_button_state.button = -10; } else if ( !spclclk_flag && useescspc_flag && event->keysym.sym == SDLK_SPACE ){ current_button_state.button = -11; } else if (((!getcursor_flag && event->keysym.sym == SDLK_LEFT) || event->keysym.sym == SDLK_h) && (event_mode & WAIT_TEXT_MODE || (usewheel_flag && !getcursor_flag && event_mode & WAIT_BUTTON_MODE) || system_menu_mode == SYSTEM_LOOKBACK)){ current_button_state.button = -2; if (event_mode & WAIT_TEXT_MODE) system_menu_mode = SYSTEM_LOOKBACK; } else if (((!getcursor_flag && event->keysym.sym == SDLK_RIGHT) || event->keysym.sym == SDLK_l) && ((enable_wheeldown_advance_flag && event_mode & WAIT_TEXT_MODE) || (usewheel_flag && event_mode & WAIT_BUTTON_MODE) || system_menu_mode == SYSTEM_LOOKBACK)){ if (event_mode & WAIT_TEXT_MODE) current_button_state.button = 0; else current_button_state.button = -3; } else if (((!getcursor_flag && event->keysym.sym == SDLK_UP) || event->keysym.sym == SDLK_k || event->keysym.sym == SDLK_p) && event_mode & WAIT_BUTTON_MODE){ shiftCursorOnButton(1); return false; } else if (((!getcursor_flag && event->keysym.sym == SDLK_DOWN) || event->keysym.sym == SDLK_j || event->keysym.sym == SDLK_n) && event_mode & WAIT_BUTTON_MODE){ shiftCursorOnButton(-1); return false; } else if ( getpageup_flag && event->keysym.sym == SDLK_PAGEUP ){ current_button_state.button = -12; sprintf(current_button_state.str, "PAGEUP"); } else if ( getpagedown_flag && event->keysym.sym == SDLK_PAGEDOWN ){ current_button_state.button = -13; sprintf(current_button_state.str, "PAGEDOWN"); } else if ( (getenter_flag && event->keysym.sym == SDLK_RETURN) || (getenter_flag && event->keysym.sym == SDLK_KP_ENTER) ){ current_button_state.button = -19; } else if ( gettab_flag && event->keysym.sym == SDLK_TAB ){ current_button_state.button = -20; } else if ( getcursor_flag && event->keysym.sym == SDLK_UP ){ current_button_state.button = -40; sprintf(current_button_state.str, "UP"); } else if ( getcursor_flag && event->keysym.sym == SDLK_RIGHT ){ current_button_state.button = -41; sprintf(current_button_state.str, "RIGHT"); } else if ( getcursor_flag && event->keysym.sym == SDLK_DOWN ){ current_button_state.button = -42; sprintf(current_button_state.str, "DOWN"); } else if ( getcursor_flag && event->keysym.sym == SDLK_LEFT ){ current_button_state.button = -43; sprintf(current_button_state.str, "LEFT"); } else if ( getinsert_flag && event->keysym.sym == SDLK_INSERT ){ current_button_state.button = -50; } else if ( getzxc_flag && event->keysym.sym == SDLK_z ){ current_button_state.button = -51; } else if ( getzxc_flag && event->keysym.sym == SDLK_x ){ current_button_state.button = -52; } else if ( getzxc_flag && event->keysym.sym == SDLK_c ){ current_button_state.button = -53; } else if ( getfunction_flag && event->keysym.sym >= SDLK_F1 && event->keysym.sym <= SDLK_F12 ){ current_button_state.button = -21-(event->keysym.sym - SDLK_F1); sprintf(current_button_state.str, "F%d", event->keysym.sym - SDLK_F1+1); } else if ( bexec_flag && event->keysym.sym >= SDLK_0 && event->keysym.sym <= SDLK_9 ){ current_button_state.button = -1; // dummy sprintf(current_button_state.str, "%d", event->keysym.sym - SDLK_0); } else if ( bexec_flag && event->keysym.sym >= SDLK_a && event->keysym.sym <= SDLK_z ){ current_button_state.button = -1; // dummy sprintf(current_button_state.str, "%c", 'A' + event->keysym.sym - SDLK_a); } else if ( bexec_flag && (event->keysym.sym == SDLK_RSHIFT || event->keysym.sym == SDLK_LSHIFT) ){ current_button_state.button = -1; // dummy sprintf(current_button_state.str, "SHIFT"); } if ( current_button_state.button != 0 ){ stopAnimation( clickstr_state ); return true; } } if ( event_mode & WAIT_INPUT_MODE && ( autoclick_time == 0 || (event_mode & WAIT_BUTTON_MODE)) ){ if (event->keysym.sym == SDLK_RETURN || event->keysym.sym == SDLK_KP_ENTER || event->keysym.sym == SDLK_SPACE ){ if (!(event_mode & WAIT_TEXT_MODE)) skip_mode |= SKIP_TO_EOL; playClickVoice(); stopAnimation( clickstr_state ); return true; } } if ( event_mode & WAIT_INPUT_MODE ){ if (event->keysym.sym == SDLK_s && !automode_flag ){ skip_mode |= SKIP_NORMAL; printf("toggle skip to true\n"); stopAnimation( clickstr_state ); return true; } else if (event->keysym.sym == SDLK_o){ if (skip_mode & SKIP_TO_EOP) skip_mode &= ~SKIP_TO_EOP; else skip_mode |= SKIP_TO_EOP; printf("toggle draw one page flag to %s\n", (skip_mode & SKIP_TO_EOP?"true":"false") ); if ( skip_mode & SKIP_TO_EOP ){ stopAnimation( clickstr_state ); return true; } } else if ( event->keysym.sym == SDLK_a && mode_ext_flag && !automode_flag ){ automode_flag = true; skip_mode &= ~SKIP_NORMAL; printf("change to automode\n"); stopAnimation( clickstr_state ); return true; } else if ( event->keysym.sym == SDLK_0 ){ if (++text_speed_no > 2) text_speed_no = 0; sentence_font.wait_time = -1; } else if ( event->keysym.sym == SDLK_1 ){ text_speed_no = 0; sentence_font.wait_time = -1; } else if ( event->keysym.sym == SDLK_2 ){ text_speed_no = 1; sentence_font.wait_time = -1; } else if ( event->keysym.sym == SDLK_3 ){ text_speed_no = 2; sentence_font.wait_time = -1; } } if ( event_mode & ( WAIT_INPUT_MODE | WAIT_BUTTON_MODE ) ){ if ( event->keysym.sym == SDLK_f ){ if ( fullscreen_mode ) menu_windowCommand(); else menu_fullCommand(); } } return false; }
/*** Función inicializadora de SDL y OpenGL ***/ GLboolean InitOpenGL(int width, int height, // Dimensiones de la ventana int bpp, // Profundidad int depth, // Z-buffer GLboolean fullscreen) // Fullscreen? { /* Inicialización de SDL */ if( SDL_Init( SDL_INIT_VIDEO ) != 0 ) { Error_SDL( "Error initializing SDL" ); return GL_FALSE; } /* Pongo el fondo en 32 bits */ if( bpp == 32 ) { SDL_GL_SetAttribute( SDL_GL_RED_SIZE , 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE , 8 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); } else if( bpp == 16 ) // 16 bits { SDL_GL_SetAttribute( SDL_GL_RED_SIZE , 4 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 4 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE , 4 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 4 ); } /* Framebuffer */ SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, bpp ); /* Z-buffer */ SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, depth ); /* Stencil buffer */ SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); /* Habilito el doble-buffering de OpengGL */ SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* Creo la ventana con soporte OpenGL */ if( SDL_SetVideoMode( width, height, bpp, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0) ) == NULL ) { Error_SDL( "Could not init OpenGL" ); return GL_FALSE; } /* Título de la ventana */ SDL_WM_SetCaption( "OpenGL", "OpenGL" ); /* Mensajes de Input directo a la aplicación */ SDL_WM_GrabInput( SDL_GRAB_ON ); /* Deshabilito la repetición del teclado */ SDL_EnableKeyRepeat( 0, SDL_DEFAULT_REPEAT_INTERVAL ); /* Inicializo los número aleatorios */ srand( time(NULL) ); return GL_TRUE; }
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); }
void RenderManagerGL2D::init(int xResolution, int yResolution, bool fullscreen) { mCurrentFlags.insert(GL_DEPTH_TEST); mCurrentFlags.insert(GL_MULTISAMPLE); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); Uint32 screenFlags = SDL_OPENGL; if (fullscreen) screenFlags |= SDL_FULLSCREEN; SDL_WM_SetCaption(AppTitle, ""); SDL_WM_SetIcon(SDL_LoadBMP("data/Icon.bmp"), NULL); SDL_SetVideoMode(xResolution, yResolution, 0, screenFlags); SDL_ShowCursor(0); glDisable(GL_MULTISAMPLE); mLeftBlobColor = Color(255, 0, 0); mRightBlobColor = Color(0, 255, 0); SDL_Surface* bgSurface = loadSurface("backgrounds/strand2.bmp"); BufferedImage* bgBufImage = new BufferedImage; bgBufImage->w = getNextPOT(bgSurface->w); bgBufImage->h = getNextPOT(bgSurface->h); bgBufImage->glHandle = loadTexture(bgSurface, false); mBackground = bgBufImage->glHandle; mImageMap["background"] = bgBufImage; mBallShadow = loadTexture(loadSurface("gfx/schball.bmp"), false); mScroll = loadTexture(loadSurface("gfx/scrollbar.bmp"), false); for (int i = 1; i <= 16; ++i) { char filename[64]; sprintf(filename, "gfx/ball%02d.bmp", i); GLuint ballImage = loadTexture(loadSurface(filename), false); mBall.push_back(ballImage); } for (int i = 1; i <= 5; ++i) { char filename[64]; sprintf(filename, "gfx/blobbym%d.bmp", i); GLuint blobImage = loadTexture(loadSurface(filename), false); mBlob.push_back(blobImage); sprintf(filename, "gfx/blobbym%d.bmp", i); GLuint blobSpecular = loadTexture(loadSurface(filename), true); mBlobSpecular.push_back(blobSpecular); sprintf(filename, "gfx/sch1%d.bmp", i); GLuint blobShadow = loadTexture(loadSurface(filename), false); mBlobShadow.push_back(blobShadow); } // create text base textures SDL_Surface* textbase = createEmptySurface(2048, 32); SDL_Surface* hltextbase = createEmptySurface(2048, 32); SDL_Surface* smalltextbase = createEmptySurface(1024, 16); SDL_Surface* hlsmalltextbase = createEmptySurface(1024, 16); int x = 0; int sx = 0; for (int i = 0; i <= 53; ++i) { char filename[64], filename2[64]; sprintf(filename, "gfx/font%02d.bmp", i); sprintf(filename2, "gfx/font_small/font%02d.bmp", i); SDL_Surface* fontSurface = loadSurface(filename); SDL_Surface* fontSurface2 = loadSurface(filename2); GLuint newFont = loadTexture(loadSurface(filename), false); GLuint newFont2 = loadTexture(loadSurface(filename2), false); SDL_Surface* highlight = highlightSurface(fontSurface, 60); SDL_Surface* highlight2 = highlightSurface(fontSurface2, 60); SDL_FreeSurface(fontSurface); SDL_FreeSurface(fontSurface2); fontSurface = loadSurface(filename); fontSurface2 = loadSurface(filename2); SDL_Rect r = {x, 0, fontSurface->w, fontSurface->h}; SDL_BlitSurface(fontSurface, 0, textbase, &r); SDL_BlitSurface(highlight, 0, hltextbase, &r); r = {sx, 0, fontSurface2->w, fontSurface2->h}; SDL_BlitSurface(fontSurface2, 0, smalltextbase, &r); SDL_BlitSurface(highlight2, 0, hlsmalltextbase, &r); //GLuint ballImage = loadTexture(sf, false); //mBall.push_back(ballImage); Texture s = Texture(0, x, 0, fontSurface->w, fontSurface->h, 2048, 32); mFont.push_back(s); mHighlightFont.push_back(s); s = Texture(0, sx, 0, fontSurface2->w, fontSurface2->h, 1024, 16); //mFont.push_back(newFont); //mHighlightFont.push_back(loadTexture(highlight, false)); mSmallFont.push_back( s ); mHighlightSmallFont.push_back( s ); x += fontSurface->w; sx += fontSurface2->w; SDL_FreeSurface(fontSurface); SDL_FreeSurface(fontSurface2); } GLuint texture = loadTexture(textbase, false); GLuint hltexture = loadTexture(hltextbase, false); GLuint smalltexture = loadTexture(smalltextbase, false); GLuint hlsmalltexture = loadTexture(hlsmalltextbase, false); for (int i = 0; i < mFont.size(); ++i) { mFont[i].texture = texture; mHighlightFont[i].texture = hltexture; mSmallFont[i].texture = smalltexture; mHighlightSmallFont[i].texture = hlsmalltexture; } mParticle = loadTexture(loadSurface("gfx/blood.bmp"), false); glViewport(0, 0, xResolution, yResolution); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 800, 600, 0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearDepth(1.0); glDepthFunc(GL_LEQUAL); glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glAlphaFunc(GL_GREATER, 0.5); glEnable(GL_ALPHA_TEST); }
/*************************** GraphicsInit: Initializes the graphic system ****************************/ void GraphicsInit(void) { const SDL_VideoInfo* video_info = SDL_GetVideoInfo(); Uint32 surface_mode = 0; DEBUGCODE { fprintf(stderr, "Entering GraphicsInit()\n"); }; //Set application's icon: seticon(); //Set caption: SDL_WM_SetCaption("Tux Typing", "TuxType"); if (video_info->hw_available) { surface_mode = SDL_HWSURFACE; LOG("HW mode\n"); } else { surface_mode = SDL_SWSURFACE; LOG("SW mode\n"); } // Determine the current resolution: this will be used as the // fullscreen resolution, if the user wants fullscreen. DEBUGCODE { fprintf(stderr, "Current resolution: w %d, h %d.\n", video_info->current_w, video_info->current_h); } /* For fullscreen, we try to use current resolution from OS: */ fs_res_x = video_info->current_w; fs_res_y = video_info->current_h; if (settings.fullscreen == 1) { screen = SDL_SetVideoMode(fs_res_x, fs_res_y, BPP, SDL_FULLSCREEN | surface_mode); if (screen == NULL) { fprintf(stderr, "\nWarning: I could not open the display in fullscreen mode.\n" "The Simple DirectMedia error that occured was:\n" "%s\n\n", SDL_GetError()); settings.fullscreen = 0; } } /* Either fullscreen not requested, or couldn't get fullscreen in SDL: */ if (settings.fullscreen == 0) { screen = SDL_SetVideoMode(RES_X, RES_Y, BPP, surface_mode); } /* Failed to get a usable screen - must bail out! */ if (screen == NULL) { fprintf(stderr, "\nError: I could not open the display.\n" "The Simple DirectMedia error that occured was:\n" "%s\n\n", SDL_GetError()); exit(2); } InitBlitQueue(); DEBUGCODE { video_info = SDL_GetVideoInfo(); fprintf(stderr, "-SDL VidMode successfully set to %ix%ix%i\n", video_info->current_w, video_info->current_h, video_info->vfmt->BitsPerPixel); } LOG( "GraphicsInit():END\n" ); }
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #else int main(int argc, char** argv) { #endif SDL_Surface *screen_sfc; F1SpiritApp *game; KEYBOARDSTATE *k; int time, act_time; SDL_Event event; bool quit = false; bool need_to_redraw = true; #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Application started\n"); #endif #ifdef HAVE_GLES fullscreen = true; #endif screen_sfc = initialization((fullscreen ? SDL_FULLSCREEN : 0)); if (screen_sfc == 0) return 0; k = new KEYBOARDSTATE(); game = new F1SpiritApp(); #if 0//ndef HAVE_GLES // why recreating the context ??? if (fullscreen) { #ifdef HAVE_GLES EGL_Close(); screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, (fullscreen ? SDL_FULLSCREEN : 0)); EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #else screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); #endif SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; #ifndef HAVE_GLES SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #endif } #endif time = init_time = SDL_GetTicks(); IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG); while (!quit) { while ( SDL_PollEvent( &event ) ) { switch ( event.type ) { /* Keyboard event */ case SDL_KEYDOWN: #ifdef __APPLE__ if (event.key.keysym.sym == SDLK_q) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers &KMOD_META) != 0) { quit = true; } } #else if (event.key.keysym.sym == SDLK_F12) { quit = true; } #endif if (event.key.keysym.sym == SDLK_F10) { game->save_configuration("f1spirit.cfg"); game->load_configuration("f1spirit.cfg"); } #ifdef _WIN32 if (event.key.keysym.sym == SDLK_F4) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) quit = true; } #endif #ifdef __APPLE__ if (event.key.keysym.sym == SDLK_f) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_META) != 0) { /* Toggle FULLSCREEN mode: */ if (fullscreen) fullscreen = false; else fullscreen = true; screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); } } #else if (event.key.keysym.sym == SDLK_RETURN) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) { /* Toggle FULLSCREEN mode: */ if (fullscreen) fullscreen = false; else fullscreen = true; #ifndef HAVE_GLES #ifdef HAVE_GLES EGL_Close(); screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); #else screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0)); #endif calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y); SDL_WM_SetCaption(application_name, 0); SDL_ShowCursor(SDL_DISABLE); reload_textures++; #ifndef HAVE_GLES SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #endif #endif } } #endif if (event.key.keysym.sym == SDLK_f) { SDLMod modifiers; modifiers = SDL_GetModState(); if ((modifiers&KMOD_ALT) != 0) { /* toggle FPS mode: */ if (show_fps) show_fps = false; else show_fps = true; } } /* Keyboard event */ SDL_keysym *ks; ks = new SDL_keysym(); *ks = event.key.keysym; k->keyevents.Add(ks); break; /* SDL_QUIT event (window close) */ case SDL_QUIT: quit = true; break; } } act_time = SDL_GetTicks(); if (act_time - time >= REDRAWING_PERIOD) { int max_frame_step = 10; /* frames_per_sec_tmp+=1; if ((act_time-init_time)>=1000) { frames_per_sec=frames_per_sec_tmp; frames_per_sec_tmp=0; init_time=act_time; } // if */ // On PANDORA, let's target 25 fps... int min_frame=1; #ifdef PANDORA min_frame=2; #endif do { time += REDRAWING_PERIOD; if ((act_time - time) > 10*REDRAWING_PERIOD) time = act_time; /* cycle */ k->cycle(); if (!game->cycle(k)) quit = true; need_to_redraw = true; k->keyevents.Delete(); act_time = SDL_GetTicks(); max_frame_step--; min_frame--; } while (((act_time - time >= REDRAWING_PERIOD) && (max_frame_step > 0)) || (min_frame > 0)); } /* Redraw */ if (need_to_redraw) { game->draw(); need_to_redraw = false; frames_per_sec_tmp += 1; } if ((act_time - init_time) >= 1000) { frames_per_sec = frames_per_sec_tmp; frames_per_sec_tmp = 0; init_time = act_time; } #ifndef PANDORA SDL_Delay(1); #endif } delete k; k = 0; delete game; game = 0; Stop_playback(); finalization(); #ifdef F1SPIRIT_DEBUG_MESSAGES output_debug_message("Application finished\n"); close_debug_messages(); #endif return 0; } /* main */
int main() { if(SDL_Init(SDL_INIT_VIDEO == -1)) { system("zenity --error --text=\"Could not load SDL\""); Debug::logger->message("Error: Could not load SDL"); return 1; } if(TTF_Init() == -1) { system("zenity --error --text=\"Could not load SDL_TTF\""); Debug::logger->message("Error: Could not load SDL_TTF"); return 1; } screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE); SDL_WM_SetCaption("fps - 00", NULL); srand(time(NULL)); camera.x = 0; camera.y = 0; camera.w = SCREEN_WIDTH; camera.h = SCREEN_HEIGHT; errorTexture = LoadImage("../Data/Media/error.png"); Text::LoadFonts(); Game* game = NULL; MainMenu* menu = new MainMenu; bool menuRunning = true; while(menuRunning) { switch(menu->Run()) { case mainMenuNewGame: delete menu; game = new Game; switch(game->Run("save")) { case gameMainMenu: menu = new MainMenu; break; case gameQuitGame: menuRunning = false; break; } delete game; break; case mainMenuLoadGame: break; case mainMenuOptions: break; case mainMenuExitGame: menuRunning = false; delete menu; break; } } //stringstream caption; //caption << "Unuk - FPS: " << fps; //SDL_WM_SetCaption(caption.str().c_str(), NULL); // Clean up after ourselves. Text::FreeFonts(); SDL_FreeSurface(screen); SDL_FreeSurface(errorTexture); SDL_Quit(); TTF_Quit(); return 0; }
int main(int argc, char **argv) { ros::init(argc, argv, "keyboard_control"); ros::NodeHandle n; g_KeyboardStatesPub = n.advertise<keyboard_control::KeyboardStates>("/keyboard_control/KeyboardStates", 1); SDL_Surface *screen; SDL_Event event; if (SDL_Init(SDL_INIT_VIDEO) < 0) return 1; if (!(screen = SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE))) { SDL_Quit(); printf("SDL_SetVideoMode failed to open window\n"); return 1; } SDL_WM_SetCaption("KeyboardSates", "KeyboardStates"); bool quit = false; ros::Rate loop_rate(30); // frequency while (ros::ok() && !quit) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_KEYDOWN: case SDL_KEYUP: { if (event.key.keysym.sym == SDLK_LEFT) g_KeyboardStatesMsg.bLeftArrow = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_RIGHT) g_KeyboardStatesMsg.bRightArrow = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_UP) g_KeyboardStatesMsg.bUpArrow = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_DOWN) g_KeyboardStatesMsg.bDownArrow = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_0) g_KeyboardStatesMsg.b0 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_1) g_KeyboardStatesMsg.b1 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_2) g_KeyboardStatesMsg.b2 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_3) g_KeyboardStatesMsg.b3 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_4) g_KeyboardStatesMsg.b4 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_5) g_KeyboardStatesMsg.b5 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_6) g_KeyboardStatesMsg.b6 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_7) g_KeyboardStatesMsg.b7 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_8) g_KeyboardStatesMsg.b8 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_9) g_KeyboardStatesMsg.b9 = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_a) g_KeyboardStatesMsg.bA = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_b) g_KeyboardStatesMsg.bB = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_c) g_KeyboardStatesMsg.bC = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_d) g_KeyboardStatesMsg.bD = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_e) g_KeyboardStatesMsg.bE = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_f) g_KeyboardStatesMsg.bF = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_g) g_KeyboardStatesMsg.bG = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_h) g_KeyboardStatesMsg.bH = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_i) g_KeyboardStatesMsg.bI = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_j) g_KeyboardStatesMsg.bJ = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_k) g_KeyboardStatesMsg.bK = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_l) g_KeyboardStatesMsg.bL = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_m) g_KeyboardStatesMsg.bM = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_n) g_KeyboardStatesMsg.bN = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_o) g_KeyboardStatesMsg.bO = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_p) g_KeyboardStatesMsg.bP = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_q) g_KeyboardStatesMsg.bQ = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_r) g_KeyboardStatesMsg.bR = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_s) g_KeyboardStatesMsg.bS = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_t) g_KeyboardStatesMsg.bT = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_u) g_KeyboardStatesMsg.bU = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_v) g_KeyboardStatesMsg.bV = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_w) g_KeyboardStatesMsg.bW = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_x) g_KeyboardStatesMsg.bX = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_y) g_KeyboardStatesMsg.bY = (event.type == SDL_KEYDOWN); if (event.key.keysym.sym == SDLK_z) g_KeyboardStatesMsg.bZ = (event.type == SDL_KEYDOWN); g_KeyboardStatesPub.publish(g_KeyboardStatesMsg); break; } } } loop_rate.sleep(); // Sleep for 10 ms ros::spinOnce(); // Process ros messages } SDL_Quit(); return EXIT_SUCCESS; }
/* Initialises the video subsystem. Note: dynamic resolution change is not supported. */ int InitVideo(void) { char title[32]; SDL_Surface *new_screen = NULL; int sdl_flags = 0; int w, h = 0; int rw, rh; sdl_flags |= SDL_HWPALETTE; sdl_flags |= SDL_SWSURFACE; if (Hint(HINT_FULLSCREEN)) sdl_flags |= SDL_FULLSCREEN; if (screen == NULL) { rw = w = Hint(HINT_WIDTH); rh = h = Hint(HINT_HEIGHT); } else { /* We do this because the game dies horribly if you try to dynamically change the _virtual_ resolution */ rw = w = screen_w; rh = h = screen_h; } if (Hint(HINT_SCALEFACTOR) > 1) { rw *= Hint(HINT_SCALEFACTOR); rh *= Hint(HINT_SCALEFACTOR); } if (!Hint(HINT_FORCEMODE)) { if (!ValidMode(w, h)) { printf("!!! Invalid Video Mode %dx%d\n", w, h); return -1; } } else { printf("\n"); printf(" BIG FAT WARNING: If this blows up in your face,\n"); printf(" and mutilates your cat, please don't cry.\n"); printf("\n"); } printf("Window dimensions:\t%dx%d\n", rw, rh); new_screen = SDL_SetVideoMode(rw, rh, 8, sdl_flags); if (new_screen == NULL) { printf("ERROR: InitVideo: %s\n", SDL_GetError() ); return -1; } if (screen == NULL) { /* only do this the first time */ debug(D_NORMAL, "setting caption and icon...\n"); sprintf(title, "C-Dogs %s [Port %s]", CDOGS_VERSION, CDOGS_SDL_VERSION); SDL_WM_SetCaption(title, NULL); SDL_WM_SetIcon(SDL_LoadBMP(GetDataFilePath("cdogs_icon.bmp")), NULL); SDL_ShowCursor(SDL_DISABLE); } else { debug(D_NORMAL, "Changed video mode...\n"); } if (screen == NULL) { screen_w = Hint(HINT_WIDTH); screen_h = Hint(HINT_HEIGHT); } screen = new_screen; SetClip(0, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1); debug(D_NORMAL, "Internal dimensions:\t%dx%d\n", SCREEN_WIDTH, SCREEN_HEIGHT); SetPalette(gPalette); return 0; }