diff --git a/src/editor/editloop.cpp b/src/editor/editloop.cpp index 73f4487337..ad5ec6f95a 100644 --- a/src/editor/editloop.cpp +++ b/src/editor/editloop.cpp @@ -285,21 +285,17 @@ static void EditorActionPlaceUnit(const Vec2i &pos, const CUnitType &type, CPlay replacedUnit.Release(); } } - if (unit != nullptr) { - if (type.GivesResource) { - if (type.StartingResources != 0) { - unit->ResourcesHeld = type.StartingResources; - unit->Variable[GIVERESOURCE_INDEX].Value = type.StartingResources; - unit->Variable[GIVERESOURCE_INDEX].Max = type.StartingResources; - } else { - unit->ResourcesHeld = DefaultResourceAmounts[type.GivesResource]; - unit->Variable[GIVERESOURCE_INDEX].Value = DefaultResourceAmounts[type.GivesResource]; - unit->Variable[GIVERESOURCE_INDEX].Max = DefaultResourceAmounts[type.GivesResource]; - } - unit->Variable[GIVERESOURCE_INDEX].Enable = 1; + if (type.GivesResource) { + if (type.StartingResources != 0) { + unit->ResourcesHeld = type.StartingResources; + unit->Variable[GIVERESOURCE_INDEX].Value = type.StartingResources; + unit->Variable[GIVERESOURCE_INDEX].Max = type.StartingResources; + } else { + unit->ResourcesHeld = DefaultResourceAmounts[type.GivesResource]; + unit->Variable[GIVERESOURCE_INDEX].Value = DefaultResourceAmounts[type.GivesResource]; + unit->Variable[GIVERESOURCE_INDEX].Max = DefaultResourceAmounts[type.GivesResource]; } - } else { - DebugPrint("Unable to allocate Unit"); + unit->Variable[GIVERESOURCE_INDEX].Enable = 1; } UpdateMinimap = true; } @@ -687,7 +683,7 @@ static bool forEachTileOptionArea(std::function> compactOptions = { + const std::vector> compactOptions = { { TileCursorSize == 1, "1x1" }, { TileCursorSize == 2, "2x2" }, { TileCursorSize == 3, "3x3" }, @@ -696,7 +692,7 @@ static bool forEachTileOptionArea(std::function> options = { + const std::vector> options = { { TileToolRandom != 0, "Random" }, { TileToolDecoration != 0, "Filler" }, { TileToolNoFixup != 0, "Manual" } @@ -983,11 +979,8 @@ static void DrawStartLocations() static void DrawEditorInfo() { #if 1 - Vec2i pos(0, 0); - - if (UI.MouseViewport) { - pos = UI.MouseViewport->ScreenToTilePos(CursorScreenPos); - } + const Vec2i pos = + UI.MouseViewport ? UI.MouseViewport->ScreenToTilePos(CursorScreenPos) : Vec2i(0, 0); char buf[256]; snprintf(buf, sizeof(buf), _("Editor (%d %d)"), pos.x, pos.y); @@ -1114,22 +1107,22 @@ void EditorUpdateDisplay() /*---------------------------------------------------------------------------- -- Highlight layers ----------------------------------------------------------------------------*/ -static inline bool OverlayElevation(const CMapField &mapField) +static bool OverlayElevation(const CMapField &mapField) { return mapField.getElevation() == Editor.HighlightElevationLevel; } -static inline bool OverlayUnpassable(const CMapField &mapField) +static bool OverlayUnpassable(const CMapField &mapField) { return mapField.getFlag() & MapFieldUnpassable; } -static inline bool OverlayNoBuildingAllowed(const CMapField &mapField) +static bool OverlayNoBuildingAllowed(const CMapField &mapField) { return mapField.getFlag() & MapFieldNoBuilding; } -static inline bool OverlayOpaque(const CMapField &mapField) +static bool OverlayOpaque(const CMapField &mapField) { return mapField.isOpaque(); } @@ -1470,6 +1463,7 @@ static void EditorCallbackKeyDown(unsigned key, unsigned keychar) break; } Exit(0); + break; case 'z': if (KeyModifiers & ModifierControl) { @@ -1513,7 +1507,7 @@ static void EditorCallbackKeyDown(unsigned key, unsigned keychar) } break; } else { - // fallthrough + [[fallthrough]]; } case '1': case '2': case '3': case '4': case '5': @@ -1659,9 +1653,6 @@ static bool EditorCallbackMouse_EditUnitArea(const PixelPos &screenPos) static bool EditorCallbackMouse_EditTileArea(const PixelPos &screenPos) { - int bx = UI.InfoPanel.X + 4; - int by = UI.InfoPanel.Y + 4 + IconHeight + 10; - bool noHit = forEachTileOptionArea([screenPos](bool active, std::string &label, int i, int x, int y, int w, int h) { if (x < screenPos.x && screenPos.x < x + w && y < screenPos.y && screenPos.y < y + h) { ButtonUnderCursor = i + 300; @@ -2018,7 +2009,6 @@ void EditorMainLoop() { bool OldCommandLogDisabled = CommandLogDisabled; const EventCallback *old_callbacks = GetCallbacks(); - bool first_init = true; CommandLogDisabled = true; SetCallbacks(&EditorCallbacks); diff --git a/src/stratagus/stratagus.cpp b/src/stratagus/stratagus.cpp index e514d7f0b0..a54290f5a9 100644 --- a/src/stratagus/stratagus.cpp +++ b/src/stratagus/stratagus.cpp @@ -694,7 +694,7 @@ static LONG WINAPI CreateDumpFile(EXCEPTION_POINTERS *ExceptionInfo) ** @param argv Vector of arguments. */ int stratagusMain(int argc, char **argv) -{ +try { for (int i = 0; i < argc; i++) { OriginalArgv.push_back(std::string(argv[i])); } @@ -723,7 +723,6 @@ int stratagusMain(int argc, char **argv) Assert(pathPtr); StratagusLibPath = pathPtr; #endif - try { Parameters ¶meters = Parameters::Instance; parameters.SetDefaultValues(); parameters.SetLocalPlayerNameFromEnv(); @@ -732,78 +731,97 @@ int stratagusMain(int argc, char **argv) RedirectOutput(); #endif - if (argc > 0) { - parameters.applicationName = argv[0]; - } + if (argc > 0) { + parameters.applicationName = argv[0]; + } - // FIXME: Parse options before or after scripts? - ParseCommandLine(argc, argv, parameters); - // Init the random number generator. - InitSyncRand(); + // FIXME: Parse options before or after scripts? + ParseCommandLine(argc, argv, parameters); + // Init the random number generator. + InitSyncRand(); - fs::create_directories(parameters.GetUserDirectory()); + fs::create_directories(parameters.GetUserDirectory()); - // Init Lua and register lua functions! - InitLua(); - LuaRegisterModules(); + // Init Lua and register lua functions! + InitLua(); + LuaRegisterModules(); - // Initialise AI module - InitAiModule(); + // Initialise AI module + InitAiModule(); - // Setup sound card, must be done before loading sounds, so that - // SDL_mixer can auto-convert to the target format - if (InitSound()) { - InitMusic(); - } + // Setup sound card, must be done before loading sounds, so that + // SDL_mixer can auto-convert to the target format + if (InitSound()) { + InitMusic(); + } - // init globals - Map.AllocateTileset(); - UnitManager = new CUnitManager(); - FogOfWar = std::make_unique(); + // init globals + Map.AllocateTileset(); + UnitManager = new CUnitManager(); + FogOfWar = std::make_unique(); - LoadCcl(parameters.luaStartFilename, parameters.luaScriptArguments); + LoadCcl(parameters.luaStartFilename, parameters.luaScriptArguments); - // Setup video display - InitVideo(); + // Setup video display + InitVideo(); - PrintHeader(); - PrintLicense(); + PrintHeader(); + PrintLicense(); #ifndef DEBUG // For debug it's better not to have: - srand(time(nullptr)); // Random counter = random each start + srand(time(nullptr)); // Random counter = random each start #endif - // Show title screens. - SetDefaultTextColors(FontYellow, FontWhite); - LoadFonts(); - SetClipping(0, 0, Video.Width - 1, Video.Height - 1); - Video.ClearScreen(); - if (!IsRestart) { - ShowTitleScreens(); - } - - // Init player data - ThisPlayer = nullptr; - //Don't clear the Players structure as it would erase the allowed units. - // memset(Players, 0, sizeof(Players)); - NumPlayers = 0; - - UnitManager->Init(); // Units memory management - PreMenuSetup(); // Load everything needed for menus - - MenuLoop(); - - Exit(0); - } catch (const std::exception &e) { - ErrorPrint("Stratagus crashed!\n" - "Please send this call stack to our bug tracker: " - "https://github.com/Wargus/stratagus/issues\n" - "and tell us what caused this bug to occur.\n" - " === exception state traceback === \n"); - ErrorPrint("%s", e.what()); - exit(1); + // Show title screens. + SetDefaultTextColors(FontYellow, FontWhite); + LoadFonts(); + SetClipping(0, 0, Video.Width - 1, Video.Height - 1); + Video.ClearScreen(); + if (!IsRestart) { + ShowTitleScreens(); } + + // Init player data + ThisPlayer = nullptr; + //Don't clear the Players structure as it would erase the allowed units. + // memset(Players, 0, sizeof(Players)); + NumPlayers = 0; + + UnitManager->Init(); // Units memory management + PreMenuSetup(); // Load everything needed for menus + + MenuLoop(); + + Exit(0); return 0; +} catch (const std::exception &e) { + ErrorPrint("Stratagus crashed!\n" + "Please send this call stack to our bug tracker: " + "https://github.com/Wargus/stratagus/issues\n" + "and tell us what caused this bug to occur.\n" + " === exception state traceback === \n"); + ErrorPrint("%s", e.what()); + exit(1); +} +catch (const gcn::Exception &ex) { + ErrorPrint("Stratagus crashed in Guichan!\n" + "Please send this call stack to our bug tracker: " + "https://github.com/Wargus/stratagus/issues\n" + "and tell us what caused this bug to occur.\n" + " === exception state traceback === \n"); + ErrorPrint("%s:%d (%s): %s", + ex.getFilename().c_str(), + ex.getLine(), + ex.getFunction().c_str(), + ex.getMessage().c_str()); + exit(1); +} +catch (...) { + ErrorPrint("Stratagus crashed!\n" + "Please send this call stack to our bug tracker: " + "https://github.com/Wargus/stratagus/issues\n" + "and tell us what caused this bug to occur.\n" + " === exception state traceback === \n"); + exit(1); } - //@} diff --git a/src/video/sdl.cpp b/src/video/sdl.cpp index 9801f69f0d..849bbcbcac 100644 --- a/src/video/sdl.cpp +++ b/src/video/sdl.cpp @@ -160,18 +160,6 @@ void SetVideoSync() -- Video ----------------------------------------------------------------------------*/ -#if defined(DEBUG) && !defined(USE_WIN32) -static void CleanExit(int) -{ - // Clean SDL - SDL_Quit(); - // Reestablish normal behaviour for next abort call - signal(SIGABRT, SIG_DFL); - // Generates a core dump - abort(); -} -#endif - /** ** Initialize SDLKey to string map */ @@ -183,9 +171,6 @@ static void InitKey2Str() return; } - int i; - char str[20]; - Key2Str[SDLK_BACKSPACE] = "backspace"; Key2Str[SDLK_TAB] = "tab"; Key2Str[SDLK_CLEAR] = "clear"; @@ -208,10 +193,8 @@ static void InitKey2Str() Key2Str[SDLK_PERIOD] = "."; Key2Str[SDLK_SLASH] = "/"; - str[1] = '\0'; - for (i = SDLK_0; i <= SDLK_9; ++i) { - str[0] = i; - Key2Str[i] = str; + for (int i = SDLK_0; i <= SDLK_9; ++i) { + Key2Str[i] = std::string(1, static_cast(i)); } Key2Str[SDLK_COLON] = ":"; @@ -226,17 +209,14 @@ static void InitKey2Str() Key2Str[SDLK_RIGHTBRACKET] = "]"; Key2Str[SDLK_BACKQUOTE] = "`"; - str[1] = '\0'; - for (i = SDLK_a; i <= SDLK_z; ++i) { - str[0] = i; - Key2Str[i] = str; + for (int i = SDLK_a; i <= SDLK_z; ++i) { + Key2Str[i] = std::string(1, static_cast(i)); } Key2Str[SDLK_DELETE] = "delete"; - for (i = SDLK_KP_0; i <= SDLK_KP_9; ++i) { - snprintf(str, sizeof(str), "kp_%d", i - SDLK_KP_0); - Key2Str[i] = str; + for (int i = SDLK_KP_0; i <= SDLK_KP_9; ++i) { + Key2Str[i] = "kp_" + std::to_string(i - SDLK_KP_0); } Key2Str[SDLK_KP_PERIOD] = "kp_period"; @@ -256,11 +236,9 @@ static void InitKey2Str() Key2Str[SDLK_PAGEUP] = "pageup"; Key2Str[SDLK_PAGEDOWN] = "pagedown"; - for (i = SDLK_F1; i <= SDLK_F15; ++i) { - snprintf(str, sizeof(str), "f%d", i - SDLK_F1 + 1); - Key2Str[i] = str; - snprintf(str, sizeof(str), "F%d", i - SDLK_F1 + 1); - Str2Key[str] = i; + for (int i = SDLK_F1; i <= SDLK_F15; ++i) { + Key2Str[i] = "f" + std::to_string(i - SDLK_F1 + 1); + Str2Key["F" + std::to_string(i - SDLK_F1 + 1)] = i; } Key2Str[SDLK_HELP] = "help"; @@ -281,36 +259,28 @@ enum PROCESS_DPI_AWARENESS { }; static void setDpiAware() { - void* userDLL; - BOOL(WINAPI *SetProcessDPIAware)(void); // Vista and later - void* shcoreDLL; HRESULT(WINAPI *SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS dpiAwareness); // Windows 8.1 and later - userDLL = SDL_LoadObject("USER32.DLL"); - if (userDLL) { - SetProcessDPIAware = (BOOL(WINAPI *)(void)) SDL_LoadFunction(userDLL, "SetProcessDPIAware"); - } else { - SetProcessDPIAware = nullptr; - } - - shcoreDLL = SDL_LoadObject("SHCORE.DLL"); - if (shcoreDLL) { + if (void* shcoreDLL = SDL_LoadObject("SHCORE.DLL")) { SetProcessDpiAwareness = (HRESULT(WINAPI *)(PROCESS_DPI_AWARENESS)) SDL_LoadFunction(shcoreDLL, "SetProcessDpiAwareness"); } else { SetProcessDpiAwareness = nullptr; } - if (SetProcessDpiAwareness) { /* Try Windows 8.1+ version */ HRESULT result = SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); DebugPrint("called SetProcessDpiAwareness: %d", (result == S_OK) ? 1 : 0); } else { - if (SetProcessDPIAware) { - /* Try Vista - Windows 8 version. - This has a constant scale factor for all monitors. - */ - BOOL success = SetProcessDPIAware(); - DebugPrint("called SetProcessDPIAware: %d", (int)success); + if (void* userDLL = SDL_LoadObject("USER32.DLL")) { + BOOL(WINAPI *SetProcessDPIAware)(void); // Vista and later + SetProcessDPIAware = (BOOL(WINAPI *)(void)) SDL_LoadFunction(userDLL, "SetProcessDPIAware"); + if (SetProcessDPIAware) { + /* Try Vista - Windows 8 version. + This has a constant scale factor for all monitors. + */ + BOOL success = SetProcessDPIAware(); + DebugPrint("called SetProcessDPIAware: %d", (int)success); + } } // In any case, on these old Windows versions we have to do a bit of // compatibility hacking. Windows 7 and below don't play well with @@ -354,8 +324,16 @@ void InitVideoSdl() // If debug is enabled, Stratagus disable SDL Parachute. // So we need gracefully handle segfaults and aborts. #if defined(DEBUG) && !defined(USE_WIN32) - signal(SIGSEGV, CleanExit); - signal(SIGABRT, CleanExit); + const auto cleanExit = [](int) { + // Clean SDL + SDL_Quit(); + // Reestablish normal behaviour for next abort call + signal(SIGABRT, SIG_DFL); + // Generates a core dump + abort(); + }; + signal(SIGSEGV, +cleanExit); + signal(SIGABRT, +cleanExit); #endif } @@ -375,12 +353,10 @@ void InitVideoSdl() Video.Width = 640; Video.Height = 480; } - if (!Video.WindowWidth || !Video.WindowHeight) { Video.WindowWidth = Video.Width; Video.WindowHeight = Video.Height; } - if (!Video.Depth) { Video.Depth = 32; } @@ -445,12 +421,7 @@ void InitVideoSdl() // } // #endif -#if ! defined(USE_WIN32) && ! defined(USE_MAEMO) - - SDL_Surface *icon = nullptr; - CGraphic *g = nullptr; - struct stat st; - +#if !defined(USE_WIN32) && !defined(USE_MAEMO) std::string FullGameNameL = FullGameName; for (size_t i = 0; i < FullGameNameL.size(); ++i) { FullGameNameL[i] = tolower(FullGameNameL[i]); @@ -458,11 +429,11 @@ void InitVideoSdl() std::string ApplicationName = Parameters::Instance.applicationName; std::string ApplicationNameL = ApplicationName; - for (size_t i = 0; i < ApplicationNameL.size(); ++i) { - ApplicationNameL[i] = tolower(ApplicationNameL[i]); + for (auto& c : ApplicationNameL) { + c = tolower(c); } - std::vector pixmaps + std::vector pixmaps { fs::path(PIXMAPS) / (FullGameName + ".png"), fs::path(PIXMAPS) / (FullGameNameL + ".png"), @@ -478,26 +449,26 @@ void InitVideoSdl() fs::path("/usr/share/pixmaps/stratagus.png") }; - for (size_t i = 0; i < pixmaps.size(); ++i) { - if (stat(pixmaps[i].c_str(), &st) == 0) { + CGraphic *g = nullptr; + SDL_Surface *icon = nullptr; + + for (const auto &p : pixmaps) { + if (fs::exists(p)) { if (g) { CGraphic::Free(g); } - g = CGraphic::New(pixmaps[i]); + g = CGraphic::New(p.u8string()); g->Load(); icon = g->Surface; if (icon) { break; } } } - if (icon) { SDL_SetWindowIcon(TheWindow, icon); } - if (g) { CGraphic::Free(g); } - #endif - Video.FullScreen = (SDL_GetWindowFlags(TheWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) ? 1 : 0; + Video.FullScreen = (SDL_GetWindowFlags(TheWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; Video.Depth = TheScreen->format->BitsPerPixel; // Must not allow SDL to switch to relative mouse coordinates when going @@ -661,21 +632,21 @@ static void SdlDoEvent(const EventCallback &callbacks, SDL_Event &event) break; case SDL_TEXTINPUT: - { - char* text = event.text.text; - if (isTextInput((uint8_t)text[0])) { - // we only accept US-ascii chars for now - char lastKey = text[0]; - InputKeyButtonPress(callbacks, SDL_GetTicks(), lastKey, lastKey); - // fabricate a keyup event for later - SDL_Event event; - SDL_zero(event); - event.type = SDL_CUSTOM_KEY_UP; - event.user.code = lastKey; - SDL_PeepEvents(&event, 1, SDL_ADDEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT); - } + { + char *text = event.text.text; + if (isTextInput((uint8_t) text[0])) { + // we only accept US-ascii chars for now + char lastKey = text[0]; + InputKeyButtonPress(callbacks, SDL_GetTicks(), lastKey, lastKey); + // fabricate a keyup event for later + SDL_Event event; + SDL_zero(event); + event.type = SDL_CUSTOM_KEY_UP; + event.user.code = lastKey; + SDL_PeepEvents(&event, 1, SDL_ADDEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT); } break; + } case SDL_KEYDOWN: keysym = event.key.keysym.sym; @@ -935,22 +906,16 @@ void ToggleGrabMouse(int mode) */ void ToggleFullScreen() { - Uint32 flags; - flags = SDL_GetWindowFlags(TheWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP; - -#ifdef USE_WIN32 - if (!TheWindow) { // don't bother if there's no surface. return; } + const Uint32 flags = SDL_GetWindowFlags(TheWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_SetWindowFullscreen(TheWindow, flags ^ SDL_WINDOW_FULLSCREEN_DESKTOP); +#ifdef USE_WIN32 Invalidate(); // Update display -#else // !USE_WIN32 - SDL_SetWindowFullscreen(TheWindow, flags ^ SDL_WINDOW_FULLSCREEN_DESKTOP); #endif - - Video.FullScreen = (flags ^ SDL_WINDOW_FULLSCREEN_DESKTOP) ? 1 : 0; + Video.FullScreen = (flags ^ SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; } //@}