void gfxengine_t::screenshot() { char filename[1024]; snprintf(filename, sizeof(filename), "screen%d.bmp", screenshot_count++); SDL_SaveBMP(screen_surface, filename); }
void app_event_loop() { bool isRunning=true; SDL_Event event; uint32_t lastTick; int32_t delay; int i; struct tm* now; printf("[DEBUG] Got app_event_loop\n"); while (isRunning) { lastTick=SDL_GetTicks (); SDL_PumpEvents (); while (SDL_PollEvent (&event)) { switch (event.type) { case(SDL_QUIT): { isRunning=false; } break; case(SDL_KEYDOWN): { switch (event.key.keysym.sym) { case(SDLK_ESCAPE): { isRunning=false; } break; case(SDLK_F1): { bodyID=(bodyID+1)%BODY_COUNT; bodyRender=true; } break; case(SDLK_F2): { shadow=!shadow; markDirty(true); bodyRender=true; } break; case(SDLK_F3): { toggle_24h_style(); if (clock_is_24h_style ()) SDL_WM_SetCaption("Pebble Local Simulator - 24H Style",0); else SDL_WM_SetCaption("Pebble Local Simulator - 12H Style",0); } break; case(SDLK_F4): { toggle_bluetooth_connection(); printf("[INFO] Toggle bluetooth %s\n", bluetooth_connection_service_peek() ? "ON":"OFF"); } break; case(SDLK_F5): { BatteryChargeState state; toggle_battery_charger_plugged(); state = battery_state_service_peek(); printf("[INFO] Toggle plugged: %d%%, %s charging, %s plugged\n", state.charge_percent, state.is_charging ? "":"not", state.is_plugged ? "":"not"); } break; case(SDLK_F12): { time_t timeSec=time(0); now=localtime(&timeSec); strftime (titleBuffer,strlen(titleBuffer),"./simdata/screenshots/%Y-%m-%e-%H-%M-%S",now); strcat(titleBuffer,".bmp"); if (SDL_SaveBMP(screen,titleBuffer)<0) printf("[WARN] SDL_SaveBMP: %s\n",SDL_GetError ()); else printf ("[INFO] Saved screenshot: %s\n",titleBuffer); } break; case(SDLK_PLUS): { BatteryChargeState state; battery_charge_increase(); state = battery_state_service_peek(); printf("[INFO] Battery state: %d%%, %s charging, %s plugged\n", state.charge_percent, state.is_charging ? "":"not", state.is_plugged ? "":"not"); } break; case(SDLK_MINUS): { BatteryChargeState state; battery_charge_decrease(); state = battery_state_service_peek(); printf("[INFO] Battery state: %d%%, %s charging, %s plugged\n", state.charge_percent, state.is_charging ? "":"not", state.is_plugged ? "":"not"); } break; case (SDLK_x): { int32_t direction=1; if(event.key.keysym.mod & KMOD_SHIFT) { direction=-1; } accel_do_tap_on_axis(ACCEL_AXIS_X, direction); printf("[INFO] Tap X %d\n", direction); } break; case (SDLK_y): { int32_t direction=1; if(event.key.keysym.mod & KMOD_SHIFT) { direction=-1; } accel_do_tap_on_axis(ACCEL_AXIS_Y, direction); printf("[INFO] Tap Y %d\n", direction); } break; case (SDLK_z): { int32_t direction=1; if(event.key.keysym.mod & KMOD_SHIFT) { direction=-1; } accel_do_tap_on_axis(ACCEL_AXIS_Z, direction); printf("[INFO] Tap Z %d\n", direction); } break; case (KEY_BUTTON_BACK): { buttonState[BUTTON_ID_BACK]=true; bodyRender=true; onButtonDown(BUTTON_ID_BACK); } break; case (KEY_BUTTON_UP): { buttonState[BUTTON_ID_UP]=true; bodyRender=true; onButtonDown(BUTTON_ID_UP); } break; case (KEY_BUTTON_SELECT): { buttonState[BUTTON_ID_SELECT]=true; bodyRender=true; onButtonDown(BUTTON_ID_SELECT); } break; case (KEY_BUTTON_DOWN): { buttonState[BUTTON_ID_DOWN]=true; bodyRender=true; onButtonDown(BUTTON_ID_DOWN); } break; default: ; } } break; case(SDL_KEYUP): { switch (event.key.keysym.sym) { case(KEY_BUTTON_BACK): { buttonState[BUTTON_ID_BACK]=false; bodyRender=true; onButtonUp(BUTTON_ID_BACK); } break; case(KEY_BUTTON_UP): { buttonState[BUTTON_ID_UP]=false; bodyRender=true; onButtonUp(BUTTON_ID_UP); } break; case(KEY_BUTTON_SELECT): { buttonState[BUTTON_ID_SELECT]=false; bodyRender=true; onButtonUp(BUTTON_ID_SELECT); } break; case(KEY_BUTTON_DOWN): { buttonState[BUTTON_ID_DOWN]=false; bodyRender=true; onButtonUp(BUTTON_ID_DOWN); } break; default: ; } } break; default: ; } } for (i=0;i<SIM_SERVICE_COUNT;i++) (serviceData.services[i]) (); if (lastVibeState!=getVibeState()) { bodyRender=true; lastVibeState=getVibeState(); } if (lastLightState!=getLightState()) { bodyRender=true; lastLightState=getLightState(); } if (render ()||bodyRender) simulatorRender (); delay=(SDL_GetTicks()-lastTick); elapsed=delay/1000.0f; delay=16-delay; //equals about 60 frames per second lastTick=SDL_GetTicks(); if (delay>0) SDL_Delay(delay); } }
int CScreen::Save(void) { static int iIndex = 0; char sFileName[STD_BUF]; char *sFileExt = #ifdef HAVE_JPEG "jpg"; #else "bmp"; #endif do { iIndex++; snprintf(sFileName, STD_BUF, "screenshot/screenshot_%04d.%s", iIndex, sFileExt); } while(!access(sFileName, 0)); #ifdef HAVE_JPEG struct jpeg_compress_struct info; struct jpeg_error_mgr jerr; FILE* FP_ptr_OutFile; JSAMPROW iRow_ptr[1]; int iRow_Stride; int iDeleteBuffer = 0; unsigned char* ucImageBuffer = NULL; SDL_Surface* SS_p_nSurface; info.err = jpeg_std_error(&jerr); jpeg_create_compress(&info); if ((FP_ptr_OutFile = fopen(sFileName, "wb")) == NULL) { std::cout << "ImpossÃvel abrir o arquivo de destino: " << sFileName << std::endl; return -1; } jpeg_stdio_dest(&info, FP_ptr_OutFile); info.image_width = SS_p_Screen->w; info.image_height = SS_p_Screen->h; info.input_components = 3; info.in_color_space = JCS_RGB; #if SDL_BYTEORDER == SDL_BIG_ENDIAN SS_p_nSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, SS_p_Screen->w, SS_p_Screen->h, 24, 0xff000000, 0x00ff0000, 0x0000ff00, 0x00000000); #else SS_p_nSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, SS_p_Screen->w, SS_p_Screen->h, 24, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000); #endif if(SS_p_nSurface == NULL) { std::cout << "Erro ao alocar superfÃcie para \'screenshot\'" << std::endl; return -1; } SDL_BlitSurface(SS_p_Screen, NULL, SS_p_nSurface, NULL); SS_p_Screen = SS_p_nSurface; iDeleteBuffer = 1; if(SDL_MUSTLOCK(SS_p_Screen)) SDL_LockSurface(SS_p_Screen); ucImageBuffer = (unsigned char *)SS_p_Screen->pixels; jpeg_set_defaults(&info); jpeg_set_quality(&info, JPEG_QUALITY_DEFAULT, TRUE); jpeg_start_compress(&info, TRUE); iRow_Stride = SS_p_Screen->pitch; while (info.next_scanline < info.image_height) { iRow_ptr[0] = &ucImageBuffer[info.next_scanline * iRow_Stride]; (void) jpeg_write_scanlines(&info, iRow_ptr, 1); } jpeg_finish_compress(&info); fclose(FP_ptr_OutFile); jpeg_destroy_compress(&info); if(SDL_MUSTLOCK(SS_p_Screen)) SDL_UnlockSurface(SS_p_Screen); if(iDeleteBuffer) SDL_FreeSurface(SS_p_Screen); return 0; #else // Caso contrario não tenha a bibliote JPEG no sistema salva como BMP SDL_SaveBMP(SS_p_Screen, sFileName); return 0; #endif // Fim de HAVE_JPEG }
void GameWorldPanel::handleEvents(bool &running) { SDL_Event e; while (SDL_PollEvent(&e) != 0) { bool applicationExit = (e.type == SDL_QUIT); bool resized = (e.type == SDL_WINDOWEVENT) && (e.window.event == SDL_WINDOWEVENT_RESIZED); bool escapePressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_ESCAPE); if (applicationExit) { running = false; } if (resized) { int width = e.window.data1; int height = e.window.data2; this->getGameState()->resizeWindow(width, height); this->updateCursorRegions(width, height); } if (escapePressed) { this->pauseButton->click(this->getGameState()); } bool takeScreenshot = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_PRINTSCREEN); if (takeScreenshot) { auto &renderer = this->getGameState()->getRenderer(); SDL_Surface *screenshot = renderer.getScreenshot(); SDL_SaveBMP(screenshot, "out.bmp"); SDL_FreeSurface(screenshot); } bool leftClick = (e.type == SDL_MOUSEBUTTONDOWN) && (e.button.button == SDL_BUTTON_LEFT); bool rightClick = (e.type == SDL_MOUSEBUTTONDOWN) && (e.button.button == SDL_BUTTON_RIGHT); const auto &renderer = this->getGameState()->getRenderer(); // Get mouse position relative to letterbox coordinates. const Int2 originalPosition = renderer.nativePointToOriginal( this->getMousePosition()); if (leftClick) { // Was an interface button clicked? if (PortraitRegion.contains(originalPosition)) { this->characterSheetButton->click(this->getGameState()); } else if (DrawWeaponRegion.contains(originalPosition)) { Debug::mention("Game", "Draw weapon."); } else if (MapRegion.contains(originalPosition)) { this->automapButton->click(this->getGameState()); } else if (ThievingRegion.contains(originalPosition)) { Debug::mention("Game", "Thieving."); } else if (StatusRegion.contains(originalPosition)) { Debug::mention("Game", "Status."); } else if (MagicRegion.contains(originalPosition)) { Debug::mention("Game", "Magic."); } else if (LogbookRegion.contains(originalPosition)) { this->logbookButton->click(this->getGameState()); } else if (UseItemRegion.contains(originalPosition)) { Debug::mention("Game", "Use item."); } else if (RestRegion.contains(originalPosition)) { Debug::mention("Game", "Rest."); } // Later... any entities in the world clicked? } else if (rightClick) { if (MapRegion.contains(originalPosition)) { this->worldMapButton->click(this->getGameState()); } } bool activateHotkeyPressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_e); bool automapHotkeyPressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_n); bool logbookHotkeyPressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_l); bool sheetHotkeyPressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_TAB); bool worldMapHotkeyPressed = (e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_m); if (activateHotkeyPressed) { // Activate whatever is looked at. } else if (automapHotkeyPressed) { this->automapButton->click(this->getGameState()); } else if (logbookHotkeyPressed) { this->logbookButton->click(this->getGameState()); } else if (sheetHotkeyPressed) { this->characterSheetButton->click(this->getGameState()); } else if (worldMapHotkeyPressed) { this->worldMapButton->click(this->getGameState()); } } }
void dump_screen(void) { // Find suitable file name FileSpecifier file; int i = 0; do { char name[256]; const char* suffix; #ifdef HAVE_PNG suffix = "png"; #else suffix = "bmp"; #endif if (get_game_state() == _game_in_progress) { sprintf(name, "%s_%04d.%s", to_alnum(static_world->level_name).c_str(), i, suffix); } else { sprintf(name, "Screenshot_%04d.%s", i, suffix); } file = screenshots_dir + name; i++; } while (file.Exists()); #ifdef HAVE_PNG // build some nice metadata std::vector<IMG_PNG_text> texts; std::map<std::string, std::string> metadata; metadata["Source"] = expand_app_variables("$appName$ $appVersion$ ($appPlatform$)"); time_t rawtime; time(&rawtime); char time_string[32]; strftime(time_string, 32,"%d %b %Y %H:%M:%S +0000", gmtime(&rawtime)); metadata["Creation Time"] = time_string; if (get_game_state() == _game_in_progress) { const float FLOAT_WORLD_ONE = float(WORLD_ONE); const float AngleConvert = 360/float(FULL_CIRCLE); metadata["Level"] = static_world->level_name; char map_file_name[256]; FileSpecifier fs = environment_preferences->map_file; fs.GetName(map_file_name); metadata["Map File"] = map_file_name; if (Scenario::instance()->GetName().size()) { metadata["Scenario"] = Scenario::instance()->GetName(); } metadata["Polygon"] = boost::lexical_cast<std::string>(world_view->origin_polygon_index); metadata["X"] = boost::lexical_cast<std::string>(world_view->origin.x / FLOAT_WORLD_ONE); metadata["Y"] = boost::lexical_cast<std::string>(world_view->origin.y / FLOAT_WORLD_ONE); metadata["Z"] = boost::lexical_cast<std::string>(world_view->origin.z / FLOAT_WORLD_ONE); metadata["Yaw"] = boost::lexical_cast<std::string>(world_view->yaw * AngleConvert); short pitch = world_view->pitch; if (pitch > HALF_CIRCLE) pitch -= HALF_CIRCLE; metadata["Pitch"] = boost::lexical_cast<std::string>(pitch * AngleConvert); } for (std::map<std::string, std::string>::const_iterator it = metadata.begin(); it != metadata.end(); ++it) { IMG_PNG_text text; text.key = const_cast<char*>(it->first.c_str()); text.value = const_cast<char*>(it->second.c_str()); texts.push_back(text); } IMG_PNG_text* textp = texts.size() ? &texts[0] : 0; #endif // Without OpenGL, dumping the screen is easy if (!MainScreenIsOpenGL()) { //#ifdef HAVE_PNG // aoIMG_SavePNG(file.GetPath(), MainScreenSurface(), IMG_COMPRESS_DEFAULT, textp, texts.size()); #ifdef HAVE_SDL_IMAGE IMG_SavePNG(MainScreenSurface(), file.GetPath()); #else SDL_SaveBMP(MainScreenSurface(), file.GetPath()); #endif return; } int video_w = MainScreenPixelWidth(); int video_h = MainScreenPixelHeight(); #ifdef HAVE_OPENGL // Otherwise, allocate temporary surface... SDL_Surface *t = SDL_CreateRGBSurface(SDL_SWSURFACE, video_w, video_h, 24, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x000000ff, 0x0000ff00, 0x00ff0000, 0); #else 0x00ff0000, 0x0000ff00, 0x000000ff, 0); #endif if (t == NULL) return; // ...and pixel buffer void *pixels = malloc(video_w * video_h * 3); if (pixels == NULL) { SDL_FreeSurface(t); return; } // Read OpenGL frame buffer glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, video_w, video_h, GL_RGB, GL_UNSIGNED_BYTE, pixels); glPixelStorei(GL_PACK_ALIGNMENT, 4); // return to default // Copy pixel buffer (which is upside-down) to surface for (int y = 0; y < video_h; y++) memcpy((uint8 *)t->pixels + t->pitch * y, (uint8 *)pixels + video_w * 3 * (video_h - y - 1), video_w * 3); free(pixels); // Save surface //#ifdef HAVE_PNG // aoIMG_SavePNG(file.GetPath(), t, IMG_COMPRESS_DEFAULT, textp, texts.size()); #ifdef HAVE_SDL_IMAGE IMG_SavePNG(t, file.GetPath()); #else SDL_SaveBMP(t, file.GetPath()); #endif SDL_FreeSurface(t); #endif }
static int setup_test(int argc, char **argv) { const char *dumpfile = NULL; SDL_Surface *bmp = NULL; Uint32 dstbpp = 32; Uint32 dstrmask = 0x00FF0000; Uint32 dstgmask = 0x0000FF00; Uint32 dstbmask = 0x000000FF; Uint32 dstamask = 0x00000000; Uint32 dstflags = 0; int dstw = 640; int dsth = 480; Uint32 srcbpp = 32; Uint32 srcrmask = 0x00FF0000; Uint32 srcgmask = 0x0000FF00; Uint32 srcbmask = 0x000000FF; Uint32 srcamask = 0x00000000; Uint32 srcflags = 0; int srcw = 640; int srch = 480; Uint32 origsrcalphaflags = 0; Uint32 origdstalphaflags = 0; Uint32 srcalphaflags = 0; Uint32 dstalphaflags = 0; Uint8 origsrcalpha = 255; Uint8 origdstalpha = 255; Uint8 srcalpha = 255; Uint8 dstalpha = 255; int screenSurface = 0; int i = 0; for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (strcmp(arg, "--dstbpp") == 0) dstbpp = atoi(argv[++i]); else if (strcmp(arg, "--dstrmask") == 0) dstrmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstgmask") == 0) dstgmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstbmask") == 0) dstbmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstamask") == 0) dstamask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstwidth") == 0) dstw = atoi(argv[++i]); else if (strcmp(arg, "--dstheight") == 0) dsth = atoi(argv[++i]); else if (strcmp(arg, "--dsthwsurface") == 0) dstflags |= SDL_HWSURFACE; else if (strcmp(arg, "--srcbpp") == 0) srcbpp = atoi(argv[++i]); else if (strcmp(arg, "--srcrmask") == 0) srcrmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcgmask") == 0) srcgmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcbmask") == 0) srcbmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcamask") == 0) srcamask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcwidth") == 0) srcw = atoi(argv[++i]); else if (strcmp(arg, "--srcheight") == 0) srch = atoi(argv[++i]); else if (strcmp(arg, "--srchwsurface") == 0) srcflags |= SDL_HWSURFACE; else if (strcmp(arg, "--seconds") == 0) testSeconds = atoi(argv[++i]); else if (strcmp(arg, "--screen") == 0) screenSurface = 1; else if (strcmp(arg, "--dumpfile") == 0) dumpfile = argv[++i]; /* !!! FIXME: set colorkey. */ else if (0) { /* !!! FIXME: we handle some commandlines elsewhere now */ fprintf(stderr, "Unknown commandline option: %s\n", arg); return (0); } } if (SDL_Init(SDL_INIT_VIDEO) == -1) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); return (0); } bmp = SDL_LoadBMP("sample.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP failed: %s\n", SDL_GetError()); SDL_Quit(); return (0); } if ((dstflags & SDL_HWSURFACE) == 0) dstflags |= SDL_SWSURFACE; if ((srcflags & SDL_HWSURFACE) == 0) srcflags |= SDL_SWSURFACE; if (screenSurface) dest = SDL_SetVideoMode(dstw, dsth, dstbpp, dstflags); else { dest = SDL_CreateRGBSurface(dstflags, dstw, dsth, dstbpp, dstrmask, dstgmask, dstbmask, dstamask); } if (dest == NULL) { fprintf(stderr, "dest surface creation failed: %s\n", SDL_GetError()); SDL_Quit(); return (0); } src = SDL_CreateRGBSurface(srcflags, srcw, srch, srcbpp, srcrmask, srcgmask, srcbmask, srcamask); if (src == NULL) { fprintf(stderr, "src surface creation failed: %s\n", SDL_GetError()); SDL_Quit(); return (0); } /* handle alpha settings... */ srcalphaflags = (src->flags & SDL_SRCALPHA) | (src->flags & SDL_RLEACCEL); dstalphaflags = (dest->flags & SDL_SRCALPHA) | (dest->flags & SDL_RLEACCEL); origsrcalphaflags = srcalphaflags; origdstalphaflags = dstalphaflags; SDL_GetSurfaceAlphaMod(src, &srcalpha); SDL_GetSurfaceAlphaMod(dest, &dstalpha); origsrcalpha = srcalpha; origdstalpha = dstalpha; for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (strcmp(arg, "--srcalpha") == 0) srcalpha = atoi(argv[++i]); else if (strcmp(arg, "--dstalpha") == 0) dstalpha = atoi(argv[++i]); else if (strcmp(arg, "--srcsrcalpha") == 0) srcalphaflags |= SDL_SRCALPHA; else if (strcmp(arg, "--srcnosrcalpha") == 0) srcalphaflags &= ~SDL_SRCALPHA; else if (strcmp(arg, "--srcrleaccel") == 0) srcalphaflags |= SDL_RLEACCEL; else if (strcmp(arg, "--srcnorleaccel") == 0) srcalphaflags &= ~SDL_RLEACCEL; else if (strcmp(arg, "--dstsrcalpha") == 0) dstalphaflags |= SDL_SRCALPHA; else if (strcmp(arg, "--dstnosrcalpha") == 0) dstalphaflags &= ~SDL_SRCALPHA; else if (strcmp(arg, "--dstrleaccel") == 0) dstalphaflags |= SDL_RLEACCEL; else if (strcmp(arg, "--dstnorleaccel") == 0) dstalphaflags &= ~SDL_RLEACCEL; } if ((dstalphaflags != origdstalphaflags) || (origdstalpha != dstalpha)) SDL_SetAlpha(dest, dstalphaflags, dstalpha); if ((srcalphaflags != origsrcalphaflags) || (origsrcalpha != srcalpha)) SDL_SetAlpha(src, srcalphaflags, srcalpha); /* set some sane defaults so we can see if the blit code is broken... */ SDL_FillRect(dest, NULL, SDL_MapRGB(dest->format, 0, 0, 0)); SDL_FillRect(src, NULL, SDL_MapRGB(src->format, 0, 0, 0)); blitCentered(src, bmp); SDL_FreeSurface(bmp); if (dumpfile) SDL_SaveBMP(src, dumpfile); /* make sure initial convert is sane. */ output_details(); return (1); }
void guiUpdate() { for(unsigned int n=0; n<simComponentList.size(); n++) simComponentList[n]->tick(); if (SDL_GetTicks() - lastUpdate < 25) return; lastUpdate = SDL_GetTicks(); int clickX = -1, clickY = -1; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: key_delay = 0; break; case SDL_KEYUP: // If escape is pressed, quit if (event.key.keysym.sym == SDLK_ESCAPE) { FILE* f = fopen("eeprom.save", "wb"); fwrite(__eeprom__storage, sizeof(__eeprom__storage), 1, f); fclose(f); exit(0); } if (event.key.keysym.sym == SDLK_p) { SDL_Surface* tmpSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 128*SCALE,64*SCALE,32, 0, 0, 0, 0); SDL_Rect src = {SCALE, SCALE, 128*SCALE,64*SCALE}; SDL_Rect dst = {0, 0, 128*SCALE,64*SCALE}; SDL_BlitSurface(screen, &src, tmpSurface, &dst); char filename[128]; static int screenshotNr = 0; sprintf(filename, "screen%i.bmp", screenshotNr); screenshotNr++; SDL_SaveBMP(tmpSurface, filename); SDL_FreeSurface(tmpSurface); } break; case SDL_MOUSEMOTION: if (event.motion.state) { #ifdef ENABLE_ULTILCD2 lcd_lib_encoder_pos_interrupt += event.motion.xrel / 2; #endif } break; case SDL_MOUSEBUTTONDOWN: clickX = event.button.x; clickY = event.button.y; break; case SDL_QUIT: { FILE* f = fopen("eeprom.save", "wb"); fwrite(__eeprom__storage, sizeof(__eeprom__storage), 1, f); fclose(f); exit(0); } } } Uint8* keys = SDL_GetKeyState(NULL); writeInput(BTN_ENC, !keys[SDLK_RETURN]); if (keys[SDLK_RIGHT]) { if (key_delay == 0) { #ifdef ENABLE_ULTILCD2 lcd_lib_encoder_pos_interrupt+=2; #endif #ifdef ULTIPANEL encoderDiff+=2; #endif key_delay = KEY_REPEAT_DELAY; }else key_delay--; } if (keys[SDLK_LEFT]) { if (key_delay == 0) { #ifdef ENABLE_ULTILCD2 lcd_lib_encoder_pos_interrupt-=2; #endif #ifdef ULTIPANEL encoderDiff-=2; #endif key_delay = KEY_REPEAT_DELAY; }else key_delay--; } SDL_FillRect(screen, NULL, 0x000000); for(unsigned int n=0; n<simComponentList.size(); n++) simComponentList[n]->doDraw(); SDL_Rect rect; rect.w = 32; rect.h = 32; rect.x = 128 * SCALE + 32; rect.y = 32; if (clickX >= rect.x && clickX <= rect.x + rect.w && clickY >= rect.y && clickY <= rect.y + rect.h) cardInserted = !cardInserted; SDL_FillRect(screen, &rect, cardInserted ? 0x00FF00 : 0xFF0000); rect.y += 48; writeInput(SDCARDDETECT, !cardInserted); if (clickX >= rect.x && clickX <= rect.x + rect.w && clickY >= rect.y && clickY <= rect.y + rect.h) stoppedValue = !stoppedValue; writeInput(SAFETY_TRIGGERED_PIN, stoppedValue); SDL_FillRect(screen, &rect, stoppedValue ? 0x00FF00 : 0xFF0000); rect.y += 48; SDL_Flip(screen); }
int main(int argc, char *argv[]) { char *argv0 = argv[0]; SDL_Window *window; SDL_Renderer *renderer; TTF_Font *font; SDL_Surface *text; Scene scene; int ptsize; int i, done; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; SDL_Event event; int rendersolid; int renderstyle; int outline; int hinting; int kerning; int dump; enum { RENDER_LATIN1, RENDER_UTF8, RENDER_UNICODE } rendertype; char *message, string[128]; /* Look for special execution mode */ dump = 0; /* Look for special rendering types */ rendersolid = 0; renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; outline = 0; hinting = TTF_HINTING_NORMAL; kerning = 1; /* Default is black and white */ forecol = &black; backcol = &white; for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) { if ( strcmp(argv[i], "-solid") == 0 ) { rendersolid = 1; } else if ( strcmp(argv[i], "-utf8") == 0 ) { rendertype = RENDER_UTF8; } else if ( strcmp(argv[i], "-unicode") == 0 ) { rendertype = RENDER_UNICODE; } else if ( strcmp(argv[i], "-b") == 0 ) { renderstyle |= TTF_STYLE_BOLD; } else if ( strcmp(argv[i], "-i") == 0 ) { renderstyle |= TTF_STYLE_ITALIC; } else if ( strcmp(argv[i], "-u") == 0 ) { renderstyle |= TTF_STYLE_UNDERLINE; } else if ( strcmp(argv[i], "-s") == 0 ) { renderstyle |= TTF_STYLE_STRIKETHROUGH; } else if ( strcmp(argv[i], "-outline") == 0 ) { if ( sscanf (argv[++i], "%d", &outline) != 1 ) { fprintf(stderr, Usage, argv0); return(1); } } else if ( strcmp(argv[i], "-hintlight") == 0 ) { hinting = TTF_HINTING_LIGHT; } else if ( strcmp(argv[i], "-hintmono") == 0 ) { hinting = TTF_HINTING_MONO; } else if ( strcmp(argv[i], "-hintnone") == 0 ) { hinting = TTF_HINTING_NONE; } else if ( strcmp(argv[i], "-nokerning") == 0 ) { kerning = 0; } else if ( strcmp(argv[i], "-dump") == 0 ) { dump = 1; } else if ( strcmp(argv[i], "-fgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } forecol->r = (Uint8)r; forecol->g = (Uint8)g; forecol->b = (Uint8)b; } else if ( strcmp(argv[i], "-bgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } backcol->r = (Uint8)r; backcol->g = (Uint8)g; backcol->b = (Uint8)b; } else { fprintf(stderr, Usage, argv0); return(1); } } argv += i; argc -= i; /* Check usage */ if ( ! argv[0] ) { fprintf(stderr, Usage, argv0); return(1); } /* Initialize the TTF library */ if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); SDL_Quit(); return(2); } /* Open the font file with the requested point size */ ptsize = 0; if ( argc > 1 ) { ptsize = atoi(argv[1]); } if ( ptsize == 0 ) { i = 2; ptsize = DEFAULT_PTSIZE; } else { i = 3; } font = TTF_OpenFont(argv[0], ptsize); if ( font == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, argv[0], SDL_GetError()); cleanup(2); } TTF_SetFontStyle(font, renderstyle); TTF_SetFontOutline(font, outline); TTF_SetFontKerning(font, kerning); TTF_SetFontHinting(font, hinting); if( dump ) { for( i = 48; i < 123; i++ ) { SDL_Surface* glyph = NULL; glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol ); if( glyph ) { char outname[64]; sprintf( outname, "glyph-%d.bmp", i ); SDL_SaveBMP( glyph, outname ); } } cleanup(0); } /* Create a window */ if (SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) { fprintf(stderr, "SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError()); cleanup(2); } /* Show which font file we're looking at */ sprintf(string, "Font file: %s", argv[0]); /* possible overflow */ if ( rendersolid ) { text = TTF_RenderText_Solid(font, string, *forecol); } else { text = TTF_RenderText_Shaded(font, string, *forecol, *backcol); } if ( text != NULL ) { scene.captionRect.x = 4; scene.captionRect.y = 4; scene.captionRect.w = text->w; scene.captionRect.h = text->h; scene.caption = SDL_CreateTextureFromSurface(renderer, text); SDL_FreeSurface(text); } /* Render and center the message */ if ( argc > 2 ) { message = argv[2]; } else { message = DEFAULT_TEXT; } switch (rendertype) { case RENDER_LATIN1: if ( rendersolid ) { text = TTF_RenderText_Solid(font,message,*forecol); } else { text = TTF_RenderText_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UTF8: if ( rendersolid ) { text = TTF_RenderUTF8_Solid(font,message,*forecol); } else { text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UNICODE: { Uint16 *unicode_text = SDL_iconv_utf8_ucs2(message); if ( rendersolid ) { text = TTF_RenderUNICODE_Solid(font, unicode_text, *forecol); } else { text = TTF_RenderUNICODE_Shaded(font, unicode_text, *forecol, *backcol); } SDL_free(unicode_text); } break; default: text = NULL; /* This shouldn't happen */ break; } if ( text == NULL ) { fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError()); TTF_CloseFont(font); cleanup(2); } scene.messageRect.x = (WIDTH - text->w)/2; scene.messageRect.y = (HEIGHT - text->h)/2; scene.messageRect.w = text->w; scene.messageRect.h = text->h; scene.message = SDL_CreateTextureFromSurface(renderer, text); printf("Font is generally %d big, and string is %d big\n", TTF_FontHeight(font), text->h); draw_scene(renderer, &scene); /* Wait for a keystroke, and blit text on mouse press */ done = 0; while ( ! done ) { if ( SDL_WaitEvent(&event) < 0 ) { fprintf(stderr, "SDL_PullEvent() error: %s\n", SDL_GetError()); done = 1; continue; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: scene.messageRect.x = event.button.x - text->w/2; scene.messageRect.y = event.button.y - text->h/2; scene.messageRect.w = text->w; scene.messageRect.h = text->h; draw_scene(renderer, &scene); break; case SDL_KEYDOWN: case SDL_QUIT: done = 1; break; default: break; } } SDL_FreeSurface(text); TTF_CloseFont(font); SDL_DestroyTexture(scene.caption); SDL_DestroyTexture(scene.message); cleanup(0); /* Not reached, but fixes compiler warnings */ return 0; }
/************************************************************************** SDL-client main loop. **************************************************************************/ Uint16 gui_event_loop(void *pData, void (*loop_action)(void *pData), Uint16 (*key_down_handler)(SDL_keysym Key, void *pData), Uint16 (*key_up_handler)(SDL_keysym Key, void *pData), Uint16 (*mouse_button_down_handler)(SDL_MouseButtonEvent *pButtonEvent, void *pData), Uint16 (*mouse_button_up_handler)(SDL_MouseButtonEvent *pButtonEvent, void *pData), Uint16 (*mouse_motion_handler)(SDL_MouseMotionEvent *pMotionEvent, void *pData)) { Uint16 ID; static struct timeval tv; static fd_set civfdset; Uint32 t_current, t_last_unit_anim, t_last_map_scrolling; Uint32 real_timer_next_call; static int result, schot_nr = 0; static char schot[32]; ID = ID_ERROR; t_last_map_scrolling = t_last_unit_anim = real_timer_next_call = SDL_GetTicks(); while (ID == ID_ERROR) { /* ========================================= */ /* net check with 10ms delay event loop */ if ((net_socket >= 0) || (ggz_socket >= 0)) { FD_ZERO(&civfdset); if (net_socket >= 0) { FD_SET(net_socket, &civfdset); } if (ggz_socket >= 0) { FD_SET(ggz_socket, &civfdset); } tv.tv_sec = 0; tv.tv_usec = 10000;/* 10ms*/ result = fc_select(MAX(net_socket, ggz_socket) + 1, &civfdset, NULL, NULL, &tv); if (result < 0) { if (errno != EINTR) { break; } else { continue; } } else { if (result > 0) { if ((net_socket >= 0) && FD_ISSET(net_socket, &civfdset)) { SDL_PushEvent(pNet_User_Event); } if ((ggz_socket >= 0) && FD_ISSET(ggz_socket, &civfdset)) { SDL_PushEvent(pGGZ_User_Event); } } } } else { /* if connection is not establish */ SDL_Delay(10); } /* ========================================= */ t_current = SDL_GetTicks(); if (t_current > real_timer_next_call) { real_timer_next_call = t_current + (real_timer_callback() * 1000); } if ((t_current - t_last_unit_anim) > UNITS_TIMER_INTERVAL) { if (autoconnect) { widget_info_counter++; SDL_PushEvent(pAnim_User_Event); } else { SDL_PushEvent(pAnim_User_Event); } t_last_unit_anim = SDL_GetTicks(); } if (is_map_scrolling) { if ((t_current - t_last_map_scrolling) > MAP_SCROLL_TIMER_INTERVAL) { SDL_PushEvent(pMap_Scroll_User_Event); t_last_map_scrolling = SDL_GetTicks(); } } else { t_last_map_scrolling = SDL_GetTicks(); } if (widget_info_counter > 0) { SDL_PushEvent(pInfo_User_Event); widget_info_counter = 0; } /* ========================================= */ if (loop_action) { loop_action(pData); } /* ========================================= */ while (SDL_PollEvent(&Main.event) == 1) { switch (Main.event.type) { case SDL_QUIT: return MAX_ID; break; case SDL_KEYUP: switch (Main.event.key.keysym.sym) { /* find if Shifts are released */ case SDLK_RSHIFT: RSHIFT = FALSE; break; case SDLK_LSHIFT: LSHIFT = FALSE; break; case SDLK_LCTRL: LCTRL = FALSE; break; case SDLK_RCTRL: RCTRL = FALSE; break; case SDLK_LALT: LALT = FALSE; break; default: if(key_up_handler) { ID = key_up_handler(Main.event.key.keysym, pData); } break; } break; case SDL_KEYDOWN: switch(Main.event.key.keysym.sym) { case SDLK_PRINT: fc_snprintf(schot, sizeof(schot), "fc_%05d.bmp", schot_nr++); log_normal(_("Making screenshot %s"), schot); SDL_SaveBMP(Main.screen, schot); break; case SDLK_RSHIFT: /* Right Shift is Pressed */ RSHIFT = TRUE; break; case SDLK_LSHIFT: /* Left Shift is Pressed */ LSHIFT = TRUE; break; case SDLK_LCTRL: /* Left CTRL is Pressed */ LCTRL = TRUE; break; case SDLK_RCTRL: /* Right CTRL is Pressed */ RCTRL = TRUE; break; case SDLK_LALT: /* Left ALT is Pressed */ LALT = TRUE; break; default: if(key_down_handler) { ID = key_down_handler(Main.event.key.keysym, pData); } break; } break; case SDL_MOUSEBUTTONDOWN: if(mouse_button_down_handler) { ID = mouse_button_down_handler(&Main.event.button, pData); } break; case SDL_MOUSEBUTTONUP: if(mouse_button_up_handler) { ID = mouse_button_up_handler(&Main.event.button, pData); } break; case SDL_MOUSEMOTION: if(mouse_motion_handler) { ID = mouse_motion_handler(&Main.event.motion, pData); } break; case SDL_USEREVENT: switch(Main.event.user.code) { case NET: input_from_server(net_socket); break; case GGZ: input_from_ggz(ggz_socket); break; case ANIM: update_button_hold_state(); animate_mouse_cursor(); draw_mouse_cursor(); break; case SHOW_WIDGET_INFO_LABBEL: draw_widget_info_label(); break; case TRY_AUTO_CONNECT: if (try_to_autoconnect()) { pInfo_User_Event->user.code = SHOW_WIDGET_INFO_LABBEL; autoconnect = FALSE; } break; case FLUSH: unqueue_flush(); break; case MAP_SCROLL: scroll_mapview(scroll_dir); break; case EXIT_FROM_EVENT_LOOP: return MAX_ID; break; default: break; } break; } } if (ID == ID_ERROR) { if (callbacks && callback_list_size(callbacks) > 0) { struct callback *cb = callback_list_get(callbacks, 0); callback_list_remove(callbacks, cb); (cb->callback)(cb->data); free(cb); } } } return ID; }
int PlayLaserGame(int diff_level) { int i, img, done, quit, frame, lowest, lowest_y, tux_img, old_tux_img, tux_pressing, tux_anim, tux_anim_frame, tux_same_counter, level_start_wait, num_cities_alive, num_comets_alive, paused, picked_comet, gameover; Uint16 key_unicode; SDL_Event event; Uint32 last_time = 0; Uint32 now_time = 0; SDLKey key; SDL_Rect src, dest; /* str[] is a buffer to draw the scores, waves, etc. (don't need wchar_t) */ char str[64]; LOG( "starting Comet Zap game\n" ); DOUT( diff_level ); SDL_ShowCursor(0); laser_load_data(); /* Clear window: */ SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0)); SDL_Flip(screen); /* --- MAIN GAME LOOP: --- */ done = 0; quit = 0; src.w = src.h = 0; /* Prepare to start the game: */ wave = 1; score = 0; gameover = 0; level_start_wait = LEVEL_START_WAIT_START; /* (Create and position cities) */ for (i = 0; i < NUM_CITIES; i++) { cities[i].alive = 1; cities[i].expl = 0; cities[i].shields = 1; } /* figure out x placement: */ calc_city_pos(); num_cities_alive = NUM_CITIES; num_comets_alive = 0; /* (Clear laser) */ laser.alive = 0; /* Reset remaining stuff: */ laser_reset_level(diff_level); /* --- MAIN GAME LOOP!!! --- */ frame = 0; paused = 0; picked_comet = -1; tux_img = IMG_TUX_RELAX1; tux_anim = -1; tux_anim_frame = 0; tux_same_counter = 0; ans_num = 0; MusicPlay(musics[MUS_GAME + (rand() % NUM_MUSICS)], 0); do { frame++; last_time = SDL_GetTicks(); old_tux_img = tux_img; tux_pressing = 0; /* Handle any incoming events: */ while (SDL_PollEvent(&event) > 0) { if (event.type == SDL_QUIT) { /* Window close event - quit! */ exit(0); } else if (event.type == SDL_KEYDOWN) { key = event.key.keysym.sym; if (key == SDLK_F10) { SwitchScreenMode(); calc_city_pos(); recalc_comet_pos(); } if (key == SDLK_F11) SDL_SaveBMP( screen, "laser.bmp"); if (key == SDLK_ESCAPE) paused = 1; /* --- eat other keys until level wait has passed --- */ if (level_start_wait > 0) key = SDLK_UNKNOWN; key_unicode = event.key.keysym.unicode; //key_unicode = event.key.keysym.unicode & 0xff; DEBUGCODE { fprintf(stderr, "key_unicode = %d\n", key_unicode); } /* For now, tuxtype is case-insensitive for input, */ /* with only uppercase for answers: */ if (key_unicode >= 97 && key_unicode <= 122) key_unicode -= 32; //convert lowercase to uppercase if (key_unicode >= 224 && key_unicode <= 255) key_unicode -= 32; //same for non-US chars LOG ("After checking for lower case:\n"); DEBUGCODE { fprintf(stderr, "key_unicode = %d\n", key_unicode); } /* Now update with case-folded value: */ ans[ans_num++] = key_unicode; } } /* Handle answer: */ for (;ans_num>0;ans_num--) { /* Pick the lowest shootable comet which has the right answer: */ lowest_y = 0; lowest = -1; for (i = 0; i < MAX_COMETS; i++) if (comets[i].alive && comets[i].shootable && comets[i].expl == 0 && comets[i].ch == ans[ans_num -1 ] && comets[i].y > lowest_y) { lowest = i; lowest_y = comets[i].y; } /* If there was an comet with this answer, destroy it! */ if (lowest != -1) { /* Destroy comet: */ comets[lowest].expl = COMET_EXPL_START; /* Make next letter in word shootable: */ comets[lowest].shootable = 0; if (comets[lowest].next) comets[lowest].next->shootable = 1; /* Fire laser: */ laser.alive = LASER_START; /* this is a hack so drawing to the center of the screen works */ if (abs(comets[lowest].x - screen->w/2) < 10) { laser.x1 = screen->w / 2; laser.y1 = screen->h; laser.x2 = laser.x1; laser.y2 = comets[lowest].y; } else { laser.x1 = screen->w / 2; laser.y1 = screen->h; laser.x2 = comets[lowest].x; laser.y2 = comets[lowest].y; } PlaySound(sounds[SND_LASER]); /* 50% of the time.. */ if (0 == (rand() % 2)) { /* ... pick an animation to play: */ if (0 == (rand() % 2)) tux_anim = IMG_TUX_YES1; else tux_anim = IMG_TUX_YAY1; tux_anim_frame = ANIM_FRAME_START; } /* Increment score: */ laser_add_score( (diff_level+1) * 5 * ((screen->h - comets[lowest].y)/20 )); } else { /* Didn't hit anything! */ PlaySound(sounds[SND_BUZZ]); if (0 == (rand() % 2)) tux_img = IMG_TUX_DRAT; else tux_img = IMG_TUX_YIPE; laser_add_score( -25 * wave); } } /* Handle start-wait countdown: */ if (level_start_wait > 0) { level_start_wait--; if (level_start_wait > LEVEL_START_WAIT_START / 4) tux_img = IMG_TUX_RELAX1; else if (level_start_wait > 0) tux_img = IMG_TUX_RELAX2; else tux_img = IMG_TUX_SIT; if (level_start_wait == LEVEL_START_WAIT_START / 4) PlaySound(sounds[SND_ALARM]); } /* If Tux pressed a button, pick a new (different!) stance: */ if (tux_pressing) { while (tux_img == old_tux_img) tux_img = IMG_TUX_CONSOLE1 + (rand() % 3); PlaySound(sounds[SND_TOCK]); } /* If Tux is being animated, show the animation: */ if (tux_anim != -1) { tux_anim_frame--; if (tux_anim_frame < 0) tux_anim = -1; else tux_img = tux_anim + 1 - (tux_anim_frame / (ANIM_FRAME_START / 2)); } /* Reset Tux to sitting if he's been doing nothing for a while: */ if (old_tux_img == tux_img) { tux_same_counter++; if (tux_same_counter >= 20) old_tux_img = tux_img = IMG_TUX_SIT; if (tux_same_counter >= 60) old_tux_img = tux_img = IMG_TUX_RELAX1; } else tux_same_counter = 0; /* Handle comets: */ num_comets_alive = 0; distanceMoved += speed; for (i = 0; i < MAX_COMETS; i++) { if (comets[i].alive) { num_comets_alive++; comets[i].x = comets[i].x + 0; comets[i].y = comets[i].y + speed; if (comets[i].y >= (screen->h - images[IMG_CITY_BLUE]->h) && comets[i].expl == 0) { /* Disable shields or destroy city: */ if (cities[comets[i].city].shields) { cities[comets[i].city].shields = 0; PlaySound(sounds[SND_SHIELDSDOWN]); laser_add_score(-50 * (diff_level+1)); } else { cities[comets[i].city].expl = CITY_EXPL_START; PlaySound(sounds[SND_EXPLOSION]); laser_add_score(-100 * (diff_level+1)); } tux_anim = IMG_TUX_FIST1; tux_anim_frame = ANIM_FRAME_START; /* Destroy comet: */ comets[i].expl = COMET_EXPL_START; } /* Handle comet explosion animation: */ if (comets[i].expl != 0) { comets[i].expl--; if (comets[i].expl == 0) comets[i].alive = 0; } } } /* Handle laser: */ if (laser.alive > 0) laser.alive--; /* Comet time! */ if (level_start_wait == 0 && (frame % 5) == 0 && gameover == 0) { if (num_attackers > 0) { /* More comets to add during this wave! */ if ((num_comets_alive < 2 || ((rand() % 4) == 0)) && distanceMoved > 40) { distanceMoved = 0; laser_add_comet(diff_level); num_attackers--; } } else { if (num_comets_alive == 0) { /* Time for the next wave! */ /* FIXME: End of level stuff goes here */ if (num_cities_alive > 0) { /* Go on to the next wave: */ wave++; laser_reset_level(diff_level); } else { /* No more cities! Game over! */ gameover = GAMEOVER_COUNTER_START; } } } } /* Handle cities: */ num_cities_alive = 0; for (i = 0; i < NUM_CITIES; i++) if (cities[i].alive) { num_cities_alive++; /* Handle animated explosion: */ if (cities[i].expl) { cities[i].expl--; if (cities[i].expl == 0) cities[i].alive = 0; } } /* Handle game-over: */ if (gameover > 0) { gameover--; if (gameover == 0) done = 1; } if ((num_cities_alive==0) && (gameover == 0)) gameover = GAMEOVER_COUNTER_START; /* Draw background: */ SDL_BlitSurface(CurrentBkgd(), NULL, screen, NULL); /* Draw wave: */ dest.x = 0; dest.y = 0; dest.w = images[IMG_WAVE]->w; dest.h = images[IMG_WAVE]->h; SDL_BlitSurface(images[IMG_WAVE], NULL, screen, &dest); sprintf(str, "%d", wave); laser_draw_numbers(str, images[IMG_WAVE]->w + (images[IMG_NUMBERS]->w / 10)); /* Draw score: */ dest.x = (screen->w - ((images[IMG_NUMBERS]->w / 10) * 7) - images[IMG_SCORE]->w); dest.y = 0; dest.w = images[IMG_SCORE]->w; dest.h = images[IMG_SCORE]->h; SDL_BlitSurface(images[IMG_SCORE], NULL, screen, &dest); sprintf(str, "%.6d", score); laser_draw_numbers(str, screen->w - ((images[IMG_NUMBERS]->w / 10) * 6)); /* Draw comets: */ for (i = 0; i < MAX_COMETS; i++) if (comets[i].alive) { /* Decide which image to display: */ if (comets[i].expl == 0) img = IMG_COMET1 + ((frame + i) % 3); else img = (IMG_COMETEX2 - (comets[i].expl / (COMET_EXPL_START / 2))); /* Draw it! */ dest.x = comets[i].x - (images[img]->w / 2); dest.y = comets[i].y - images[img]->h; dest.w = images[img]->w; dest.h = images[img]->h; SDL_BlitSurface(images[img], NULL, screen, &dest); } /* Draw letters: */ for (i = 0; i < MAX_COMETS; i++) if (comets[i].alive && comets[i].expl == 0) laser_draw_let(comets[i].ch, comets[i].x, comets[i].y); /* Draw cities: */ if (frame%2 == 0) NEXT_FRAME(shield); for (i = 0; i < NUM_CITIES; i++) { /* Decide which image to display: */ if (cities[i].alive) { if (cities[i].expl == 0) img = IMG_CITY_BLUE; else img = (IMG_CITY_BLUE_EXPL5 - (cities[i].expl / (CITY_EXPL_START / 5))); } else img = IMG_CITY_BLUE_DEAD; /* Change image to appropriate color: */ img += ((wave % MAX_CITY_COLORS) * (IMG_CITY_GREEN - IMG_CITY_BLUE)); /* Draw it! */ dest.x = cities[i].x - (images[img]->w / 2); dest.y = (screen->h) - (images[img]->h); dest.w = (images[img]->w); dest.h = (images[img]->h); SDL_BlitSurface(images[img], NULL, screen, &dest); /* Draw sheilds: */ if (cities[i].shields) { dest.x = cities[i].x - (shield->frame[shield->cur]->w / 2); dest.h = (screen->h) - (shield->frame[shield->cur]->h); dest.w = src.w; dest.h = src.h; SDL_BlitSurface( shield->frame[shield->cur], NULL, screen, &dest); } } /* Draw laser: */ if (laser.alive) laser_draw_line(laser.x1, laser.y1, laser.x2, laser.y2, 255 / (LASER_START - laser.alive), 192 / (LASER_START - laser.alive), 64); laser_draw_console_image(IMG_CONSOLE); if (gameover > 0) tux_img = IMG_TUX_FIST1 + ((frame / 2) % 2); laser_draw_console_image(tux_img); /* Draw "Game Over" */ if (gameover > 0) { dest.x = (screen->w - images[IMG_GAMEOVER]->w) / 2; dest.y = (screen->h - images[IMG_GAMEOVER]->h) / 2; dest.w = images[IMG_GAMEOVER]->w; dest.h = images[IMG_GAMEOVER]->h; SDL_BlitSurface(images[IMG_GAMEOVER], NULL, screen, &dest); } /* Swap buffers: */ SDL_Flip(screen); /* If we're in "PAUSE" mode, pause! */ if (paused) { quit = Pause(); paused = 0; } /* Keep playing music: */ if (settings.sys_sound && !Mix_PlayingMusic()) MusicPlay(musics[MUS_GAME + (rand() % NUM_MUSICS)], 0); /* Pause (keep frame-rate event) */ DEBUGCODE { fprintf(stderr, "now_time = %d\tlast_time = %d, elapsed time = %d\n", now_time, last_time, now_time - last_time); } now_time = SDL_GetTicks(); if (now_time < last_time + FPS) SDL_Delay(last_time + FPS - now_time); }
Font::Font(const string& fileName) { guiCam = new Camera(true); vertices = new vector<Vertex>(); indices = new vector<int>(); TTF_Font *font = TTF_OpenFont(fileName.c_str(), 64); if (!font) printf("Unable to load font %s-%s\n", fileName.c_str(), TTF_GetError()); //first of all, need to render out the text atlas to use for vertex rendering SDL_Surface *atlasSurf = SDL_CreateRGBSurface(0, width, height, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF); //to track where to put next glyphs int x = 0, y = 0; //marks where the newline starts int newY = 0; //32 being space, 126 being ~, all visible characters for (uint glyph = 32; glyph < 127; glyph++) { SDL_Surface *glyphSurf = TTF_RenderGlyph_Blended(font, glyph, {255, 255, 255}); int w = glyphSurf->w, h = glyphSurf->h; if (x + w > width) //if we can't go right anymore { x = 0; //start from left y += newY; //on a new line newY = 0; //start looking for a new newline offset } SDL_Rect r = { x, y, w, h }; SDL_BlitSurface(glyphSurf, NULL, atlasSurf, &r); RECTF rect = { x, y, w, h - 4 }; //adding a 4pixel boundary from the bottom rects[glyph - 32] = rect; //saving the unnormalized UVs x += w; newY = glm::max(newY, h); SDL_FreeSurface(glyphSurf); } //now normalizing the UVs int count = 127 - 32; for (int i = 0; i < count; i++) { RECTF r = rects[i]; r.x /= (float)width; r.y /= (float)height; r.w /= (float)width; r.h /= (float)height; rects[i] = r; } //for debug SDL_SaveBMP(atlasSurf, "atlas.bmp"); GLuint atlasText = ConvertSDLSurfaceToTexture(atlasSurf); SDL_FreeSurface(atlasSurf); TTF_CloseFont(font); //saving the previous state GLint currActive; glGetIntegerv(GL_ACTIVE_TEXTURE, &currActive); //pushing our texture and setting standard settings glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, atlasText); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); //restoring it glActiveTexture(currActive); m = new Model(); m->SetUpAttrib(0, 3, GL_FLOAT, 0); m->SetUpAttrib(1, 2, GL_FLOAT, sizeof(vec3) + sizeof(vec4)); shader = new ShaderProgram(SHADER_PATH + "guiVS.glsl", SHADER_PATH + "guiFS.glsl"); shader->BindAttribLoc(0, "vertexPosition"); shader->BindAttribLoc(1, "uvs"); shader->Link(); t = new Texture(atlasText); renderer = new Renderer(); renderer->SetModel(m, GL_TRIANGLES); renderer->SetShaderProgram(shader); renderer->AddTexture(t); }
void present_rendering(std::vector<rt::core::Surface2d*>& surfaces) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Failed to init SDL"); exit(0); } SDL_Window* window = SDL_CreateWindow("Raytracer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WND_SIZE_X, WND_SIZE_Y, 0); REQUIRE(window); //make sure we do not have to do some kind of resizing //later may be supported but for *now* - no int w = 0, h = 0; SDL_GetWindowSize(window, &w, &h); REQUIRE(w == WND_SIZE_X); REQUIRE(h == WND_SIZE_Y); SDL_Surface* surface = SDL_GetWindowSurface(window); REQUIRE(surface); int current_image = 0; bool running = true; while (running) { SDL_Event e; while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } else if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_n) { current_image++; if (current_image >= surfaces.size()) { current_image = 0; } } else if (e.key.keysym.sym == SDLK_s) { for (int i = 0; i < surfaces.size(); ++i) { std::stringstream ss; ss << "file"; ss << i; ss << ".bmp"; rt::core::Surface2d* to_copy = surfaces[i]; SDL_LockSurface(surface); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { putpixel(surface, x, y, to_copy->pixel(x, y)); } } SDL_UnlockSurface(surface); SDL_UpdateWindowSurface(window); SDL_SaveBMP(surface, ss.str().c_str()); } } } } rt::core::Surface2d* to_copy = surfaces[current_image]; SDL_LockSurface(surface); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { putpixel(surface, x, y, to_copy->pixel(x, y)); } } SDL_UnlockSurface(surface); SDL_UpdateWindowSurface(window); SDL_Delay(WAIT_TIME); } SDL_DestroyWindow(window); SDL_Quit(); }
static int setup_test(int argc, char **argv) { const char *dumpfile = NULL; SDL_Surface *bmp = NULL; Uint32 dstbpp = 32; Uint32 dstrmask = 0x00FF0000; Uint32 dstgmask = 0x0000FF00; Uint32 dstbmask = 0x000000FF; Uint32 dstamask = 0x00000000; Uint32 dstflags = 0; int dstw = 640; int dsth = 480; Uint32 srcbpp = 32; Uint32 srcrmask = 0x00FF0000; Uint32 srcgmask = 0x0000FF00; Uint32 srcbmask = 0x000000FF; Uint32 srcamask = 0x00000000; Uint32 srcflags = 0; int srcw = 640; int srch = 480; int screenSurface = 0; int i; for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (strcmp(arg, "--dstbpp") == 0) dstbpp = atoi(argv[++i]); else if (strcmp(arg, "--dstrmask") == 0) dstrmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstgmask") == 0) dstgmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstbmask") == 0) dstbmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstamask") == 0) dstamask = atoi_hex(argv[++i]); else if (strcmp(arg, "--dstwidth") == 0) dstw = atoi(argv[++i]); else if (strcmp(arg, "--dstheight") == 0) dsth = atoi(argv[++i]); else if (strcmp(arg, "--dsthwsurface") == 0) dstflags |= SDL_HWSURFACE; else if (strcmp(arg, "--srcbpp") == 0) srcbpp = atoi(argv[++i]); else if (strcmp(arg, "--srcrmask") == 0) srcrmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcgmask") == 0) srcgmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcbmask") == 0) srcbmask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcamask") == 0) srcamask = atoi_hex(argv[++i]); else if (strcmp(arg, "--srcwidth") == 0) srcw = atoi(argv[++i]); else if (strcmp(arg, "--srcheight") == 0) srch = atoi(argv[++i]); else if (strcmp(arg, "--srchwsurface") == 0) srcflags |= SDL_HWSURFACE; else if (strcmp(arg, "--seconds") == 0) testSeconds = atoi(argv[++i]); else if (strcmp(arg, "--screen") == 0) screenSurface = 1; else if (strcmp(arg, "--dumpfile") == 0) dumpfile = argv[++i]; else { fprintf(stderr, "Unknown commandline option: %s\n", arg); return(0); } } if (SDL_Init(SDL_INIT_VIDEO) == -1) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); return(0); } bmp = SDL_LoadBMP("sample.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP failed: %s\n", SDL_GetError()); SDL_Quit(); return(0); } if ((dstflags & SDL_HWSURFACE) == 0) dstflags |= SDL_SWSURFACE; if ((srcflags & SDL_HWSURFACE) == 0) srcflags |= SDL_SWSURFACE; if (screenSurface) dest = SDL_SetVideoMode(dstw, dsth, dstbpp, dstflags); else { dest = SDL_CreateRGBSurface(dstflags, dstw, dsth, dstbpp, dstrmask, dstgmask, dstbmask, dstamask); } if (dest == NULL) { fprintf(stderr, "dest surface creation failed: %s\n", SDL_GetError()); SDL_Quit(); return(0); } src = SDL_CreateRGBSurface(srcflags, srcw, srch, srcbpp, srcrmask, srcgmask, srcbmask, srcamask); if (src == NULL) { fprintf(stderr, "src surface creation failed: %s\n", SDL_GetError()); SDL_Quit(); return(0); } /* set some sane defaults so we can see if the blit code is broken... */ SDL_FillRect(dest, NULL, SDL_MapRGB(dest->format, 0, 0, 0)); SDL_FillRect(src, NULL, SDL_MapRGB(src->format, 0, 0, 0)); blitCentered(src, bmp); SDL_FreeSurface(bmp); if (dumpfile) SDL_SaveBMP(src, dumpfile); /* make sure initial convert is sane. */ output_details(); return(1); }
int main ( int argc, char** argv ) { //make sure we have all the necessary arguments if( argc < 4 ) { fprintf(stderr, "Usage: %s (input texture filename) (texton neighborhood diameter) \n", argv[0]); fprintf(stderr, " (output size) [number threads] [r weight] [g weight] [b weight]\n"); fprintf(stderr, " Options in () are required, options in [] are optional.\n"); fprintf(stderr, " Note that if you want to set r weight, number threads must be set too.\n"); fprintf(stderr, " Input texture reading is handled by SDL_Image so the file can be tga, bmp, \n"); fprintf(stderr, " pnm, xpm, xcf, pcx, gif, jpg, lbm, or png.\n"); fprintf(stderr, " If [number threads] is set to 0, no threads will be generated. If it is set\n"); fprintf(stderr, " to 1, one thread will be generated to do all the work. Default is %d.\n", TEX_SYN_THREADS); fprintf(stderr, " [rgb weight] defines how much weight to give to the r, g, and b channels\n"); fprintf(stderr, " when calculating the similarity between two neighborhoods.\n"); fprintf(stderr, " These values are only used if rgb weighting is enabled in the code.\n"); fprintf(stderr, " Default Values are %f, %f, and %f respectively.\n", TEX_SYN_RED_WEIGHT, TEX_SYN_GREEN_WEIGHT, TEX_SYN_BLUE_WEIGHT); exit(EXIT_FAILURE); } //looks good, start loading values: //diameter textonDiameter = atoi(argv[2]); //make sure textonDiameter is odd, add one to it if it is even. if(textonDiameter % 2 == 0) textonDiameter++; //output size outputSize = atoi(argv[3]); //# threads if(argc >= 5) TEX_SYN_THREADS = atoi(argv[4]); //r weight if(argc >= 6) TEX_SYN_RED_WEIGHT = atof(argv[5]); //g weight if(argc >= 7) TEX_SYN_GREEN_WEIGHT = atof(argv[6]); //b weight if(argc >= 8) TEX_SYN_BLUE_WEIGHT = atof(argv[7]); debug("Will generate texture using file %s as a kernel and\n", argv[1]); debug("\tneighborhood size %d to generate unique %d x %d texture\n", textonDiameter, outputSize, outputSize); #ifdef TEX_SYN_USE_MULTIRESOLUTION debug("\twith a multi-resolution synthesis algorithm.\n"); #else debug("\twith a single-resolution synthesis algorithm.\n"); #endif if(TEX_SYN_THREADS == 0) debug("No threads will be generated to compare neighborhoods.\n"); else debug("%d threads will be generated to compare neighborhoods.\n", TEX_SYN_THREADS); #ifdef TEX_SYN_WEIGHTED_COLORS debug("When comparing neighborhoods, red, green, and blue will be weighted\n"); debug("\twith the values %f, %f, and %f respectively\n", TEX_SYN_RED_WEIGHT, TEX_SYN_GREEN_WEIGHT, TEX_SYN_BLUE_WEIGHT); #else debug("When comparing neighborhoods, red, green, and blue will not be weighted\n"); #endif //initialize SDL debug("Initializing SDL\n"); initSDL(outputSize, outputSize); // load an image debug("Loading Image %s\n", argv[1]); SDL_Surface *loadedTexture = IMG_Load(argv[1]); if (!loadedTexture) { printf("Unable to load image %s: %s\n", argv[1], SDL_GetError()); return 1; } //convert to be the same format as the display (32 bit) debug("Convert input texture to useable format\n"); inputTexture = SDL_DisplayFormat(loadedTexture); SDL_FreeSurface(loadedTexture); //run the texture synthesis SDL_Surface *outputTexture = textureSynthesis(inputTexture, outputSize, outputSize); //this is the texture that will be rendered on screen: SDL_Surface *renderTexture = outputTexture; // centre the bitmap on screen SDL_Rect dstrect; dstrect.x = (screen->w - renderTexture->w) / 2; dstrect.y = (screen->h - renderTexture->h) / 2; // program main loop debug("Entering display loop...\n"); while (!checkEvents()) { // DRAWING STARTS HERE // clear screen SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 255, 255, 255)); // draw bitmap SDL_BlitSurface(renderTexture, 0, screen, &dstrect); // DRAWING ENDS HERE // finally, update the screen :) SDL_Flip(screen); } // end main loop //save output texture char stripped[256]; char outName[256]; int start = 0, end = 0; for(int i = strlen(argv[1]) - 1; i>=0; i--) { if( argv[1][i] == '/' && i > start ) start = i + 1; if( argv[1][i] == '.' && i > end ) end = i; } int i = 0; for( int n = start; n < end; n++, i++) stripped[i] = argv[1][n]; stripped[i] = '\0'; sprintf(outName, "synthesizedTextures/%s-%dx%d,%d.bmp", stripped, outputSize, outputSize, textonDiameter); debug("Saving the output image to %s\n", outName); if(SDL_SaveBMP(outputTexture, outName) < 0) { fprintf(stderr, "ERROR saving output texture to file %s: %s\n", outName, SDL_GetError()); exit(EXIT_FAILURE); } debug("Cleaning up\n"); // free loaded bitmap SDL_FreeSurface(inputTexture); SDL_FreeSurface(outputTexture); //note, sdl_quit doesn't need to be here because it's told to run //on quit in the init function. return 0; }
int main(int argc, const char**argv) { if (argc < 2) return -1; int grid[size][size]; int x = 0, y = 0; FILE *fp; char ch; if((fp = fopen(argv[ 1 ],"r"))==NULL) { printf("Cannot open file.\n"); exit(1); } while(ch != EOF) { ch = fgetc( fp ); if (ch == '\n') { x = 0; y++; continue; } else if (ch == 'o') grid[x][y] = 1; else if (ch == ' ') grid[x][y] = 0; x++; if (x >= size) continue; } fclose(fp); /*for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) std::cout << grid[y][x]; std::cout << "\n"; }*/ SDL_Surface *screen; SDL_Event event; int keypress = 0, seq = 0; if (SDL_Init(SDL_INIT_VIDEO) < 0 ) return 1; if (!(screen = SDL_SetVideoMode(WIDTH, HEIGHT, DEPTH, SDL_HWSURFACE))) { SDL_Quit(); return 1; } if (argc == 3) keypress = 1; do { DrawScreen(screen, grid); while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: keypress = 1; break; case SDL_KEYDOWN: keypress = 1; break; } } }while(!keypress); if (argc == 3) SDL_SaveBMP(screen, argv[2]); SDL_Quit(); return 0; }
bool OSystem_SDL::saveScreenshot(const char *filename) { assert(_hwscreen != NULL); Common::StackLock lock(_graphicsMutex); // Lock the mutex until this function ends return SDL_SaveBMP(_hwscreen, filename) == 0; }
void SDLRenderer::do_take_screenshot() { // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it? int width; int height; if (SDL_GetRendererOutputSize(m_renderer, &width, &height) != 0) { log_warning << "SDL_GetRenderOutputSize failed: " << SDL_GetError() << std::endl; } else { #if SDL_BYTEORDER == SDL_BIG_ENDIAN Uint32 rmask = 0xff000000; Uint32 gmask = 0x00ff0000; Uint32 bmask = 0x0000ff00; Uint32 amask = 0x000000ff; #else Uint32 rmask = 0x000000ff; Uint32 gmask = 0x0000ff00; Uint32 bmask = 0x00ff0000; Uint32 amask = 0xff000000; #endif SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, rmask, gmask, bmask, amask); if (!surface) { log_warning << "SDL_CreateRGBSurface failed: " << SDL_GetError() << std::endl; } else { int ret = SDL_RenderReadPixels(m_renderer, NULL, SDL_PIXELFORMAT_ABGR8888, surface->pixels, surface->pitch); if (ret != 0) { log_warning << "SDL_RenderReadPixels failed: " << SDL_GetError() << std::endl; } else { // save screenshot static const std::string writeDir = PHYSFS_getWriteDir(); static const std::string dirSep = PHYSFS_getDirSeparator(); static const std::string baseName = "screenshot"; static const std::string fileExt = ".bmp"; std::string fullFilename; for (int num = 0; num < 1000; num++) { std::ostringstream oss; oss << baseName; oss << std::setw(3) << std::setfill('0') << num; oss << fileExt; std::string fileName = oss.str(); fullFilename = writeDir + dirSep + fileName; if (!PHYSFS_exists(fileName.c_str())) { SDL_SaveBMP(surface, fullFilename.c_str()); log_info << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl; return; } } log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl; } } } }
void image_save(struct image *img, char *name) { // sauvegarde SDL SDL_SaveBMP(img->priv, name); }
bool MenuBase::doInput(SDL_Event &event) { switch (event.type) { case (SDL_KEYDOWN): { // Look for a keypress switch(event.key.keysym.sym) { case SDLK_ESCAPE: { if((pChildWindow == NULL) && (bAllowQuiting == true)) { quit(); } } break; case SDLK_RETURN: { if(SDL_GetModState() & KMOD_ALT) { SDL_WM_ToggleFullScreen(screen); } } break; case SDLK_p: { if(SDL_GetModState() & KMOD_CTRL) { // fall through to SDLK_PRINT } else { break; // do not fall through } } // fall through case SDLK_PRINT: case SDLK_SYSREQ: { std::string screenshotFilename; int i = 1; do { screenshotFilename = "Screenshot" + stringify(i) + ".bmp"; i++; } while(existsFile(screenshotFilename) == true); SDL_SaveBMP(screen, screenshotFilename.c_str()); } break; case SDLK_TAB: { if(SDL_GetModState() & KMOD_ALT) { SDL_WM_IconifyWindow(); } } break; default: { } break; } } break; case SDL_MOUSEMOTION: { SDL_MouseMotionEvent* mouse = &event.motion; drawnMouseX = mouse->x; drawnMouseY = mouse->y; } break; case SDL_QUIT: { if((pChildWindow == NULL) && (bAllowQuiting == true)) { quit(); } } break; default: { } break; } handleInput(event); return !quiting; }
/* Saves a GyImage as a to a file in filename in BMP format. Return NULL if it failed, img on success. */ GyImage * gyimage_savebmp(GyImage * img, const char * filename) { SDL_Surface * surf = gyimage_surface(img); int res = SDL_SaveBMP(surf, filename); if (res < 0) return NULL; return img; }
void OEMFGame :: run() { // clearWithColor(0x000000, false); // refresh(); refreshCentered(); refreshScoreBoard(); updateScreen(); Uint32 start = SDL_GetTicks(); Sint32 waitTime = 0; SDL_Event event; while (!m_done) { if ((waitTime = SDL_GetTicks() - start) >= m_frameDuration) { start = SDL_GetTicks(); //refresh(); refreshCentered(); refreshScoreBoard(); updateScreen(); } handleInput(); updatePhysics(); // handle flags if (m_requestFlagDie) { m_requestFlagDie = false; die(); } if (m_requestFlagEnd) { m_requestFlagEnd = false; endLevel(); initialize(); } Uint32 sym; /* Check for events */ while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEMOTION: break; case SDL_MOUSEBUTTONDOWN: break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { string options[2] = {string("No"), string("Yes")}; if (chooseList(0, "Are you sure you want to end the game?", options, 2) == 1) m_done = 1; } else if (event.key.keysym.sym == SDLK_q) { m_frameDuration-=10; } else if (event.key.keysym.sym == SDLK_w) { m_frameDuration+=10; } else if (event.key.keysym.sym == SDLK_e) { m_delayTime--; printf("m_delayTime = %d\n", m_delayTime); } else if (event.key.keysym.sym == SDLK_r) { m_delayTime++; printf("m_delayTime = %d\n", m_delayTime); } else if (event.key.keysym.sym == SDLK_p) { SDL_SaveBMP(m_screen, "screenshot.bmp"); } else { // key array sym = event.key.keysym.sym; if (sym < KEYCOUNT) { m_keyDown[sym] = true; } } break; case SDL_KEYUP: // key array sym = event.key.keysym.sym; if (sym < KEYCOUNT) { m_keyDown[sym] = false; } break; case SDL_QUIT: m_done = 1; break; default: break; } } // Uint32 start2 = SDL_GetTicks(); // while (SDL_GetTicks() - start2 < m_delayTime); SDL_Delay(m_delayTime); // frameDuration = SDL_GetTicks() - start; // waitTime = 20 - (Sint32) frameDuration; // if (waitTime > 0) // SDL_Delay(waitTime); } }
/* Compare surfaces */ int SDLTest_CompareSurfaces(SDL_Surface *surface, SDL_Surface *referenceSurface, int allowable_error) { int ret; int i,j; int bpp, bpp_reference; Uint8 *p, *p_reference; int dist; Uint8 R, G, B, A; Uint8 Rd, Gd, Bd, Ad; char imageFilename[128]; char referenceFilename[128]; /* Validate input surfaces */ if (surface == NULL || referenceSurface == NULL) { return -1; } /* Make sure surface size is the same. */ if ((surface->w != referenceSurface->w) || (surface->h != referenceSurface->h)) { return -2; } /* Sanitize input value */ if (allowable_error<0) { allowable_error = 0; } SDL_LockSurface( surface ); SDL_LockSurface( referenceSurface ); ret = 0; bpp = surface->format->BytesPerPixel; bpp_reference = referenceSurface->format->BytesPerPixel; /* Compare image - should be same format. */ for (j=0; j<surface->h; j++) { for (i=0; i<surface->w; i++) { p = (Uint8 *)surface->pixels + j * surface->pitch + i * bpp; p_reference = (Uint8 *)referenceSurface->pixels + j * referenceSurface->pitch + i * bpp_reference; SDL_GetRGBA(*(Uint32*)p, surface->format, &R, &G, &B, &A); SDL_GetRGBA(*(Uint32*)p_reference, referenceSurface->format, &Rd, &Gd, &Bd, &Ad); dist = 0; dist += (R-Rd)*(R-Rd); dist += (G-Gd)*(G-Gd); dist += (B-Bd)*(B-Bd); /* Allow some difference in blending accuracy */ if (dist > allowable_error) { ret++; } } } SDL_UnlockSurface( surface ); SDL_UnlockSurface( referenceSurface ); /* Save test image and reference for analysis on failures */ _CompareSurfaceCount++; if (ret != 0) { SDL_snprintf(imageFilename, 127, "CompareSurfaces%04d_TestOutput.bmp", _CompareSurfaceCount); SDL_SaveBMP(surface, imageFilename); SDL_snprintf(referenceFilename, 127, "CompareSurfaces%04d_Reference.bmp", _CompareSurfaceCount); SDL_SaveBMP(referenceSurface, referenceFilename); SDLTest_LogError("Surfaces from failed comparison saved as '%s' and '%s'", imageFilename, referenceFilename); } return ret; }
void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename) { SDL_SaveBMP((SDL_Surface *)surf,filename); }
bool THRenderTarget::takeScreenshot(const char* sFile) { return SDL_SaveBMP(m_pSurface, sFile) == 0; }
int main(int argc, char *argv[]) { char *argv0 = argv[0]; SDL_Surface *screen; TTF_Font *font; SDL_Surface *text; int ptsize; int i, done; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; GLenum gl_error; GLuint texture; int x, y, w, h; GLfloat texcoord[4]; GLfloat texMinX, texMinY; GLfloat texMaxX, texMaxY; float color[8][3]= {{ 1.0, 1.0, 0.0}, { 1.0, 0.0, 0.0}, { 0.0, 0.0, 0.0}, { 0.0, 1.0, 0.0}, { 0.0, 1.0, 1.0}, { 1.0, 1.0, 1.0}, { 1.0, 0.0, 1.0}, { 0.0, 0.0, 1.0}}; float cube[8][3]= {{ 0.5, 0.5, -0.5}, { 0.5, -0.5, -0.5}, {-0.5, -0.5, -0.5}, {-0.5, 0.5, -0.5}, {-0.5, 0.5, 0.5}, { 0.5, 0.5, 0.5}, { 0.5, -0.5, 0.5}, {-0.5, -0.5, 0.5}}; SDL_Event event; int renderstyle; int dump; enum { RENDER_LATIN1, RENDER_UTF8, RENDER_UNICODE } rendertype; char *message; /* Look for special execution mode */ dump = 0; /* Look for special rendering types */ renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; /* Default is black and white */ forecol = &black; backcol = &white; for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) { if ( strcmp(argv[i], "-utf8") == 0 ) { rendertype = RENDER_UTF8; } else if ( strcmp(argv[i], "-unicode") == 0 ) { rendertype = RENDER_UNICODE; } else if ( strcmp(argv[i], "-b") == 0 ) { renderstyle |= TTF_STYLE_BOLD; } else if ( strcmp(argv[i], "-i") == 0 ) { renderstyle |= TTF_STYLE_ITALIC; } else if ( strcmp(argv[i], "-u") == 0 ) { renderstyle |= TTF_STYLE_UNDERLINE; } else if ( strcmp(argv[i], "-dump") == 0 ) { dump = 1; } else if ( strcmp(argv[i], "-fgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } forecol->r = (Uint8)r; forecol->g = (Uint8)g; forecol->b = (Uint8)b; } else if ( strcmp(argv[i], "-bgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } backcol->r = (Uint8)r; backcol->g = (Uint8)g; backcol->b = (Uint8)b; } else { fprintf(stderr, Usage, argv0); return(1); } } argv += i; argc -= i; /* Check usage */ if ( ! argv[0] ) { fprintf(stderr, Usage, argv0); return(1); } /* Initialize SDL */ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); return(2); } atexit(SDL_Quit); /* Initialize the TTF library */ if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); return(2); } atexit(TTF_Quit); /* Open the font file with the requested point size */ ptsize = 0; if ( argc > 1 ) { ptsize = atoi(argv[1]); } if ( ptsize == 0 ) { i = 2; ptsize = DEFAULT_PTSIZE; } else { i = 3; } font = TTF_OpenFont(argv[0], ptsize); if ( font == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, argv[0], SDL_GetError()); return(2); } TTF_SetFontStyle(font, renderstyle); if( dump ) { for( i = 48; i < 123; i++ ) { SDL_Surface* glyph = NULL; glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol ); if( glyph ) { char outname[64]; sprintf( outname, "glyph-%d.bmp", i ); SDL_SaveBMP( glyph, outname ); } } return( 0 ); } /* Set a 640x480 video mode */ screen = SDL_SetVideoMode(640, 480, 0, SDL_OPENGL); if ( screen == NULL ) { fprintf(stderr, "Couldn't set 640x480 OpenGL mode: %s\n", SDL_GetError()); return(2); } /* Render and center the message */ if ( argc > 2 ) { message = argv[2]; } else { message = DEFAULT_TEXT; } switch (rendertype) { case RENDER_LATIN1: text = TTF_RenderText_Blended(font, message, *forecol); break; case RENDER_UTF8: text = TTF_RenderUTF8_Blended(font, message, *forecol); break; case RENDER_UNICODE: { /* This doesn't actually work because you can't pass UNICODE text in via command line, AFAIK, but... */ Uint16 unicode_text[BUFSIZ]; int index; for ( index = 0; (message[0] || message[1]); ++index ) { unicode_text[index] = ((Uint8 *)message)[0]; unicode_text[index] <<= 8; unicode_text[index] |= ((Uint8 *)message)[1]; message += 2; } text = TTF_RenderUNICODE_Blended(font, unicode_text, *forecol); } break; default: text = NULL; /* This shouldn't happen */ break; } if ( text == NULL ) { fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError()); TTF_CloseFont(font); return(2); } x = (screen->w - text->w)/2; y = (screen->h - text->h)/2; w = text->w; h = text->h; printf("Font is generally %d big, and string is %hd big\n", TTF_FontHeight(font), text->h); /* Convert the text into an OpenGL texture */ glGetError(); texture = SDL_GL_LoadTexture(text, texcoord); if ( (gl_error = glGetError()) != GL_NO_ERROR ) { /* If this failed, the text may exceed texture size limits */ printf("Warning: Couldn't create texture: 0x%x\n", gl_error); } /* Make texture coordinates easy to understand */ texMinX = texcoord[0]; texMinY = texcoord[1]; texMaxX = texcoord[2]; texMaxY = texcoord[3]; /* We don't need the original text surface anymore */ SDL_FreeSurface(text); /* Initialize the GL state */ glViewport( 0, 0, screen->w, screen->h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glOrtho( -2.0, 2.0, -2.0, 2.0, -20.0, 20.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); /* Wait for a keystroke, and blit text on mouse press */ done = 0; while ( ! done ) { while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_MOUSEMOTION: x = event.motion.x - w/2; y = event.motion.y - h/2; break; case SDL_KEYDOWN: case SDL_QUIT: done = 1; break; default: break; } } /* Clear the screen */ glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Draw the spinning cube */ glBegin( GL_QUADS ); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[7]); glVertex3fv(cube[7]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[5]); glVertex3fv(cube[5]); glColor3fv(color[0]); glVertex3fv(cube[0]); glColor3fv(color[3]); glVertex3fv(cube[3]); glColor3fv(color[4]); glVertex3fv(cube[4]); glColor3fv(color[6]); glVertex3fv(cube[6]); glColor3fv(color[1]); glVertex3fv(cube[1]); glColor3fv(color[2]); glVertex3fv(cube[2]); glColor3fv(color[7]); glVertex3fv(cube[7]); glEnd( ); /* Rotate the cube */ glMatrixMode(GL_MODELVIEW); glRotatef(5.0, 1.0, 1.0, 1.0); /* Show the text on the screen */ SDL_GL_Enter2DMode(); glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(texMinX, texMinY); glVertex2i(x, y ); glTexCoord2f(texMaxX, texMinY); glVertex2i(x+w, y ); glTexCoord2f(texMinX, texMaxY); glVertex2i(x, y+h); glTexCoord2f(texMaxX, texMaxY); glVertex2i(x+w, y+h); glEnd(); SDL_GL_Leave2DMode(); /* Swap the buffers so everything is visible */ SDL_GL_SwapBuffers( ); } TTF_CloseFont(font); return(0); }
int interface_capture (SDL_Surface *screen, int w, int h) {{{ const char *extension[]={".jpeg",".png",".bmp"}; /* This function is called to take a picure from the cam * and save it to a file */ char *capture_filename; SDL_Surface *tmp_surface; struct stat file_stat; int file_size = -1; /* Get a free filename */ capture_filename = getNewFilename (Dump_Path(), Dump_Prefix(), extension [configuration.dump_mode]); if (NULL == capture_filename) return -1; /* Capture the image*/ tmp_surface = get_ImageSurface(screen, w, h); /* {{{ Write image */ { unsigned char *data; int i; unsigned char tmp; data = (unsigned char*)tmp_surface->pixels; if ( SDL_MUSTLOCK(screen) ) { if ( SDL_LockSurface(screen) < 0 ) { fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError()); free (capture_filename); return -1; } } /* swap Red and blue */ for (i=0; i<tmp_surface->w*tmp_surface->h*3; i+=3) { tmp = data[i]; data[i] = data[i+2]; data[i+2] = tmp; } if ( SDL_MUSTLOCK (screen) ) { SDL_UnlockSurface (screen); } switch (configuration.dump_mode) { case 0: write_file_jpeg (capture_filename, (unsigned char*)tmp_surface->pixels, tmp_surface->w, tmp_surface->h); break; case 1: write_file_png (capture_filename, (unsigned char*)tmp_surface->pixels, (unsigned int)tmp_surface->w, (unsigned int)tmp_surface->h); break; case 2: SDL_SaveBMP(tmp_surface, capture_filename); break; default: fprintf(stderr, "Unsuported capture format.\n"); break; } } /* }}} */ SDL_FreeSurface(tmp_surface); // if (configuration.debug > 0) printf("Saved file: %s\n", capture_filename); /* {{{ FTP-Stuff */ if( configuration.ftp_host !=NULL && configuration.ftp_user !=NULL && configuration.ftp_pass !=NULL && configuration.ftp_file !=NULL ) { if (init_ftp (configuration.ftp_host, configuration.ftp_user, configuration.ftp_pass)) { if (configuration.debug > 0) printf ("Starte FTP Upload\n"); if (configuration.ftp_temp != NULL) { if (configuration.debug > 0) printf ("Using FTP Rename Method\n"); if (ftp_send (capture_filename, configuration.ftp_temp)) ftp_rename (configuration.ftp_temp, configuration.ftp_file); } else ftp_send (capture_filename, configuration.ftp_file); } } /* }}} */ if (!stat (capture_filename, &file_stat)) { file_size = file_stat.st_size; } free (capture_filename); return file_size; }}}
int main(int argc, char *argv[]) { char *argv0 = argv[0]; SDL_Surface *screen; TTF_Font *font; SDL_Surface *text, *temp; int ptsize; int i, done; int rdiff, gdiff, bdiff; SDL_Color colors[NUM_COLORS]; SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 }; SDL_Color black = { 0x00, 0x00, 0x00, 0 }; SDL_Color *forecol; SDL_Color *backcol; SDL_Rect dstrect; SDL_Event event; int rendersolid; int renderstyle; int outline; int hinting; int kerning; int dump; enum { RENDER_LATIN1, RENDER_UTF8, RENDER_UNICODE } rendertype; char *message, string[128]; /* Look for special execution mode */ dump = 0; /* Look for special rendering types */ rendersolid = 0; renderstyle = TTF_STYLE_NORMAL; rendertype = RENDER_LATIN1; outline = 0; hinting = TTF_HINTING_NORMAL; kerning = 1; /* Default is black and white */ forecol = &black; backcol = &white; for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) { if ( strcmp(argv[i], "-solid") == 0 ) { rendersolid = 1; } else if ( strcmp(argv[i], "-utf8") == 0 ) { rendertype = RENDER_UTF8; } else if ( strcmp(argv[i], "-unicode") == 0 ) { rendertype = RENDER_UNICODE; } else if ( strcmp(argv[i], "-b") == 0 ) { renderstyle |= TTF_STYLE_BOLD; } else if ( strcmp(argv[i], "-i") == 0 ) { renderstyle |= TTF_STYLE_ITALIC; } else if ( strcmp(argv[i], "-u") == 0 ) { renderstyle |= TTF_STYLE_UNDERLINE; } else if ( strcmp(argv[i], "-s") == 0 ) { renderstyle |= TTF_STYLE_STRIKETHROUGH; } else if ( strcmp(argv[i], "-outline") == 0 ) { if ( sscanf (argv[++i], "%d", &outline) != 1 ) { fprintf(stderr, Usage, argv0); return(1); } } else if ( strcmp(argv[i], "-hintlight") == 0 ) { kerning = TTF_HINTING_LIGHT; } else if ( strcmp(argv[i], "-hintmono") == 0 ) { kerning = TTF_HINTING_MONO; } else if ( strcmp(argv[i], "-hintnone") == 0 ) { kerning = TTF_HINTING_NONE; } else if ( strcmp(argv[i], "-nokerning") == 0 ) { kerning = 0; } else if ( strcmp(argv[i], "-dump") == 0 ) { dump = 1; } else if ( strcmp(argv[i], "-fgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } forecol->r = (Uint8)r; forecol->g = (Uint8)g; forecol->b = (Uint8)b; } else if ( strcmp(argv[i], "-bgcol") == 0 ) { int r, g, b; if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) { fprintf(stderr, Usage, argv0); return(1); } backcol->r = (Uint8)r; backcol->g = (Uint8)g; backcol->b = (Uint8)b; } else { fprintf(stderr, Usage, argv0); return(1); } } argv += i; argc -= i; /* Check usage */ if ( ! argv[0] ) { fprintf(stderr, Usage, argv0); return(1); } /* Initialize SDL */ if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); return(2); } /* Initialize the TTF library */ if ( TTF_Init() < 0 ) { fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError()); SDL_Quit(); return(2); } /* Open the font file with the requested point size */ ptsize = 0; if ( argc > 1 ) { ptsize = atoi(argv[1]); } if ( ptsize == 0 ) { i = 2; ptsize = DEFAULT_PTSIZE; } else { i = 3; } font = TTF_OpenFont(argv[0], ptsize); if ( font == NULL ) { fprintf(stderr, "Couldn't load %d pt font from %s: %s\n", ptsize, argv[0], SDL_GetError()); cleanup(2); } TTF_SetFontStyle(font, renderstyle); TTF_SetFontOutline(font, outline); TTF_SetFontKerning(font, kerning); if( dump ) { for( i = 48; i < 123; i++ ) { SDL_Surface* glyph = NULL; glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol ); if( glyph ) { char outname[64]; sprintf( outname, "glyph-%d.bmp", i ); SDL_SaveBMP( glyph, outname ); } } cleanup(0); } /* Set a 640x480x8 video mode */ screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE); if ( screen == NULL ) { fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n", SDL_GetError()); cleanup(2); } /* Set a palette that is good for the foreground colored text */ rdiff = backcol->r - forecol->r; gdiff = backcol->g - forecol->g; bdiff = backcol->b - forecol->b; for ( i=0; i<NUM_COLORS; ++i ) { colors[i].r = forecol->r + (i*rdiff)/4; colors[i].g = forecol->g + (i*gdiff)/4; colors[i].b = forecol->b + (i*bdiff)/4; } SDL_SetColors(screen, colors, 0, NUM_COLORS); /* Clear the background to background color */ SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, backcol->r, backcol->g, backcol->b)); SDL_UpdateRect(screen, 0, 0, 0, 0); /* Show which font file we're looking at */ sprintf(string, "Font file: %s", argv[0]); /* possible overflow */ if ( rendersolid ) { text = TTF_RenderText_Solid(font, string, *forecol); } else { text = TTF_RenderText_Shaded(font, string, *forecol, *backcol); } if ( text != NULL ) { dstrect.x = 4; dstrect.y = 4; dstrect.w = text->w; dstrect.h = text->h; SDL_BlitSurface(text, NULL, screen, &dstrect); SDL_FreeSurface(text); } /* Render and center the message */ if ( argc > 2 ) { message = argv[2]; } else { message = DEFAULT_TEXT; } switch (rendertype) { case RENDER_LATIN1: if ( rendersolid ) { text = TTF_RenderText_Solid(font,message,*forecol); } else { text = TTF_RenderText_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UTF8: if ( rendersolid ) { text = TTF_RenderUTF8_Solid(font,message,*forecol); } else { text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol); } break; case RENDER_UNICODE: { Uint16 unicode_text[BUFSIZ]; int index; #ifdef HAVE_ICONV /* Use iconv to convert the message into utf-16. * "char" and "" are aliases for the local 8-bit encoding */ iconv_t cd; /*ICONV_CONST*/ char *from_str = message; char *to_str = (char*)unicode_text; size_t from_sz = strlen(message) + 1; size_t to_sz = sizeof(unicode_text); size_t res; int i; if ((cd = iconv_open("UTF-16", "char")) == (iconv_t)-1 && (cd = iconv_open("UTF-16", "")) == (iconv_t)-1) { perror("Couldn't open iconv"); exit(1); } res = iconv(cd, &from_str, &from_sz, &to_str, &to_sz); if (res == -1) { perror("Couldn't use iconv"); exit(1); } iconv_close(cd); #else /* Convert the message from ascii into utf-16. * This is unreliable as a test because it always * gives the local ordering. */ for (index = 0; message[index]; index++) { unicode_text[index] = message[index]; } unicode_text[index] = 0; #endif if ( rendersolid ) { text = TTF_RenderUNICODE_Solid(font, unicode_text, *forecol); } else { text = TTF_RenderUNICODE_Shaded(font, unicode_text, *forecol, *backcol); } } break; default: text = NULL; /* This shouldn't happen */ break; } if ( text == NULL ) { fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError()); TTF_CloseFont(font); cleanup(2); } dstrect.x = (screen->w - text->w)/2; dstrect.y = (screen->h - text->h)/2; dstrect.w = text->w; dstrect.h = text->h; printf("Font is generally %d big, and string is %hd big\n", TTF_FontHeight(font), text->h); /* Blit the text surface */ if ( SDL_BlitSurface(text, NULL, screen, &dstrect) < 0 ) { fprintf(stderr, "Couldn't blit text to display: %s\n", SDL_GetError()); TTF_CloseFont(font); cleanup(2); } SDL_UpdateRect(screen, 0, 0, 0, 0); /* Set the text colorkey and convert to display format */ if ( SDL_SetColorKey(text, SDL_SRCCOLORKEY|SDL_RLEACCEL, 0) < 0 ) { fprintf(stderr, "Warning: Couldn't set text colorkey: %s\n", SDL_GetError()); } temp = SDL_DisplayFormat(text); if ( temp != NULL ) { SDL_FreeSurface(text); text = temp; } /* Wait for a keystroke, and blit text on mouse press */ done = 0; while ( ! done ) { if ( SDL_WaitEvent(&event) < 0 ) { fprintf(stderr, "SDL_PullEvent() error: %s\n", SDL_GetError()); done = 1; continue; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: dstrect.x = event.button.x - text->w/2; dstrect.y = event.button.y - text->h/2; dstrect.w = text->w; dstrect.h = text->h; if ( SDL_BlitSurface(text, NULL, screen, &dstrect) == 0 ) { SDL_UpdateRects(screen, 1, &dstrect); } else { fprintf(stderr, "Couldn't blit text to display: %s\n", SDL_GetError()); } break; case SDL_KEYDOWN: case SDL_QUIT: done = 1; break; default: break; } } SDL_FreeSurface(text); TTF_CloseFont(font); cleanup(0); /* Not reached, but fixes compiler warnings */ return 0; }
// -------------------------------------------------------------------------------------------------------- void KikiController::saveScreenShot () { static int counter = -1; KSize screenSize = getScreenSize(); Uint32 rmask, gmask, bmask, amask; rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x00000000; setDisplayFps(false); display(); void * pixels = malloc (screenSize.w * screenSize.h * sizeof(GLuint)); #ifndef WIN32 glReadPixels (0, 0, screenSize.w, screenSize.h, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, pixels); #else glReadPixels (0, 0, screenSize.w, screenSize.h, GL_RGBA, GL_4_BYTES, pixels); #endif //............................................................ reverse order of lines (mirror vertical) int scanlineLength = screenSize.w * sizeof(GLuint); void * scanline = malloc (scanlineLength); for (int lineIndex = 0; lineIndex < screenSize.h/2; lineIndex++) { memcpy (scanline, // copy from bottom to save line &((char*)pixels)[lineIndex * scanlineLength], scanlineLength); memcpy (&((char*)pixels)[lineIndex * scanlineLength], // copy from top to bottom &((char*)pixels)[(screenSize.h-lineIndex-1) * scanlineLength], scanlineLength); // copy from save line to top memcpy (&((char*)pixels)[(screenSize.h-lineIndex-1) * scanlineLength], scanline, scanlineLength); } //............................................................ create SDL_surface from pixels SDL_Surface * saveSurface = SDL_CreateRGBSurfaceFrom (pixels, screenSize.w, screenSize.h, 32, screenSize.w * 4, rmask, gmask, bmask, amask); free (scanline); if (saveSurface == NULL) { KConsole::printf("WARNING unable to copy screen surface for screenshot"); free (pixels); return; } std::string screenShotFile; //............................................................ search for a free file name do { counter++; #ifndef WIN32 screenShotFile = kStringPrintf("%s/kiki_%03d.bmp", getenv ("HOME"), counter); #else screenShotFile = kStringPrintf("c:/kiki_%03d.bmp", counter); #endif } while (kFileExists(screenShotFile)); //............................................................ save the screenshot if (SDL_SaveBMP(saveSurface, screenShotFile.c_str()) == 0) { KConsole::printf("screenshot saved to file %s", kFileAbsPathName(screenShotFile).c_str()); } else // ooops... { KConsole::printf("WARNING unable to write screenshot to file %s", screenShotFile.c_str()); } SDL_FreeSurface(saveSurface); free (pixels); }
void DrawPict(SDL_Surface * screen, char *bmpfile, int speedy, int flip, int nofade) { SDL_Surface *picture; SDL_Rect dest, update; int i, centered; int ncolors; SDL_Color *colors, *cmap; /* Load the image into a surface */ if (bmpfile == NULL) { bmpfile = "sample.bmp"; /* Sample image */ } fprintf(stderr, "Loading picture: %s\n", bmpfile); picture = SDL_LoadBMP(bmpfile); if (picture == NULL) { fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError()); return; } /* Set the display colors -- on a hicolor display this is a no-op */ if (picture->format->palette) { ncolors = picture->format->palette->ncolors; colors = (SDL_Color *) malloc(ncolors * sizeof(SDL_Color)); cmap = (SDL_Color *) malloc(ncolors * sizeof(SDL_Color)); memcpy(colors, picture->format->palette->colors, ncolors * sizeof(SDL_Color)); } else { int r, g, b; /* Allocate 256 color palette */ ncolors = 256; colors = (SDL_Color *) malloc(ncolors * sizeof(SDL_Color)); cmap = (SDL_Color *) malloc(ncolors * sizeof(SDL_Color)); /* Set a 3,3,2 color cube */ for (r = 0; r < 8; ++r) { for (g = 0; g < 8; ++g) { for (b = 0; b < 4; ++b) { i = ((r << 5) | (g << 2) | b); colors[i].r = r << 5; colors[i].g = g << 5; colors[i].b = b << 6; } } } } NOTICE("testwin: setting colors\n"); if (!SDL_SetColors(screen, colors, 0, ncolors) && (screen->format->palette != NULL)) { fprintf(stderr, "Warning: Couldn't set all of the colors, but SDL will map the image\n" " (colormap fading will suffer - try the -warp option)\n"); } /* Display the picture */ if (speedy) { SDL_Surface *displayfmt; fprintf(stderr, "Converting picture\n"); displayfmt = SDL_DisplayFormat(picture); if (displayfmt == NULL) { fprintf(stderr, "Couldn't convert image: %s\n", SDL_GetError()); goto done; } SDL_FreeSurface(picture); picture = displayfmt; } printf("(image surface located in %s memory)\n", (picture->flags & SDL_HWSURFACE) ? "video" : "system"); centered = (screen->w - picture->w) / 2; if (centered < 0) { centered = 0; } dest.y = (screen->h - picture->h) / 2; dest.w = picture->w; dest.h = picture->h; NOTICE("testwin: moving image\n"); for (i = 0; i <= centered; ++i) { dest.x = i; update = dest; if (SDL_BlitSurface(picture, NULL, screen, &update) < 0) { fprintf(stderr, "Blit failed: %s\n", SDL_GetError()); break; } if (flip) { SDL_Flip(screen); } else { SDL_UpdateRects(screen, 1, &update); } } #ifdef SCREENSHOT if (SDL_SaveBMP(screen, "screen.bmp") < 0) printf("Couldn't save screen: %s\n", SDL_GetError()); #endif #ifndef BENCHMARK_SDL /* Let it sit there for a while */ SDL_Delay(5 * 1000); #endif /* Fade the colormap */ if (!nofade) { int maxstep; SDL_Color final; SDL_Color palcolors[256]; struct { Sint16 r, g, b; } cdist[256]; NOTICE("testwin: fading out...\n"); memcpy(cmap, colors, ncolors * sizeof(SDL_Color)); maxstep = 32 - 1; final.r = 0xFF;
int Engine::work() { //SDL vars for WM SDL_Event event; timer FPS_counter,FPS_updater; int FPS_frames=0; this->working = 1; this->active = 1; //fixing additional mouse events due to Win if(this->active) { //SDL_WarpMouse(this->width/2,this->height/2); while(SDL_PollEvent(&event)); } //FPS updater start FPS_updater.t_Start(); //#MAIN LOOP while(this->working) { bool lag = 0; //Timer for each frame FPS_counter.t_Start(); //mouse //SDL_ShowCursor(!this->active); //#SDL EVENTS HANDLING# while(SDL_PollEvent(&event)) { ui->handle(&event); switch(event.type) { case SDL_QUIT: this->working = 0; fclose(stdout); break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_q: this->working = 0; break; } break; } } UIEvent uievent; while(ui->pollEvent(&uievent)) { switch(uievent.type) { case UIEVENT_BUTTONCLICKED: if(uievent.id == this->button_exit) this->working = 0; if(uievent.id == this->button_generate) { this->level->generate(120, 10); sprintf(this->ui->getText(this->log)->text, "Generation started\n"); } if(uievent.id == this->button_continue) this->level->nextStep(); if(uievent.id == this->button_export) this->exporting = 1; break; } } this->level->step(); //#RENDER this->renderQuad(0, 0, this->width, this->height, this->bg_r, this->bg_g, this->bg_b); this->level->render(); if(!exporting) { if(this->level->onRoomGeneration) { for(int i =0; i<this->level->current_room+1; i++) { int h = this->level->rands[i] * 40 + 1; int y = 470 - h; this->renderQuad(10 + i*2, y, 2, h, 0, 232, 0); } } this->ui->render(); } if(exporting) { if(this->level->onRoomGenerationFinished && !this->level->onRoomSeparationFinished) SDL_SaveBMP(this->screen, "00export_generation.bmp"); if(this->level->onRoomSeparationFinished && !this->level->onRoomClearingFinished) SDL_SaveBMP(this->screen, "01export_separation.bmp"); if(this->level->onRoomClearingFinished && !this->level->onDelaunayFinished) SDL_SaveBMP(this->screen, "02export_cleaning.bmp"); if(this->level->onDelaunayFinished && !this->level->onCorridorFinished) SDL_SaveBMP(this->screen, "03export_tree_building.bmp"); if(this->level->onCorridorFinished) SDL_SaveBMP(this->screen, "04export_final.bmp"); this->exporting = 0; } else { //END of render SDL_Flip(this->screen); //actual render } //#FPS CONTROL# FPS_frames++; //Regulating FPS if(FPS_counter.t_GetTime() < 1000.f / FPS_max && FPS_max > 0.0) { SDL_Delay((int) ((1000.f / FPS_max + 0.5) - FPS_counter.t_GetTime())); } //Calculating FPS if(FPS_updater.t_GetTime()>1000) { FPS = FPS_frames / (FPS_updater.t_GetTime() / 1000.f); //FPS_physics = FPS_frames / (FPS_physics_counter.t_GetTime() / 1000.f); FPS_frames = 0; FPS_updater.t_Start(); } //END of main loop } return 0; }