From c3b0d71973fa6029c69b594cf5a46fd6b49e10ff Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Thu, 11 Jun 2026 21:14:35 +0100 Subject: [PATCH] Codechange: use EnumRange over many enum loops --- src/ai/ai_gui.cpp | 2 +- src/bootstrap_gui.cpp | 4 ++-- src/build_vehicle_gui.cpp | 2 +- src/clear_cmd.cpp | 4 ++-- src/company_cmd.cpp | 8 ++++---- src/company_gui.cpp | 6 +++--- src/console_cmds.cpp | 6 +++--- src/console_gui.cpp | 2 +- src/currency.cpp | 5 ++--- src/depot_gui.cpp | 2 +- src/driver.cpp | 2 +- src/driver.h | 2 +- src/economy.cpp | 8 ++++---- src/elrail.cpp | 6 +++--- src/engine.cpp | 4 ++-- src/fileio.cpp | 2 +- src/fontcache.cpp | 4 ++-- src/fontcache/spritefontcache.cpp | 2 +- src/framerate_gui.cpp | 6 +++--- src/game/game_gui.cpp | 2 +- src/graph_gui.cpp | 4 ++-- src/group_cmd.cpp | 6 +++--- src/highscore.cpp | 4 ++-- src/landscape.cpp | 14 +++++++------- src/linkgraph/refresh.cpp | 4 ++-- src/main_gui.cpp | 4 ++-- src/map.cpp | 2 +- src/network/network_admin.cpp | 4 ++-- src/network/network_content_gui.cpp | 6 +++--- src/network/network_gui.cpp | 4 ++-- src/newgrf.cpp | 16 ++++++++-------- src/newgrf.h | 1 + src/newgrf_debug_gui.cpp | 2 +- src/newgrf_gui.cpp | 2 +- src/newgrf_railtype.cpp | 2 +- src/newgrf_roadtype.cpp | 2 +- src/newgrf_spritegroup.h | 2 +- src/pathfinder/yapf/yapf_river_builder.cpp | 2 +- src/rail.cpp | 2 +- src/rail_cmd.cpp | 4 ++-- src/rail_gui.cpp | 2 +- src/road.cpp | 4 ++-- src/road_cmd.cpp | 2 +- src/saveload/afterload.cpp | 4 ++-- src/saveload/labelmaps_sl.cpp | 4 ++-- src/saveload/oldloader_sl.cpp | 2 +- src/script/api/script_cargolist.cpp | 2 +- src/script/api/script_infrastructure.cpp | 4 ++-- src/script/api/script_railtypelist.cpp | 2 +- src/script/api/script_roadtypelist.cpp | 2 +- src/script/api/script_townlist.cpp | 2 +- src/settings_gui.cpp | 4 ++-- src/ship_cmd.cpp | 2 +- src/signal.cpp | 2 +- src/signs_gui.cpp | 4 ++-- src/spritecache.cpp | 4 +--- src/station.cpp | 2 +- src/station_cmd.cpp | 14 +++++++------- src/station_gui.cpp | 8 ++++---- src/strings.cpp | 2 +- src/survey.cpp | 2 +- src/terraform_cmd.cpp | 2 +- src/tests/mock_fontcache.h | 2 +- src/town_cmd.cpp | 8 ++++---- src/town_gui.cpp | 15 ++++++--------- src/viewport.cpp | 2 +- src/water_cmd.cpp | 8 ++++---- 67 files changed, 136 insertions(+), 141 deletions(-) diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp index 0552f86cea..07a4d3aa13 100644 --- a/src/ai/ai_gui.cpp +++ b/src/ai/ai_gui.cpp @@ -326,7 +326,7 @@ struct AIConfigWindow : public Window { this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, !IsEditable(this->selected_slot) || !IsEditable(static_cast(this->selected_slot + 1))); this->SetWidgetDisabledState(WID_AIC_OPEN_URL, this->selected_slot == CompanyID::Invalid() || config->GetInfo() == nullptr || config->GetInfo()->GetURL().empty()); - for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { + for (TextfileType tft : EnumRange(TFT_CONTENT_BEGIN, TFT_CONTENT_END)) { this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == CompanyID::Invalid() || !config->GetTextfile(tft, this->selected_slot).has_value()); } } diff --git a/src/bootstrap_gui.cpp b/src/bootstrap_gui.cpp index d82e81c3f2..f2b7203f51 100644 --- a/src/bootstrap_gui.cpp +++ b/src/bootstrap_gui.cpp @@ -387,8 +387,8 @@ bool HandleBootstrap() * This way the mauve and gray colours work and we can show the user interface. */ GfxInitPalettes(); static const EnumIndexArray offsets = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x04, 0x08 }; - for (Colours i = Colours::Begin; i != Colours::End; i++) { - for (Shade j = Shade::Begin; j < Shade::End; j++) { + for (Colours i : EnumRange(Colours::End)) { + for (Shade j : EnumRange(Shade::End)) { SetColourGradient(i, j, PixelColour(offsets[i] + to_underlying(j))); } } diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index 836ffa6877..d91c570f16 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -512,7 +512,7 @@ static GUIEngineList::FilterFunction * const _engine_filter_funcs[] = { static uint GetCargoWeight(const CargoArray &cap, VehicleType vtype) { uint weight = 0; - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (cap[cargo] != 0) { if (vtype == VehicleType::Train) { weight += CargoSpec::Get(cargo)->WeightOfNUnitsInTrain(cap[cargo]); diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp index 3d1b67fca9..980dc10e40 100644 --- a/src/clear_cmd.cpp +++ b/src/clear_cmd.cpp @@ -179,7 +179,7 @@ static void UpdateFences(TileIndex tile) assert(IsTileType(tile, TileType::Clear) && IsClearGround(tile, ClearGround::Fields)); bool dirty = false; - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { if (GetFence(tile, dir) != 0) continue; TileIndex neighbour = tile + TileOffsByDiagDir(dir); if (IsTileType(neighbour, TileType::Clear) && IsClearGround(neighbour, ClearGround::Fields)) continue; @@ -232,7 +232,7 @@ static void TileLoopClearAlps(TileIndex tile) */ static inline bool NeighbourIsNormal(TileIndex tile) { - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { TileIndex t = tile + TileOffsByDiagDir(dir); if (!IsValidTile(t)) continue; if (GetTropicZone(t) != TropicZone::Desert) return true; diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index f739b9f421..d447392007 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -574,7 +574,7 @@ restart:; */ void ResetCompanyLivery(Company *c) { - for (LiveryScheme scheme = LiveryScheme::Begin; scheme < LiveryScheme::End; scheme++) { + for (LiveryScheme scheme : EnumRange(LiveryScheme::End)) { c->livery[scheme].in_use.Reset(); c->livery[scheme].colour1 = c->colour; c->livery[scheme].colour2 = c->colour; @@ -1093,7 +1093,7 @@ CommandCost CmdSetCompanyManagerFace(DoCommandFlags flags, uint style, uint32_t */ void UpdateCompanyLiveries(Company *c) { - for (LiveryScheme i = LiveryScheme::Steam; i < LiveryScheme::End; i++) { + for (LiveryScheme i : EnumRange(LiveryScheme::Steam, LiveryScheme::End)) { if (!c->livery[i].in_use.Test(Livery::Flag::Primary)) c->livery[i].colour1 = c->livery[LiveryScheme::Default].colour1; if (!c->livery[i].in_use.Test(Livery::Flag::Secondary)) c->livery[i].colour2 = c->livery[LiveryScheme::Default].colour2; } @@ -1155,8 +1155,8 @@ CommandCost CmdSetCompanyColour(DoCommandFlags flags, LiveryScheme scheme, bool /* Else loop through all schemes to see if any are left enabled. * If not, disable the default scheme too. */ c->livery[LiveryScheme::Default].in_use.Reset({Livery::Flag::Primary, Livery::Flag::Secondary}); - for (scheme = LiveryScheme::Default; scheme < LiveryScheme::End; scheme++) { - if (c->livery[scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) { + for (LiveryScheme other_scheme : EnumRange(LiveryScheme::End)) { + if (c->livery[other_scheme].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) { c->livery[LiveryScheme::Default].in_use.Set(Livery::Flag::Primary); break; } diff --git a/src/company_gui.cpp b/src/company_gui.cpp index 03d3bbde18..80f231ce4b 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -673,7 +673,7 @@ private: default_col = GetColourOffset(*default_livery, primary) + to_underlying(Colours::End); list.push_back(std::make_unique>(default_col, false)); } - for (Colours colour = Colours::Begin; colour != Colours::End; colour++) { + for (Colours colour : EnumRange(Colours::End)) { list.push_back(std::make_unique>(to_underlying(colour), used_colours.Test(colour))); } @@ -803,7 +803,7 @@ public: case WID_SCL_PRI_COL_DROPDOWN: { this->square = GetSpriteSize(SPR_SQUARE); int string_padding = this->square.width + WidgetDimensions::scaled.hsep_normal + padding.width; - for (Colours colour = Colours::Begin; colour != Colours::End; colour++) { + for (Colours colour : EnumRange(Colours::End)) { size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DARK_BLUE + to_underlying(colour)).width + string_padding); } size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + string_padding); @@ -2062,7 +2062,7 @@ struct CompanyWindow : Window void DrawVehicleCountsWidget(const Rect &r, const Company *c) const { int y = r.top; - for (VehicleType type = VehicleType::Begin; type < VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { uint amount = c->group_all[type].num_vehicle; if (amount != 0) { DrawString(r.left, r.right, y, GetString(_company_view_vehicle_count_strings[type], amount)); diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index ca715f7c4b..500623c752 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -2452,7 +2452,7 @@ static bool ConFont(std::span argv) SetFont(argfs, font, size); } - for (FontSize fs = FontSize::Begin; fs < FontSize::End; fs++) { + for (FontSize fs : EnumRange(FontSize::End)) { FontCache *fc = FontCache::Get(fs); FontCacheSubSetting *setting = GetFontCacheSubSetting(fs); /* Make sure all non sprite fonts are loaded. */ @@ -2810,7 +2810,7 @@ static void ConDumpRoadTypes() IConsolePrint(CC_DEFAULT, " T = buildable by towns"); std::map grfs; - for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) { + for (RoadType rt : EnumRange(ROADTYPE_END)) { const RoadTypeInfo *rti = GetRoadTypeInfo(rt); if (rti->label == 0) continue; uint32_t grfid = 0; @@ -2849,7 +2849,7 @@ static void ConDumpRailTypes() IConsolePrint(CC_DEFAULT, " d = always disallow 90 degree turns"); std::map grfs; - for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) { + for (RailType rt : EnumRange(RAILTYPE_END)) { const RailTypeInfo *rti = GetRailTypeInfo(rt); if (rti->label == 0) continue; uint32_t grfid = 0; diff --git a/src/console_gui.cpp b/src/console_gui.cpp index e7bb691c7a..17bba8f279 100644 --- a/src/console_gui.cpp +++ b/src/console_gui.cpp @@ -547,7 +547,7 @@ bool IsValidConsoleColour(ExtendedTextColour c) /* A text colour from the palette is used; must be the company * colour gradient, so it must be one of those. */ - for (Colours i = Colours::Begin; i < Colours::End; i++) { + for (Colours i : EnumRange(Colours::End)) { if (ExtendedTextColour{GetColourGradient(i, Shade::Normal)} == c) return true; } diff --git a/src/currency.cpp b/src/currency.cpp index 745f2c323f..c86ba78802 100644 --- a/src/currency.cpp +++ b/src/currency.cpp @@ -128,9 +128,8 @@ uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id) uint64_t GetMaskOfAllowedCurrencies() { uint64_t mask = 0LL; - uint i; - for (i = 0; i < CURRENCY_END; i++) { + for (Currencies i : EnumRange(CURRENCY_END)) { TimerGameCalendar::Year to_euro = _currency_specs[i].to_euro; if (to_euro != CF_NOEURO && to_euro != CF_ISEURO && TimerGameCalendar::year >= to_euro) continue; @@ -162,7 +161,7 @@ static const IntervalTimer _check_switch_to_euro({TimerGameCa */ void ResetCurrencies(bool preserve_custom) { - for (uint i = 0; i < CURRENCY_END; i++) { + for (Currencies i : EnumRange(CURRENCY_END)) { if (preserve_custom && i == CURRENCY_CUSTOM) continue; _currency_specs[i] = origin_currency_specs[i]; } diff --git a/src/depot_gui.cpp b/src/depot_gui.cpp index 7770ba44f4..34945184a1 100644 --- a/src/depot_gui.cpp +++ b/src/depot_gui.cpp @@ -222,7 +222,7 @@ static void InitBlocksizeForVehicles(VehicleType type, EngineImageType image_typ */ void InitDepotWindowBlockSizes() { - for (VehicleType vt = VehicleType::Begin; vt < VehicleType::CompanyEnd; vt++) { + for (VehicleType vt : EnumRange(VehicleType::CompanyEnd)) { InitBlocksizeForVehicles(vt, EIT_IN_DEPOT); InitBlocksizeForVehicles(vt, EIT_PURCHASE); } diff --git a/src/driver.cpp b/src/driver.cpp index 631bf064b3..d91f53a35c 100644 --- a/src/driver.cpp +++ b/src/driver.cpp @@ -220,7 +220,7 @@ void DriverFactoryBase::MarkVideoDriverOperational() */ void DriverFactoryBase::GetDriversInfo(std::back_insert_iterator &output_iterator) { - for (Driver::Type type = Driver::Type::Begin; type != Driver::Type::End; type++) { + for (Driver::Type type : EnumRange(Driver::Type::End)) { fmt::format_to(output_iterator, "List of {} drivers:\n", GetDriverTypeName(type)); for (int priority = 10; priority >= 0; priority--) { diff --git a/src/driver.h b/src/driver.h index bf5a7a4ce6..bcfeb0de05 100644 --- a/src/driver.h +++ b/src/driver.h @@ -127,7 +127,7 @@ public: */ static void ShutdownDrivers() { - for (Driver::Type dt = Driver::Type::Begin; dt != Driver::Type::End; ++dt) { + for (Driver::Type dt : EnumRange(Driver::Type::End)) { auto &driver = GetActiveDriver(dt); if (driver != nullptr) driver->Stop(); } diff --git a/src/economy.cpp b/src/economy.cpp index 4cac152b64..e0003034be 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -289,7 +289,7 @@ int UpdateCompanyRatingAndValue(Company *c, bool update) int total_score = 0; int s; score = 0; - for (ScoreID i = ScoreID::Begin; i < ScoreID::End; i++) { + for (ScoreID i : EnumRange(ScoreID::End)) { /* Skip the total */ if (i == ScoreID::Total) continue; /* Check the score */ @@ -647,13 +647,13 @@ static void CompaniesGenStatistics() for (const Company *c : Company::Iterate()) { CommandCost cost(ExpensesType::Property); uint32_t rail_total = c->infrastructure.GetRailTotal(); - for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) { + for (RailType rt : EnumRange(RAILTYPE_END)) { if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total)); } cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal)); uint32_t road_total = c->infrastructure.GetRoadTotal(); uint32_t tram_total = c->infrastructure.GetTramTotal(); - for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) { + for (RoadType rt : EnumRange(ROADTYPE_END)) { if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total)); } cost.AddCost(CanalMaintenanceCost(c->infrastructure.water)); @@ -736,7 +736,7 @@ void RecomputePrices() _economy.max_loan = ((uint64_t)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL; /* Setup price bases */ - for (Price i = Price::Begin; i < Price::End; i++) { + for (Price i : EnumRange(Price::End)) { Money price = _price_base_specs[i].start_price; /* Apply difficulty settings */ diff --git a/src/elrail.cpp b/src/elrail.cpp index 636e815d83..10dd61ba28 100644 --- a/src/elrail.cpp +++ b/src/elrail.cpp @@ -134,7 +134,7 @@ static TrackBits MaskWireBits(TileIndex t, TrackBits tracks) if (!IsPlainRailTile(t)) return tracks; TrackdirBits neighbour_tdb{}; - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { /* If the neighbour tile is either not electrified or has no tracks that can be reached * from this tile, mark all trackdirs that can be reached from the neighbour tile * as needing no catenary. We make an exception for blocked station tiles with a matching @@ -310,7 +310,7 @@ static void DrawRailCatenaryRailway(const TileInfo *ti) SpriteID pylon_normal = GetPylonBase(ti->tile); SpriteID pylon_halftile = IsValidCorner(halftile_corner) ? GetPylonBase(ti->tile, TCX_UPPER_HALFTILE) : pylon_normal; - for (DiagDirection i = DiagDirection::Begin; i < DiagDirection::End; i++) { + for (DiagDirection i : EnumRange(DiagDirection::End)) { SpriteID pylon_base = (IsValidCorner(halftile_corner) && HasBit(InclinedSlope(i), halftile_corner)) ? pylon_halftile : pylon_normal; TileIndex neighbour = ti->tile + TileOffsByDiagDir(i); int elevation = GetPCPElevation(ti->tile, i); @@ -414,7 +414,7 @@ static void DrawRailCatenaryRailway(const TileInfo *ti) (!HasStationTileRail(ti->tile) || CanStationTileHavePylons(ti->tile))) { const auto &ppp_orders = _ppp_order[i][GetTileLocationGroup(ti->tile)]; - for (Direction k = Direction::Begin; k < Direction::End; k++) { + for (Direction k : EnumRange(Direction::End)) { Direction temp = ppp_orders[k]; if (ppp_allowed[i].Test(temp)) { diff --git a/src/engine.cpp b/src/engine.cpp index 5ee01ccc0b..a9304fdf14 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -535,7 +535,7 @@ bool Engine::IsVariantHidden(CompanyID c) const void EngineOverrideManager::ResetToDefaultMapping() { EngineID id = EngineID::Begin(); - for (VehicleType type = VehicleType::Train; type <= VehicleType::Aircraft; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { auto &map = this->mappings[type]; map.clear(); for (uint internal_id = 0; internal_id < GetOriginalEngineCount(type); internal_id++, ++id) { @@ -629,7 +629,7 @@ void SetupEngines() CloseWindowByClass(WindowClass::EnginePreview); _engine_pool.CleanPool(); - for (VehicleType type = VehicleType::Begin; type != VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { const auto &mapping = _engine_mngr.mappings[type]; /* Verify that the engine override manager has at least been set up with the default engines. */ diff --git a/src/fileio.cpp b/src/fileio.cpp index a549a34070..eed45545e6 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -84,7 +84,7 @@ static void FillValidSearchPaths(bool only_local_path) _valid_searchpaths.clear(); std::set seen{}; - for (Searchpath sp = Searchpath::Begin; sp < Searchpath::End; sp++) { + for (Searchpath sp : EnumRange(Searchpath::End)) { if (sp == Searchpath::WorkingDir && !_do_scan_working_directory) continue; if (only_local_path) { diff --git a/src/fontcache.cpp b/src/fontcache.cpp index c43124ac57..2bdaa9f99c 100644 --- a/src/fontcache.cpp +++ b/src/fontcache.cpp @@ -98,7 +98,7 @@ int GetCharacterHeight(FontSize size) */ /* static */ void FontCache::InitializeFontCaches() { - for (FontSize fs = FontSize::Begin; fs != FontSize::End; fs++) { + for (FontSize fs : EnumRange(FontSize::End)) { if (FontCache::Get(fs) != nullptr) continue; FontCache::Register(FontProviderManager::LoadFont(fs, FontType::Sprite, false, {}, {})); } @@ -133,7 +133,7 @@ void SetFont(FontSize fontsize, const std::string &font, uint size) if (fontsize != FontSize::Monospace) { /* Try to reload only the modified font. */ FontCacheSettings backup = _fcsettings; - for (FontSize fs = FontSize::Begin; fs < FontSize::End; fs++) { + for (FontSize fs : EnumRange(FontSize::End)) { if (fs == fontsize) continue; FontCache *fc = FontCache::Get(fs); GetFontCacheSubSetting(fs)->font = fc->HasParent() ? fc->GetFontName() : ""; diff --git a/src/fontcache/spritefontcache.cpp b/src/fontcache/spritefontcache.cpp index d9723ddae5..b912bb1f4b 100644 --- a/src/fontcache/spritefontcache.cpp +++ b/src/fontcache/spritefontcache.cpp @@ -106,7 +106,7 @@ void InitializeUnicodeGlyphMap(FontSize fs) */ void InitializeUnicodeGlyphMap() { - for (FontSize fs = FontSize::Begin; fs < FontSize::End; fs++) { + for (FontSize fs : EnumRange(FontSize::End)) { InitializeUnicodeGlyphMap(fs); } } diff --git a/src/framerate_gui.cpp b/src/framerate_gui.cpp index d69653959f..e973bda3b0 100644 --- a/src/framerate_gui.cpp +++ b/src/framerate_gui.cpp @@ -280,7 +280,7 @@ PerformanceMeasurer::~PerformanceMeasurer() if (this->elem == PFE_ALLSCRIPTS) { /* Hack to not record scripts total when no scripts are active */ bool any_active = _pf_data[PFE_GAMESCRIPT].num_valid > 0; - for (uint e = PFE_AI0; e < PFE_MAX; e++) any_active |= _pf_data[e].num_valid > 0; + for (PerformanceElement e : EnumRange(PFE_AI0, PFE_MAX)) any_active |= _pf_data[e].num_valid > 0; if (!any_active) { PerformanceMeasurer::SetInactive(PFE_ALLSCRIPTS); return; @@ -500,7 +500,7 @@ struct FramerateWindow : Window { this->rate_drawing.SetRate(_pf_data[PFE_DRAWING].GetRate(), _settings_client.gui.refresh_rate); int new_active = 0; - for (PerformanceElement e = PFE_FIRST; e < PFE_MAX; e++) { + for (PerformanceElement e : EnumRange(PFE_MAX)) { this->times_shortterm[e].SetTime(_pf_data[e].GetAverageDurationMilliseconds(8), MILLISECONDS_PER_TICK); this->times_longterm[e].SetTime(_pf_data[e].GetAverageDurationMilliseconds(NUM_FRAMERATE_POINTS), MILLISECONDS_PER_TICK); if (_pf_data[e].num_valid > 0) { @@ -1080,7 +1080,7 @@ void ConPrintFramerate() printed_anything = true; } - for (PerformanceElement e = PFE_FIRST; e < PFE_MAX; e++) { + for (PerformanceElement e : EnumRange(PFE_MAX)) { auto &pf = _pf_data[e]; if (pf.num_valid == 0) continue; std::string_view name; diff --git a/src/game/game_gui.cpp b/src/game/game_gui.cpp index 7cf4699706..8400156617 100644 --- a/src/game/game_gui.cpp +++ b/src/game/game_gui.cpp @@ -396,7 +396,7 @@ struct GSConfigWindow : public Window { const GameConfig *config = GameConfig::GetConfig(); this->SetWidgetDisabledState(WID_GSC_OPEN_URL, config->GetInfo() == nullptr || config->GetInfo()->GetURL().empty()); - for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { + for (TextfileType tft : EnumRange(TFT_CONTENT_BEGIN, TFT_CONTENT_END)) { this->SetWidgetDisabledState(WID_GSC_TEXTFILE + tft, !config->GetTextfile(tft, OWNER_DEITY).has_value()); } this->RebuildVisibleSettings(); diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp index ecfefb63eb..307cbb91e7 100644 --- a/src/graph_gui.cpp +++ b/src/graph_gui.cpp @@ -1525,7 +1525,7 @@ struct PerformanceRatingDetailWindow : Window { size.height = this->bar_height + WidgetDimensions::scaled.matrix.Vertical(); uint score_info_width = 0; - for (ScoreID i = ScoreID::Begin; i < ScoreID::End; i++) { + for (ScoreID i : EnumRange(ScoreID::End)) { score_info_width = std::max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + to_underlying(i)).width); } score_info_width += GetStringBoundingBox(GetString(STR_JUST_COMMA, GetParamMaxValue(1000))).width + WidgetDimensions::scaled.hsep_wide; @@ -1599,7 +1599,7 @@ struct PerformanceRatingDetailWindow : Window { /* ScoreID::Total has its own rules ;) */ if (score_type == ScoreID::Total) { - for (ScoreID i = ScoreID::Begin; i < ScoreID::End; i++) score += _score_info[i].score; + for (ScoreID i : EnumRange(ScoreID::End)) score += _score_info[i].score; needed = SCORE_MAX; } diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp index 9051bbc07c..919061a344 100644 --- a/src/group_cmd.cpp +++ b/src/group_cmd.cpp @@ -121,7 +121,7 @@ uint16_t GroupStatistics::GetNumEngines(EngineID engine) const { /* Set up the engine count for all companies */ for (Company *c : Company::Iterate()) { - for (VehicleType type = VehicleType::Begin; type < VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { c->group_all[type].Clear(); c->group_default[type].Clear(); } @@ -216,7 +216,7 @@ uint16_t GroupStatistics::GetNumEngines(EngineID engine) const { /* Set up the engine count for all companies */ for (Company *c : Company::Iterate()) { - for (VehicleType type = VehicleType::Begin; type < VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { c->group_all[type].ClearProfits(); c->group_default[type].ClearProfits(); } @@ -243,7 +243,7 @@ uint16_t GroupStatistics::GetNumEngines(EngineID engine) const { /* Set up the engine count for all companies */ Company *c = Company::Get(company); - for (VehicleType type = VehicleType::Begin; type < VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { c->group_all[type].ClearAutoreplace(); c->group_default[type].ClearAutoreplace(); } diff --git a/src/highscore.cpp b/src/highscore.cpp index 8a15aa5507..7c6c67eb11 100644 --- a/src/highscore.cpp +++ b/src/highscore.cpp @@ -120,7 +120,7 @@ void SaveToHighScore() auto &fp = *ofp; /* Does not iterate through the complete array!. */ - for (int i = 0; i < SP_SAVED_HIGHSCORE_END; i++) { + for (SettingsProfile i : EnumRange(SP_SAVED_HIGHSCORE_END)) { for (HighScore &hs : _highscore_table[i]) { /* This code is weird and old fashioned to keep compatibility with the old high score files. */ uint8_t name_length = ClampTo(hs.name.size()); @@ -145,7 +145,7 @@ void LoadFromHighScore() auto &fp = *ofp; /* Does not iterate through the complete array!. */ - for (int i = 0; i < SP_SAVED_HIGHSCORE_END; i++) { + for (SettingsProfile i : EnumRange(SP_SAVED_HIGHSCORE_END)) { for (HighScore &hs : _highscore_table[i]) { /* This code is weird and old fashioned to keep compatibility with the old high score files. */ uint8_t name_length; diff --git a/src/landscape.cpp b/src/landscape.cpp index cabbe6b185..60bce0c0ff 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -1046,7 +1046,7 @@ static bool FindSpring(TileIndex tile) }; uint num_hills = 0; - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex check_tile = tile; for (uint i = 0; i < max_hill_distance; i++) { check_tile = TileAddByDiagDir(check_tile, d); @@ -1089,7 +1089,7 @@ static void MakeLake(TileIndex lake_centre, uint height_lake) for (uint loops = 0; loops < 2; ++loops) { for (TileIndex tile : SpiralTileSequence(lake_centre, diameter)) { if (!IsValidRiverTerminusTile(tile, height_lake)) continue; - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex t = tile + TileOffsByDiagDir(d); if (IsWaterTile(t)) { MakeRiverAndModifyDesertZoneAround(tile); @@ -1209,7 +1209,7 @@ void RiverMakeWider(TileIndex tile, TileIndex origin_tile) */ /* First, determine the desired slope based on adjacent river tiles. This doesn't necessarily match the origin tile for the SpiralTileSequence. */ - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex other_tile = TileAddByDiagDir(tile, d); Slope other_slope = GetTileSlope(other_tile); @@ -1240,7 +1240,7 @@ void RiverMakeWider(TileIndex tile, TileIndex origin_tile) /* If the river is flat and the adjacent tile has one corner lowered, we want to raise it. */ if (desired_slope == SLOPE_FLAT && IsSlopeWithThreeCornersRaised(cur_slope)) { /* Make sure we're not affecting an existing river slope tile. */ - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex other_tile = TileAddByDiagDir(tile, d); if (IsInclinedSlope(GetTileSlope(other_tile)) && IsWaterTile(other_tile)) return; } @@ -1363,7 +1363,7 @@ static bool CountConnectedSeaTiles(TileIndex tile, std::unordered_set if (sea.size() > limit) return false; /* Count adjacent tiles using recursion. */ - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex t = tile + TileOffsByDiagDir(d); if (IsValidTile(t) && !sea.contains(t)) { if (CountConnectedSeaTiles(t, sea, limit)) return true; @@ -1430,7 +1430,7 @@ static std::tuple FlowRiver(TileIndex spring, TileIndex begin, uint } } - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex t = end + TileOffsByDiagDir(d); if (IsValidTile(t) && !marks.contains(t) && RiverFlowsDown(end, t)) { marks.insert(t); @@ -1542,7 +1542,7 @@ static uint CalculateCoverageLine(uint coverage, uint edge_multiplier) if (edge_multiplier != 0) { /* Check if any of our neighbours is below us. */ - for (DiagDirection dir = DiagDirection::Begin; dir != DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { TileIndex neighbour_tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir)); if (IsValidTile(neighbour_tile) && TileHeight(neighbour_tile) < h) { edge_histogram[h]++; diff --git a/src/linkgraph/refresh.cpp b/src/linkgraph/refresh.cpp index ed8bdef769..03a4b39f77 100644 --- a/src/linkgraph/refresh.cpp +++ b/src/linkgraph/refresh.cpp @@ -188,7 +188,7 @@ void LinkRefresher::RefreshStats(VehicleOrderID cur, VehicleOrderID next) Station *st = Station::GetIfValid(orders[cur].GetDestination().ToStationID()); if (st != nullptr && next_station != StationID::Invalid() && next_station != st->index) { Station *st_to = Station::Get(next_station); - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { /* Refresh the link and give it a minimum capacity. */ uint cargo_quantity = this->capacities[cargo]; @@ -260,7 +260,7 @@ void LinkRefresher::RefreshLinks(VehicleOrderID cur, VehicleOrderID next, Refres } else if (!flags.Test(RefreshFlag::InAutorefit)) { flags.Set(RefreshFlag::InAutorefit); LinkRefresher backup(*this); - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (CargoSpec::Get(cargo)->IsValid() && this->HandleRefit(cargo)) { this->RefreshLinks(cur, next, flags, num_hops); *this = backup; diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 3169a79d8d..108f8ce726 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -553,10 +553,10 @@ void ShowSelectGameWindow(); */ void SetupColoursAndInitialWindow() { - for (Colours i = Colours::Begin; i != Colours::End; i++) { + for (Colours i : EnumRange(Colours::End)) { const uint8_t *b = GetNonSprite(GetColourPalette(i), SpriteType::Recolour) + 1; assert(b != nullptr); - for (Shade j = Shade::Begin; j < Shade::End; j++) { + for (Shade j : EnumRange(Shade::End)) { SetColourGradient(i, j, PixelColour{b[0xC6 + to_underlying(j)]}); } } diff --git a/src/map.cpp b/src/map.cpp index da1aa8b478..f88d0deafe 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -279,7 +279,7 @@ uint GetClosestWaterDistance(TileIndex tile, bool water) y--; /* going counter-clockwise around this square */ - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { static constexpr DiagDirectionIndexArray ddx{-1, 1, 1, -1}; static constexpr DiagDirectionIndexArray ddy{ 1, 1, -1, -1}; diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index 0679989b41..3b8eb8cb1b 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -160,7 +160,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendProtocol() /* announce the protocol version */ p->Send_uint8(NETWORK_GAME_ADMIN_VERSION); - for (int i = 0; i < ADMIN_UPDATE_END; i++) { + for (AdminUpdateType i : EnumRange(ADMIN_UPDATE_END)) { p->Send_bool (true); p->Send_uint16(i); p->Send_uint16(_admin_update_type_frequencies[i].base()); @@ -1115,7 +1115,7 @@ void ServerNetworkAdminSocketHandler::WelcomeAll() void NetworkAdminUpdate(AdminUpdateFrequency freq) { for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) { - for (int i = 0; i < ADMIN_UPDATE_END; i++) { + for (AdminUpdateType i : EnumRange(ADMIN_UPDATE_END)) { if (as->update_frequency[i].Test(freq)) { /* Update the admin for the required details */ switch (i) { diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index 00bfabd6a3..8d0ce81e63 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -609,7 +609,7 @@ public: size.width += Window::SortButtonWidth() * 2; /* And also enough for the width of each type of content. */ Dimension d = size; - for (ContentType ct = ContentType::Begin; ct != ContentType::End; ++ct) { + for (ContentType ct : EnumRange(ContentType::Begin, ContentType::End)) { d = maxdim(d, GetStringBoundingBox(GetContentTypeString(ct))); } size.width = std::max(size.width, d.width + padding.width); @@ -1010,7 +1010,7 @@ public: this->SetWidgetDisabledState(WID_NCL_SELECT_ALL, !show_select_all); this->SetWidgetDisabledState(WID_NCL_SELECT_UPDATE, !show_select_upgrade || !this->filter_data.string_filter.IsEmpty()); this->SetWidgetDisabledState(WID_NCL_OPEN_URL, this->selected == nullptr || this->selected->url.empty()); - for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { + for (TextfileType tft : EnumRange(TFT_CONTENT_BEGIN, TFT_CONTENT_END)) { this->SetWidgetDisabledState(WID_NCL_TEXTFILE + tft, this->selected == nullptr || this->selected->state != ContentInfo::State::AlreadyHere || !this->selected->GetTextfile(tft).has_value()); } } @@ -1037,7 +1037,7 @@ EnumIndexArray NetworkContentListWin */ void BuildContentTypeStringList() { - for (ContentType ct = ContentType::Begin; ct != ContentType::End; ++ct) { + for (ContentType ct : EnumRange(ContentType::Begin, ContentType::End)) { NetworkContentListWindow::content_type_strs[ct] = GetString(GetContentTypeString(ct)); } } diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 269c8202bb..39dd75302e 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -2154,8 +2154,8 @@ struct NetworkJoinStatusWindow : Window { switch (widget) { case WID_NJS_PROGRESS_BAR: /* Account for the statuses */ - for (uint i = 0; i < to_underlying(NetworkJoinStatus::End); i++) { - size = maxdim(size, GetStringBoundingBox(STR_NETWORK_CONNECTING_1 + i)); + for (NetworkJoinStatus i : EnumRange(NetworkJoinStatus::End)) { + size = maxdim(size, GetStringBoundingBox(STR_NETWORK_CONNECTING_1 + to_underlying(i))); } /* For the number of waiting (other) players */ size = maxdim(size, GetStringBoundingBox(GetString(STR_NETWORK_CONNECTING_WAITING, GetParamMaxValue(MAX_CLIENTS)))); diff --git a/src/newgrf.cpp b/src/newgrf.cpp index e17d45b8b5..b9c5c0d9aa 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -653,7 +653,7 @@ static CargoLabel GetActiveCargoLabel(const std::variantcanal_local_properties[i].callback_mask; _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags; @@ -1514,7 +1514,7 @@ static void FinalisePriceBaseMultipliers() source.grf_features.Set(features); dest.grf_features.Set(features); - for (Price p = Price::Begin; p < Price::End; p++) { + for (Price p : EnumRange(Price::End)) { /* No price defined -> nothing to do */ if (!features.Test(_price_base_specs[p].grf_feature) || source.price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue; Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source.filename, p, dest.filename); @@ -1532,7 +1532,7 @@ static void FinalisePriceBaseMultipliers() source.grf_features.Set(features); dest.grf_features.Set(features); - for (Price p = Price::Begin; p < Price::End; p++) { + for (Price p : EnumRange(Price::End)) { /* Already a price defined -> nothing to do */ if (!features.Test(_price_base_specs[p].grf_feature) || dest.price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue; Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source.filename, dest.filename); @@ -1550,7 +1550,7 @@ static void FinalisePriceBaseMultipliers() source.grf_features.Set(features); dest.grf_features.Set(features); - for (Price p = Price::Begin; p < Price::End; p++) { + for (Price p : EnumRange(Price::End)) { if (!features.Test(_price_base_specs[p].grf_feature)) continue; if (source.price_base_multipliers[p] != dest.price_base_multipliers[p]) { Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest.filename, source.filename); @@ -1563,7 +1563,7 @@ static void FinalisePriceBaseMultipliers() for (auto &file : _grf_files) { if (file.grf_version >= 8) continue; PriceMultipliers &price_base_multipliers = file.price_base_multipliers; - for (Price p = Price::Begin; p < Price::End; p++) { + for (Price p : EnumRange(Price::End)) { Price fallback_price = _price_base_specs[p].fallback_price; if (fallback_price != Price::Invalid && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { /* No price multiplier has been set. @@ -1576,7 +1576,7 @@ static void FinalisePriceBaseMultipliers() /* Decide local/global scope of price base multipliers */ for (auto &file : _grf_files) { PriceMultipliers &price_base_multipliers = file.price_base_multipliers; - for (Price p = Price::Begin; p < Price::End; p++) { + for (Price p : EnumRange(Price::End)) { if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { /* No multiplier was set; set it to a neutral value */ price_base_multipliers[p] = 0; @@ -1811,7 +1811,7 @@ void LoadNewGRF(SpriteID load_index, uint num_baseset) /* Load newgrf sprites * in each loading stage, (try to) open each file specified in the config * and load information from it. */ - for (GrfLoadingStage stage = GrfLoadingStage::LabelScan; stage <= GrfLoadingStage::Activation; stage++) { + for (GrfLoadingStage stage : EnumRange(GrfLoadingStage::LabelScan, GrfLoadingStage::End)) { /* Set activated grfs back to will-be-activated between reservation- and activation-stage. * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */ for (const auto &c : _grfconfig) { diff --git a/src/newgrf.h b/src/newgrf.h index 1c76a98311..a8a3807faa 100644 --- a/src/newgrf.h +++ b/src/newgrf.h @@ -60,6 +60,7 @@ enum class GrfLoadingStage : uint8_t { Init, ///< Second step of NewGRF loading; load all actions into memory. Reserve, ///< Third step of NewGRF loading; reserve features and GRMs. Activation, ///< Forth step of NewGRF loading; activate the features. + End, ///< End marker. }; DECLARE_INCREMENT_DECREMENT_OPERATORS(GrfLoadingStage) diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp index f40740cee2..b4f616933d 100644 --- a/src/newgrf_debug_gui.cpp +++ b/src/newgrf_debug_gui.cpp @@ -1087,7 +1087,7 @@ struct SpriteAlignerWindow : Window { } SpriteAlignerWindow::zoom = Clamp(SpriteAlignerWindow::zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max); - for (ZoomLevel z = ZoomLevel::Begin; z < ZoomLevel::End; z++) { + for (ZoomLevel z : EnumRange(ZoomLevel::End)) { this->SetWidgetsDisabledState(z < _settings_client.gui.zoom_min || z > _settings_client.gui.zoom_max, WID_SA_ZOOM + to_underlying(z)); this->SetWidgetsLoweredState(SpriteAlignerWindow::zoom == z, WID_SA_ZOOM + to_underlying(z)); } diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp index 2bcd9a4e97..db2b6b6a0d 100644 --- a/src/newgrf_gui.cpp +++ b/src/newgrf_gui.cpp @@ -1252,7 +1252,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { ); const GRFConfig *selected_config = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel; - for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { + for (TextfileType tft : EnumRange(TFT_CONTENT_BEGIN, TFT_CONTENT_END)) { this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, selected_config == nullptr || !selected_config->GetTextfile(tft).has_value()); } this->SetWidgetDisabledState(WID_NS_OPEN_URL, selected_config == nullptr || !selected_config->GetURL().has_value()); diff --git a/src/newgrf_railtype.cpp b/src/newgrf_railtype.cpp index 8218625fd6..0ca3dfddad 100644 --- a/src/newgrf_railtype.cpp +++ b/src/newgrf_railtype.cpp @@ -245,7 +245,7 @@ void SetCurrentRailTypeLabelList() { _railtype_list.clear(); - for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) { + for (RailType rt : EnumRange(RAILTYPE_END)) { _railtype_list.emplace_back(GetRailTypeInfo(rt)->label, 0); } } diff --git a/src/newgrf_roadtype.cpp b/src/newgrf_roadtype.cpp index 990b8e97f7..aefe053969 100644 --- a/src/newgrf_roadtype.cpp +++ b/src/newgrf_roadtype.cpp @@ -273,7 +273,7 @@ void ConvertRoadTypes() void SetCurrentRoadTypeLabelList() { _roadtype_list.clear(); - for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) { + for (RoadType rt : EnumRange(ROADTYPE_END)) { _roadtype_list.emplace_back(GetRoadTypeInfo(rt)->label, to_underlying(GetRoadTramType(rt))); } } diff --git a/src/newgrf_spritegroup.h b/src/newgrf_spritegroup.h index a36342a3f3..c16067721b 100644 --- a/src/newgrf_spritegroup.h +++ b/src/newgrf_spritegroup.h @@ -463,7 +463,7 @@ public: uint32_t GetReseedSum() const { uint32_t sum = 0; - for (VarSpriteGroupScope vsg = VSG_BEGIN; vsg < VSG_END; vsg++) { + for (VarSpriteGroupScope vsg : EnumRange(VSG_END)) { sum |= this->reseed[vsg]; } return sum; diff --git a/src/pathfinder/yapf/yapf_river_builder.cpp b/src/pathfinder/yapf/yapf_river_builder.cpp index f9c34cc7ba..f99d20a742 100644 --- a/src/pathfinder/yapf/yapf_river_builder.cpp +++ b/src/pathfinder/yapf/yapf_river_builder.cpp @@ -88,7 +88,7 @@ public: /** @copydoc CYapfBaseT::PfFollowNodeFunc */ inline void PfFollowNode(Node &old_node) { - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; ++d) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { const TileIndex t = old_node.GetTile() + TileOffsByDiagDir(d); if (IsValidTile(t) && RiverFlowsDown(old_node.GetTile(), t)) { Node &node = Yapf().CreateNewNode(); diff --git a/src/rail.cpp b/src/rail.cpp index 1624dbf1f1..beaa6d0075 100644 --- a/src/rail.cpp +++ b/src/rail.cpp @@ -105,7 +105,7 @@ RailTypes AddDateIntroducedRailTypes(RailTypes current, TimerGameCalendar::Date { RailTypes rts = current; - for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) { + for (RailType rt : EnumRange(RAILTYPE_END)) { const RailTypeInfo *rti = GetRailTypeInfo(rt); /* Unused rail type. */ if (rti->label == 0) continue; diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index 37cd1d09ef..ff2928e12a 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -103,7 +103,7 @@ void ResolveRailTypeGUISprites(RailTypeInfo *rti) SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY}, }}}; - for (SignalType type = SignalType::Block; type < SignalType::End; type = static_cast(to_underlying(type) + 1)) { + for (SignalType type : EnumRange(SignalType::End)) { for (SignalVariant var : {SignalVariant::Electric, SignalVariant::Semaphore}) { SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SignalState::Red, true); SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SignalState::Green, true); @@ -2729,7 +2729,7 @@ static void TileLoop_Rail(TileIndex tile) Owner owner = GetTileOwner(tile); DiagDirections fences{}; - for (DiagDirection d = DiagDirection::Begin; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { static constexpr DiagDirectionIndexArray dir_to_trackbits{TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW}; /* Track bit on this edge => no fence. */ diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index 7f9d6f1a22..7a35c43395 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -1554,7 +1554,7 @@ public: this->sig_sprite_size.height = 0; this->sig_sprite_bottom_offset = 0; const RailTypeInfo *rti = GetRailTypeInfo(_cur_railtype); - for (SignalType type = SignalType::Block; type < SignalType::End; type = static_cast(to_underlying(type) + 1)) { + for (SignalType type : EnumRange(SignalType::End)) { for (SignalVariant variant : {SignalVariant::Electric, SignalVariant::Semaphore}) { for (SignalState state : {SignalState::Red, SignalState::Green}) { Point offset; diff --git a/src/road.cpp b/src/road.cpp index a3d56eed42..9d07a694d9 100644 --- a/src/road.cpp +++ b/src/road.cpp @@ -59,7 +59,7 @@ static bool IsPossibleCrossing(const TileIndex tile, Axis ax) RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb) { if (!IsValidTile(tile)) return {}; - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { const TileIndex neighbour_tile = TileAddByDiagDir(tile, dir); /* Get the Roadbit pointing to the neighbour_tile */ @@ -178,7 +178,7 @@ RoadTypes AddDateIntroducedRoadTypes(RoadTypes current, TimerGameCalendar::Date { RoadTypes rts = current; - for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) { + for (RoadType rt : EnumRange(ROADTYPE_END)) { const RoadTypeInfo *rti = GetRoadTypeInfo(rt); /* Unused road type. */ if (rti->label == 0) continue; diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 0b67070bc6..9f70e3dfb8 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -1376,7 +1376,7 @@ void DrawRoadTypeCatenary(const TileInfo *ti, RoadType rt, RoadBits rb) /* On junctions we check whether neighbouring tiles also have catenary, and possibly * do not draw catenary towards those neighbours, which do not have catenary. */ RoadBits rb_new{}; - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { if (rb.Any(DiagDirToRoadBits(dir))) { TileIndex neighbour = TileAddByDiagDir(ti->tile, dir); if (MayHaveRoad(neighbour)) { diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 1cd4d6506b..0702b8ad69 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -114,7 +114,7 @@ void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_cla bool has_canal = false; bool has_river = false; - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { Tile neighbour = TileAddByDiagDir(t, dir); switch (GetTileType(neighbour)) { case TileType::Water: @@ -436,7 +436,7 @@ static void FixOwnerOfRailTrack(Tile t) } /* try to find any connected rail */ - for (DiagDirection dd = DiagDirection::Begin; dd < DiagDirection::End; dd++) { + for (DiagDirection dd : EnumRange(DiagDirection::End)) { TileIndex tt{t + TileOffsByDiagDir(dd)}; if (GetTileTrackStatus(t, TRANSPORT_RAIL, RoadTramType::Invalid, dd).trackdirs.Any() && GetTileTrackStatus(tt, TRANSPORT_RAIL, RoadTramType::Invalid, ReverseDiagDir(dd)).trackdirs.Any() && diff --git a/src/saveload/labelmaps_sl.cpp b/src/saveload/labelmaps_sl.cpp index 01248a50de..c1ab94b4fb 100644 --- a/src/saveload/labelmaps_sl.cpp +++ b/src/saveload/labelmaps_sl.cpp @@ -45,7 +45,7 @@ struct RAILChunkHandler : ChunkHandler { SlTableHeader(description); LabelObject lo; - for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) { + for (RailType r : EnumRange(RAILTYPE_END)) { lo.label = GetRailTypeInfo(r)->label; SlSetArrayIndex(r); @@ -81,7 +81,7 @@ struct ROTTChunkHandler : ChunkHandler { SlTableHeader(description); LabelObject lo; - for (RoadType r = ROADTYPE_BEGIN; r != ROADTYPE_END; r++) { + for (RoadType r : EnumRange(ROADTYPE_END)) { const RoadTypeInfo *rti = GetRoadTypeInfo(r); lo.label = rti->label; lo.subtype = to_underlying(GetRoadTramType(r)); diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp index 443f6a1086..78c906ba51 100644 --- a/src/saveload/oldloader_sl.cpp +++ b/src/saveload/oldloader_sl.cpp @@ -904,7 +904,7 @@ static bool LoadOldCompanyYearly(LoadgameState &ls, int num) { Company *c = Company::Get(_current_company_id); - for (ExpensesType i = ExpensesType::Begin; i != ExpensesType::End; ++i) { + for (ExpensesType i : EnumRange(ExpensesType::End)) { if (_savegame_type == SGT_TTO && i == ExpensesType::Property) { _old_yearly = 0; // property maintenance } else { diff --git a/src/script/api/script_cargolist.cpp b/src/script/api/script_cargolist.cpp index e72b11298b..19057b3e1d 100644 --- a/src/script/api/script_cargolist.cpp +++ b/src/script/api/script_cargolist.cpp @@ -53,7 +53,7 @@ ScriptCargoList_StationAccepting::ScriptCargoList_StationAccepting(StationID sta if (!ScriptStation::IsValidStation(station_id)) return; const Station *st = ::Station::Get(station_id); - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (st->goods[cargo].status.Test(GoodsEntry::State::Acceptance)) this->AddItem(cargo); } } diff --git a/src/script/api/script_infrastructure.cpp b/src/script/api/script_infrastructure.cpp index 4ec91d3cb9..8e4e9a0669 100644 --- a/src/script/api/script_infrastructure.cpp +++ b/src/script/api/script_infrastructure.cpp @@ -92,7 +92,7 @@ case INFRASTRUCTURE_RAIL: { Money cost; uint32_t rail_total = c->infrastructure.GetRailTotal(); - for (::RailType rt = ::RAILTYPE_BEGIN; rt != ::RAILTYPE_END; rt++) { + for (::RailType rt : EnumRange(::RAILTYPE_END)) { cost += RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total); } return cost; @@ -105,7 +105,7 @@ Money cost; uint32_t road_total = c->infrastructure.GetRoadTotal(); uint32_t tram_total = c->infrastructure.GetTramTotal(); - for (::RoadType rt = ::ROADTYPE_BEGIN; rt != ::ROADTYPE_END; rt++) { + for (::RoadType rt : EnumRange(::ROADTYPE_END)) { cost += RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total); } return cost; diff --git a/src/script/api/script_railtypelist.cpp b/src/script/api/script_railtypelist.cpp index 7b779f813b..7f108b0bd1 100644 --- a/src/script/api/script_railtypelist.cpp +++ b/src/script/api/script_railtypelist.cpp @@ -19,7 +19,7 @@ ScriptRailTypeList::ScriptRailTypeList() EnforceDeityOrCompanyModeValid_Void(); bool is_deity = ScriptCompanyMode::IsDeity(); ::CompanyID owner = ScriptObject::GetCompany(); - for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) { + for (RailType rt : EnumRange(RAILTYPE_END)) { if (is_deity || ::HasRailTypeAvail(owner, rt)) this->AddItem(rt); } } diff --git a/src/script/api/script_roadtypelist.cpp b/src/script/api/script_roadtypelist.cpp index 1d213ce104..7200bd3b00 100644 --- a/src/script/api/script_roadtypelist.cpp +++ b/src/script/api/script_roadtypelist.cpp @@ -17,7 +17,7 @@ ScriptRoadTypeList::ScriptRoadTypeList(ScriptRoad::RoadTramTypes rtts) { EnforceDeityOrCompanyModeValid_Void(); ::CompanyID owner = ScriptObject::GetCompany(); - for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) { + for (RoadType rt : EnumRange(ROADTYPE_END)) { if (!::RoadTramTypes{rtts}.Test(GetRoadTramType(rt))) continue; if (::HasRoadTypeAvail(owner, rt)) this->AddItem(rt); } diff --git a/src/script/api/script_townlist.cpp b/src/script/api/script_townlist.cpp index eec56c481b..9632bc7efa 100644 --- a/src/script/api/script_townlist.cpp +++ b/src/script/api/script_townlist.cpp @@ -20,7 +20,7 @@ ScriptTownList::ScriptTownList(HSQUIRRELVM vm) ScriptTownEffectList::ScriptTownEffectList() { - for (TownAcceptanceEffect i = TownAcceptanceEffect::Begin; i < TownAcceptanceEffect::End; ++i) { + for (TownAcceptanceEffect i : EnumRange(TownAcceptanceEffect::End)) { this->AddItem(to_underlying(i)); } } diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index ec609dec9c..cf574fa756 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -570,7 +570,7 @@ struct GameOptionsWindow : Window { break; case WID_GO_RESTRICT_DROPDOWN: - for (int mode = 0; mode != RM_END; mode++) { + for (RestrictionMode mode : EnumRange(RM_END)) { /* If we are in adv. settings screen for the new game's settings, * we don't want to allow comparing with new game's settings. */ bool disabled = mode == RM_CHANGED_AGAINST_NEW && settings_ptr == &_settings_newgame; @@ -1566,7 +1566,7 @@ struct GameOptionsWindow : Window { this->SetWidgetDisabledState(WID_GO_BASE_SFX_OPEN_URL, BaseSounds::GetUsedSet() == nullptr || BaseSounds::GetUsedSet()->url.empty()); this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_OPEN_URL, BaseMusic::GetUsedSet() == nullptr || BaseMusic::GetUsedSet()->url.empty()); - for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { + for (TextfileType tft : EnumRange(TFT_CONTENT_BEGIN, TFT_CONTENT_END)) { this->SetWidgetDisabledState(WID_GO_BASE_GRF_TEXTFILE + tft, BaseGraphics::GetUsedSet() == nullptr || !BaseGraphics::GetUsedSet()->GetTextfile(tft).has_value()); this->SetWidgetDisabledState(WID_GO_BASE_SFX_TEXTFILE + tft, BaseSounds::GetUsedSet() == nullptr || !BaseSounds::GetUsedSet()->GetTextfile(tft).has_value()); this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_TEXTFILE + tft, BaseMusic::GetUsedSet() == nullptr || !BaseMusic::GetUsedSet()->GetTextfile(tft).has_value()); diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp index 81fd2a15df..e049270d49 100644 --- a/src/ship_cmd.cpp +++ b/src/ship_cmd.cpp @@ -569,7 +569,7 @@ bool IsShipDestinationTile(TileIndex tile, StationID station) { assert(IsDockingTile(tile)); /* Check each tile adjacent to docking tile. */ - for (DiagDirection d = DiagDirection::Begin; d != DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex t = tile + TileOffsByDiagDir(d); if (!IsValidTile(t)) continue; if (IsDockTile(t) && GetStationIndex(t) == station && IsDockWaterPart(t)) return true; diff --git a/src/signal.cpp b/src/signal.cpp index d6b37252d7..7530514f82 100644 --- a/src/signal.cpp +++ b/src/signal.cpp @@ -350,7 +350,7 @@ static SigFlags ExploreSegment(Owner owner) } } - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { // test all possible exit directions + for (DiagDirection dir : EnumRange(DiagDirection::End)) { // test all possible exit directions if (dir != enterdir && tracks.Any(_enterdir_to_trackbits[dir])) { // any accessible track? TileIndex newtile = tile + TileOffsByDiagDir(dir); // new tile to check DiagDirection newdir = ReverseDiagDir(dir); // direction we are entering from diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp index 03bc452298..bd162d1fed 100644 --- a/src/signs_gui.cpp +++ b/src/signs_gui.cpp @@ -490,7 +490,7 @@ struct SignWindow : Window, SignList { if (widget == WID_QES_COLOUR) { const Dimension square_size = GetSpriteSize(SPR_SQUARE); const uint string_padding = square_size.width + WidgetDimensions::scaled.hsep_normal + padding.width; - for (Colours colour = Colours::Begin; colour != Colours::End; ++colour) { + for (Colours colour : EnumRange(Colours::End)) { size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DARK_BLUE + to_underlying(colour)).width + string_padding); } size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + string_padding); @@ -503,7 +503,7 @@ struct SignWindow : Window, SignList { void ShowColourDropDownMenu() { DropDownList list; - for (Colours colour = Colours::Begin; colour != Colours::End; ++colour) { + for (Colours colour : EnumRange(Colours::End)) { list.emplace_back(MakeDropDownListIconItem(SPR_SQUARE, GetColourPalette(colour), STR_COLOUR_DARK_BLUE + to_underlying(colour), colour)); } const int selected = to_underlying(this->new_colour.value_or(Sign::Get(this->cur_sign)->text_colour)); diff --git a/src/spritecache.cpp b/src/spritecache.cpp index e7745ad124..6afa986cab 100644 --- a/src/spritecache.cpp +++ b/src/spritecache.cpp @@ -380,9 +380,7 @@ static bool ResizeSprites(SpriteLoader::SpriteCollection &sprite, ZoomLevels spr if (!PadSprites(sprite, sprite_avail, encoder)) return false; /* Create other missing zoom levels */ - for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) { - if (zoom == ZoomLevel::Min) continue; - + for (ZoomLevel zoom : EnumRange(ZoomLevel::In2x, ZoomLevel::End)) { if (sprite_avail.Test(zoom)) { /* Check that size and offsets match the fully zoomed image. */ [[maybe_unused]] const auto &root_sprite = sprite[ZoomLevel::Min]; diff --git a/src/station.cpp b/src/station.cpp index fbb91d8bf8..0f69a915b6 100644 --- a/src/station.cpp +++ b/src/station.cpp @@ -100,7 +100,7 @@ Station::~Station() if (a->targetairport == this->index) a->targetairport = StationID::Invalid(); } - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { LinkGraph *lg = LinkGraph::GetIfValid(this->goods[cargo].link_graph); if (lg == nullptr) continue; diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index cf67ea9d34..ae72b0013f 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -638,7 +638,7 @@ void UpdateStationAcceptance(Station *st, bool show_msg) } /* Adjust in case our station only accepts fewer kinds of goods */ - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { uint amt = acceptance[cargo]; /* Make sure the station can accept the goods type. */ @@ -828,7 +828,7 @@ CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int int flat_z = z + GetSlopeMaxZ(tileh); if (tileh != SLOPE_FLAT) { /* Forbid building if the tile faces a slope in a invalid direction. */ - for (DiagDirection dir = DiagDirection::Begin; dir != DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { if (invalid_dirs.Test(dir) && !CanBuildDepotByTileh(dir, tileh)) { return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED); } @@ -2988,7 +2988,7 @@ CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station void RemoveDockingTile(TileIndex t) { - for (DiagDirection d = DiagDirection::Begin; d != DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex tile = t + TileOffsByDiagDir(d); if (!IsValidTile(tile)) continue; @@ -3012,7 +3012,7 @@ void ClearDockingTilesCheckingNeighbours(TileIndex tile) assert(IsValidTile(tile)); /* Clear and maybe re-set docking tile */ - for (DiagDirection d = DiagDirection::Begin; d != DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex docking_tile = tile + TileOffsByDiagDir(d); if (!IsValidTile(docking_tile)) continue; @@ -3035,7 +3035,7 @@ static TileIndex FindDockLandPart(TileIndex t) StationGfx gfx = GetStationGfx(t); if (gfx < GFX_DOCK_BASE_WATER_PART) return t; - for (DiagDirection d = DiagDirection::Begin; d != DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex tile = t + TileOffsByDiagDir(d); if (!IsValidTile(tile)) continue; if (!IsDockTile(tile)) continue; @@ -3901,7 +3901,7 @@ void TriggerWatchedCargoCallbacks(Station *st) { /* Collect cargoes accepted since the last big tick. */ CargoTypes cargoes{}; - for (CargoType cargo_type{}; cargo_type < NUM_CARGO; ++cargo_type) { + for (CargoType cargo_type : EnumRange(NUM_CARGO)) { if (st->goods[cargo_type].status.Test(GoodsEntry::State::AcceptedBigtick)) cargoes.Set(cargo_type); } @@ -4175,7 +4175,7 @@ void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid */ void DeleteStaleLinks(Station *from) { - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual); GoodsEntry &ge = from->goods[cargo]; LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph); diff --git a/src/station_gui.cpp b/src/station_gui.cpp index 438d86d3ea..2ffa5816c9 100644 --- a/src/station_gui.cpp +++ b/src/station_gui.cpp @@ -88,7 +88,7 @@ int DrawStationCoverageAreaText(const Rect &r, StationCoverageType sct, int rad, } /* Convert cargo counts to a set of cargo bits, and draw the result. */ - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { switch (sct) { case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(cargo, CargoClass::Passengers)) continue; break; case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(cargo, CargoClass::Passengers)) continue; break; @@ -316,10 +316,10 @@ protected: if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) { bool has_rating = false; /* Add to the station/cargo counts. */ - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (st->goods[cargo].HasRating()) this->stations_per_cargo_type[cargo]++; } - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (st->goods[cargo].HasRating()) { has_rating = true; if (this->filter.cargoes.Test(cargo)) { @@ -1668,7 +1668,7 @@ struct StationViewWindow : public Window { */ void BuildCargoList(CargoDataEntry *entry, const Station *st) { - for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) { + for (CargoType cargo : EnumRange(NUM_CARGO)) { if (this->cached_destinations.Retrieve(cargo) == nullptr) { this->RecalcDestinations(cargo); diff --git a/src/strings.cpp b/src/strings.cpp index 393734c424..4561aa0d71 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -2070,7 +2070,7 @@ bool ReadLanguagePack(const LanguageMetadata *lang) std::array tab_start, tab_num; uint count = 0; - for (uint i = 0; i < TEXT_TAB_END; i++) { + for (StringTab i : EnumRange(TEXT_TAB_END)) { uint16_t num = FROM_LE16(lang_pack->offsets[i]); if (num > TAB_SIZE) return false; diff --git a/src/survey.cpp b/src/survey.cpp index 2d135f5630..427dd2b6a3 100644 --- a/src/survey.cpp +++ b/src/survey.cpp @@ -325,7 +325,7 @@ void SurveyCompanies(nlohmann::json &survey) company["script"] = fmt::format("{}.{}", c->ai_info->GetName(), c->ai_info->GetVersion()); } - for (VehicleType type = VehicleType::Begin; type < VehicleType::CompanyEnd; type++) { + for (VehicleType type : EnumRange(VehicleType::CompanyEnd)) { uint amount = c->group_all[type].num_vehicle; company["vehicles"][_vehicle_type_to_string[type]] = amount; } diff --git a/src/terraform_cmd.cpp b/src/terraform_cmd.cpp index 524691f439..19f9c0427c 100644 --- a/src/terraform_cmd.cpp +++ b/src/terraform_cmd.cpp @@ -135,7 +135,7 @@ static std::tuple TerraformTileHeight(TerraformerState * total_cost.AddCost(_price[Price::Terraform]); /* Recurse to neighboured corners if height difference is larger than 1 */ - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { TileIndex neighbour_tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir)); /* Not using IsValidTile as we want to also change TileType::Void tiles, which IsValidTile excludes. */ diff --git a/src/tests/mock_fontcache.h b/src/tests/mock_fontcache.h index 1ccd159834..8285fbb948 100644 --- a/src/tests/mock_fontcache.h +++ b/src/tests/mock_fontcache.h @@ -31,7 +31,7 @@ public: static void InitializeFontCaches() { - for (FontSize fs = FontSize::Begin; fs != FontSize::End; fs++) { + for (FontSize fs : EnumRange(FontSize::End)) { if (FontCache::Get(fs) != nullptr) continue; FontCache::Register(std::make_unique(fs)); } diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 3de8130904..683e53b420 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -1189,7 +1189,7 @@ static bool GrowTownWithExtraHouse(Town *t, TileIndex tile, TownExpandModes mode uint counter = 0; // counts the house neighbour tiles /* Check the tiles E,N,W and S of the current tile for houses */ - for (DiagDirection dir = DiagDirection::Begin; dir < DiagDirection::End; dir++) { + for (DiagDirection dir : EnumRange(DiagDirection::End)) { /* Count both void and house tiles for checking whether there * are enough houses in the area. This to make it likely that * houses get build up to the edge of the map. */ @@ -2605,7 +2605,7 @@ static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope) /* we need to check this tile too because we can be at different tile now */ if (!CheckBuildHouseSameZ(tile, z, noslope)) return false; - for (DiagDirection d = DiagDirection::SE; d < DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::SE, DiagDirection::End)) { tile += TileOffsByDiagDir(d); if (!CheckBuildHouseSameZ(tile, z, noslope)) return false; } @@ -3712,7 +3712,7 @@ TownActions GetMaskOfTownActions(CompanyID cid, const Town *t) /* Check the action bits for validity and * if they are valid add them */ - for (TownAction cur = {}; cur != TownAction::End; ++cur) { + for (TownAction cur : EnumRange(TownAction::End)) { /* Is the company prohibited from bribing ? */ if (cur == TownAction::Bribe) { @@ -3915,7 +3915,7 @@ static void UpdateTownGrowth(Town *t) if (t->fund_buildings_months == 0) { /* Check if all goals are reached for this town to grow (given we are not funding it) */ - for (TownAcceptanceEffect i = TownAcceptanceEffect::Begin; i < TownAcceptanceEffect::End; i++) { + for (TownAcceptanceEffect i : EnumRange(TownAcceptanceEffect::End)) { switch (t->goal[i]) { case TOWN_GROWTH_WINTER: if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return; diff --git a/src/town_gui.cpp b/src/town_gui.cpp index 452fd1ae83..710ce8fcb9 100644 --- a/src/town_gui.cpp +++ b/src/town_gui.cpp @@ -208,11 +208,8 @@ public: DrawString(r, STR_LOCAL_AUTHORITY_ACTIONS_TITLE); r.top += GetCharacterHeight(FontSize::Normal); - /* Draw list of actions */ - for (TownAction i = {}; i != TownAction::End; ++i) { - /* Don't show actions if disabled in settings. */ - if (!this->enabled_actions.Test(i)) continue; - + /* Draw list of enabled actions */ + for (TownAction i : this->enabled_actions) { /* Set colour of action based on ability to execute and if selected. */ ExtendedTextColour action_colour{TextColour::Grey, ExtendedTextColourFlag::NoShade}; if (this->available_actions.Test(i)) action_colour = TextColour::Orange; @@ -252,7 +249,7 @@ public: case WID_TA_ACTION_INFO: { assert(size.width > padding.width && size.height > padding.height); Dimension d = {0, 0}; - for (TownAction i = {}; i != TownAction::End; ++i) { + for (TownAction i : EnumRange(TownAction::End)) { Money price = _price[Price::TownAction] * GetTownActionCost(i) >> 8; d = maxdim(d, GetStringMultiLineBoundingBox(GetString(this->action_tooltips[to_underlying(i)], price), size)); } @@ -265,7 +262,7 @@ public: case WID_TA_COMMAND_LIST: size.height = (to_underlying(TownAction::End) + 1) * GetCharacterHeight(FontSize::Normal) + padding.height; size.width = GetStringBoundingBox(STR_LOCAL_AUTHORITY_ACTIONS_TITLE).width; - for (TownAction i = {}; i != TownAction::End; ++i) { + for (TownAction i : EnumRange(TownAction::End)) { size.width = std::max(size.width, GetStringBoundingBox(STR_LOCAL_AUTHORITY_ACTION_SMALL_ADVERTISING_CAMPAIGN + to_underlying(i)).width + padding.width); } size.width += padding.width; @@ -414,7 +411,7 @@ public: } bool first = true; - for (TownAcceptanceEffect i = TownAcceptanceEffect::Begin; i < TownAcceptanceEffect::End; i++) { + for (TownAcceptanceEffect i : EnumRange(TownAcceptanceEffect::End)) { if (this->town->goal[i] == 0) continue; if (this->town->goal[i] == TOWN_GROWTH_WINTER && (TileHeight(this->town->xy) < LowestSnowLine() || this->town->cache.population <= 90)) continue; if (this->town->goal[i] == TOWN_GROWTH_DESERT && (GetTropicZone(this->town->xy) != TropicZone::Desert || this->town->cache.population <= 60)) continue; @@ -538,7 +535,7 @@ public: uint aimed_height = static_cast(1 + CargoSpec::town_production_cargoes[TownProductionEffect::Passengers].size() + CargoSpec::town_production_cargoes[TownProductionEffect::Mail].size()) * GetCharacterHeight(FontSize::Normal); bool first = true; - for (TownAcceptanceEffect i = TownAcceptanceEffect::Begin; i < TownAcceptanceEffect::End; i++) { + for (TownAcceptanceEffect i : EnumRange(TownAcceptanceEffect::End)) { if (this->town->goal[i] == 0) continue; if (this->town->goal[i] == TOWN_GROWTH_WINTER && (TileHeight(this->town->xy) < LowestSnowLine() || this->town->cache.population <= 90)) continue; if (this->town->goal[i] == TOWN_GROWTH_DESERT && (GetTropicZone(this->town->xy) != TropicZone::Desert || this->town->cache.population <= 60)) continue; diff --git a/src/viewport.cpp b/src/viewport.cpp index 9835a8cc7f..a855d8f44d 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -1561,7 +1561,7 @@ void ViewportSign::MarkDirty(ZoomLevel maxzoom) const const uint half_width = std::max(this->width_normal, this->width_small) / 2 + 1; const uint height = WidgetDimensions::scaled.fullbevel.top + std::max(GetCharacterHeight(FontSize::Normal), GetCharacterHeight(FontSize::Small)) + WidgetDimensions::scaled.fullbevel.bottom + 1; - for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) { + for (ZoomLevel zoom : EnumRange(ZoomLevel::End)) { zoomlevels[zoom].left = this->center - ScaleByZoom(half_width, zoom); zoomlevels[zoom].top = this->top - ScaleByZoom(1, zoom); zoomlevels[zoom].right = this->center + ScaleByZoom(half_width, zoom); diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index 52ed8a95d3..ddad17f7f1 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -86,7 +86,7 @@ static inline void MarkTileDirtyIfCanalOrRiver(TileIndex tile) */ static void MarkCanalsAndRiversAroundDirty(TileIndex tile) { - for (Direction dir = Direction::Begin; dir < Direction::End; dir++) { + for (Direction dir : EnumRange(Direction::End)) { MarkTileDirtyIfCanalOrRiver(tile + TileOffsByDir(dir)); } } @@ -97,7 +97,7 @@ static void MarkCanalsAndRiversAroundDirty(TileIndex tile) */ void ClearNeighbourNonFloodingStates(TileIndex tile) { - for (Direction dir = Direction::Begin; dir != Direction::End; dir++) { + for (Direction dir : EnumRange(Direction::End)) { TileIndex dest = tile + TileOffsByDir(dir); if (IsValidTile(dest) && IsTileType(dest, TileType::Water)) SetNonFloodingWaterTile(dest, false); } @@ -200,7 +200,7 @@ bool IsPossibleDockingTile(Tile t) */ void CheckForDockingTile(TileIndex t) { - for (DiagDirection d = DiagDirection::Begin; d != DiagDirection::End; d++) { + for (DiagDirection d : EnumRange(DiagDirection::End)) { TileIndex tile = t + TileOffsByDiagDir(d); if (!IsValidTile(tile)) continue; @@ -1299,7 +1299,7 @@ void TileLoop_Water(TileIndex tile) switch (GetFloodingBehaviour(tile)) { case FloodingBehaviour::Active: { bool continue_flooding = false; - for (Direction dir = Direction::Begin; dir < Direction::End; dir++) { + for (Direction dir : EnumRange(Direction::End)) { TileIndex dest = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDir(dir)); /* Contrary to drying up, flooding does not consider TileType::Void tiles. */ if (!IsValidTile(dest)) continue;