From ab8177ea77f9467ba41c51df1873ce1f6f31b539 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Mon, 10 Feb 2025 18:08:53 +0100 Subject: [PATCH] Codechange: strongly type CompanyID --- src/ai/ai.hpp | 2 +- src/ai/ai_gui.cpp | 12 ++++----- src/cargomonitor.h | 4 +-- src/cheat_gui.cpp | 4 +-- src/command.cpp | 2 +- src/company_base.h | 8 +++--- src/company_cmd.cpp | 2 +- src/company_type.h | 43 +++++++++++++----------------- src/console_cmds.cpp | 8 +++--- src/core/random_func.cpp | 2 +- src/crashlog.cpp | 4 +-- src/graph_gui.cpp | 6 ++--- src/main_gui.cpp | 4 +-- src/network/network_gui.cpp | 2 +- src/network/network_server.cpp | 10 +++---- src/newgrf_commons.cpp | 2 +- src/newgrf_industries.cpp | 4 +-- src/newgrf_object.cpp | 4 +-- src/road_cmd.cpp | 4 +-- src/road_map.h | 8 +++--- src/saveload/afterload.cpp | 10 +++---- src/saveload/ai_sl.cpp | 2 +- src/screenshot_png.cpp | 4 +-- src/script/api/script_company.cpp | 2 +- src/script/api/script_company.hpp | 2 +- src/script/api/script_goal.cpp | 2 +- src/script/api/script_log.cpp | 2 +- src/script/api/script_object.hpp | 2 +- src/script/api/script_viewport.cpp | 2 +- src/script/script_gui.cpp | 6 ++--- src/smallmap_gui.cpp | 2 +- src/station_cmd.cpp | 6 ++--- src/survey.cpp | 2 +- src/tile_map.h | 2 +- src/toolbar_gui.cpp | 4 +-- src/vehicle_gui.cpp | 2 +- src/vehiclelist.cpp | 2 +- 37 files changed, 92 insertions(+), 97 deletions(-) diff --git a/src/ai/ai.hpp b/src/ai/ai.hpp index 5750ae6c53..d9bf811f9d 100644 --- a/src/ai/ai.hpp +++ b/src/ai/ai.hpp @@ -103,7 +103,7 @@ public: /** * Broadcast a new event to all active AIs. */ - static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company = MAX_COMPANIES); + static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company = CompanyID::Invalid()); /** * Save data from an AI to a savegame. diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp index 5c9d73713d..8c4143bf93 100644 --- a/src/ai/ai_gui.cpp +++ b/src/ai/ai_gui.cpp @@ -169,7 +169,7 @@ struct AIConfigWindow : public Window { for (const Company *c : Company::Iterate()) { if (c->is_ai) max_slot--; } - for (CompanyID cid = COMPANY_FIRST; cid < (CompanyID)max_slot && cid < MAX_COMPANIES; cid++) { + for (CompanyID cid = COMPANY_FIRST; cid < max_slot && cid < MAX_COMPANIES; ++cid) { if (Company::IsValidID(cid)) max_slot++; } } else { @@ -219,7 +219,7 @@ struct AIConfigWindow : public Window { if (widget == WID_AIC_DECREASE_NUMBER) { new_value = std::max(0, GetGameSettings().difficulty.max_no_competitors - 1); } else { - new_value = std::min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1); + new_value = std::min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1); } IConsoleSetSetting("difficulty.max_no_competitors", new_value); this->InvalidateData(); @@ -249,8 +249,8 @@ struct AIConfigWindow : public Window { case WID_AIC_MOVE_UP: if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot - 1))) { Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot - 1]); - this->selected_slot--; - this->vscroll->ScrollTowards(this->selected_slot); + this->selected_slot = CompanyID(this->selected_slot - 1); + this->vscroll->ScrollTowards(this->selected_slot.base()); this->InvalidateData(); } break; @@ -258,8 +258,8 @@ struct AIConfigWindow : public Window { case WID_AIC_MOVE_DOWN: if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot + 1))) { Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot + 1]); - this->selected_slot++; - this->vscroll->ScrollTowards(this->selected_slot); + ++this->selected_slot; + this->vscroll->ScrollTowards(this->selected_slot.base()); this->InvalidateData(); } break; diff --git a/src/cargomonitor.h b/src/cargomonitor.h index 3c95b84e9d..cc3d687f35 100644 --- a/src/cargomonitor.h +++ b/src/cargomonitor.h @@ -64,7 +64,7 @@ inline CargoMonitorID EncodeCargoIndustryMonitor(CompanyID company, CargoType ct SB(ret, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH, ind); SetBit(ret, CCB_IS_INDUSTRY_BIT); SB(ret, CCB_CARGO_TYPE_START, CCB_CARGO_TYPE_LENGTH, ctype); - SB(ret, CCB_COMPANY_START, CCB_COMPANY_LENGTH, company); + SB(ret, CCB_COMPANY_START, CCB_COMPANY_LENGTH, company.base()); return ret; } @@ -83,7 +83,7 @@ inline CargoMonitorID EncodeCargoTownMonitor(CompanyID company, CargoType ctype, uint32_t ret = 0; SB(ret, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH, town); SB(ret, CCB_CARGO_TYPE_START, CCB_CARGO_TYPE_LENGTH, ctype); - SB(ret, CCB_COMPANY_START, CCB_COMPANY_LENGTH, company); + SB(ret, CCB_COMPANY_START, CCB_COMPANY_LENGTH, company.base()); return ret; } diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 3e37322e31..ea004c71c1 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -75,12 +75,12 @@ static int32_t ClickChangeCompanyCheat(int32_t new_value, int32_t change_directi while ((uint)new_value < Company::GetPoolSize()) { if (Company::IsValidID((CompanyID)new_value)) { SetLocalCompany((CompanyID)new_value); - return _local_company; + return _local_company.base(); } new_value += change_direction; } - return _local_company; + return _local_company.base(); } /** diff --git a/src/command.cpp b/src/command.cpp index eccf4b2deb..34c917e91f 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -260,7 +260,7 @@ void CommandHelperBase::InternalPostResult(const CommandCost &res, TileIndex til /** Helper to make a desync log for a command. */ void CommandHelperBase::LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed) { - Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {} ({})", failed ? "cmdf" : "cmd", (uint32_t)TimerGameEconomy::date.base(), TimerGameEconomy::date_fract, (int)_current_company, cmd, err_message, FormatArrayAsHex(args), GetCommandName(cmd)); + Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {} ({})", failed ? "cmdf" : "cmd", (uint32_t)TimerGameEconomy::date.base(), TimerGameEconomy::date_fract, _current_company, cmd, err_message, FormatArrayAsHex(args), GetCommandName(cmd)); } /** diff --git a/src/company_base.h b/src/company_base.h index aa06ec88c4..cc0a33f423 100644 --- a/src/company_base.h +++ b/src/company_base.h @@ -62,7 +62,7 @@ private: std::vector used_bitmap; }; -typedef Pool CompanyPool; +typedef Pool CompanyPool; extern CompanyPool _company_pool; /** Statically loadable part of Company pool item */ @@ -156,7 +156,7 @@ struct Company : CompanyProperties, CompanyPool::PoolItem<&_company_pool> { * @param index Index in the pool. * @return \c true if it is a valid, computer controlled company, else \c false. */ - static inline bool IsValidAiID(size_t index) + static inline bool IsValidAiID(auto index) { const Company *c = Company::GetIfValid(index); return c != nullptr && c->is_ai; @@ -168,7 +168,7 @@ struct Company : CompanyProperties, CompanyPool::PoolItem<&_company_pool> { * @return \c true if it is a valid, human controlled company, else \c false. * @note If you know that \a index refers to a valid company, you can use #IsHumanID() instead. */ - static inline bool IsValidHumanID(size_t index) + static inline bool IsValidHumanID(auto index) { const Company *c = Company::GetIfValid(index); return c != nullptr && !c->is_ai; @@ -181,7 +181,7 @@ struct Company : CompanyProperties, CompanyPool::PoolItem<&_company_pool> { * @pre \a index must be a valid CompanyID. * @note If you don't know whether \a index refers to a valid company, you should use #IsValidHumanID() instead. */ - static inline bool IsHumanID(size_t index) + static inline bool IsHumanID(auto index) { return !Company::Get(index)->is_ai; } diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index ba48fec40e..176ca755db 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -586,7 +586,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY) c = new Company(STR_SV_UNNAMED, is_ai); } else { if (Company::IsValidID(company)) return nullptr; - c = new (company) Company(STR_SV_UNNAMED, is_ai); + c = new (company.base()) Company(STR_SV_UNNAMED, is_ai); } c->colour = colour; diff --git a/src/company_type.h b/src/company_type.h index e36f4934de..485bdc051b 100644 --- a/src/company_type.h +++ b/src/company_type.h @@ -11,32 +11,27 @@ #define COMPANY_TYPE_H #include "core/enum_type.hpp" +#include "core/pool_type.hpp" -/** - * Enum for all companies/owners. - */ -enum Owner : uint8_t { - /* All companies below MAX_COMPANIES are playable - * companies, above, they are special, computer controlled 'companies' */ - OWNER_BEGIN = 0x00, ///< First owner - COMPANY_FIRST = 0x00, ///< First company, same as owner - MAX_COMPANIES = 0x0F, ///< Maximum number of companies - OWNER_TOWN = 0x0F, ///< A town owns the tile, or a town is expanding - OWNER_NONE = 0x10, ///< The tile has no ownership - OWNER_WATER = 0x11, ///< The tile/execution is done by "water" - OWNER_DEITY = 0x12, ///< The object is owned by a superuser / goal script - OWNER_END, ///< Last + 1 owner - INVALID_OWNER = 0xFF, ///< An invalid owner - INVALID_COMPANY = 0xFF, ///< An invalid company +using CompanyID = PoolID; +static constexpr CompanyID COMPANY_FIRST = CompanyID::Begin(); +static constexpr CompanyID INVALID_COMPANY = CompanyID::Invalid(); ///< An invalid company - /* 'Fake' companies used for networks */ - COMPANY_INACTIVE_CLIENT = 253, ///< The client is joining - COMPANY_NEW_COMPANY = 254, ///< The client wants a new company - COMPANY_SPECTATOR = 255, ///< The client is spectating -}; -DECLARE_INCREMENT_DECREMENT_OPERATORS(Owner) -DECLARE_ENUM_AS_ADDABLE(Owner) +/* 'Fake' companies used for networks */ +static constexpr CompanyID COMPANY_INACTIVE_CLIENT{253}; ///< The client is joining +static constexpr CompanyID COMPANY_NEW_COMPANY{254}; ///< The client wants a new company +static constexpr CompanyID COMPANY_SPECTATOR{255}; ///< The client is spectating +using Owner = CompanyID; +static constexpr Owner OWNER_BEGIN = Owner::Begin(); ///< First owner +static constexpr Owner OWNER_TOWN{0x0F}; ///< A town owns the tile, or a town is expanding +static constexpr Owner OWNER_NONE{0x10}; ///< The tile has no ownership +static constexpr Owner OWNER_WATER{0x11}; ///< The tile/execution is done by "water" +static constexpr Owner OWNER_DEITY{0x12}; ///< The object is owned by a superuser / goal script +static constexpr Owner OWNER_END{0x13}; ///< Last + 1 owner +static constexpr Owner INVALID_OWNER = Owner::Invalid(); ///< An invalid owner + +static const uint8_t MAX_COMPANIES = CompanyID::End().base(); static const uint MAX_LENGTH_PRESIDENT_NAME_CHARS = 32; ///< The maximum length of a president name in characters including '\0' static const uint MAX_LENGTH_COMPANY_NAME_CHARS = 32; ///< The maximum length of a company name in characters including '\0' @@ -50,7 +45,7 @@ typedef Owner CompanyID; class CompanyMask : public BaseBitSet { public: constexpr CompanyMask() : BaseBitSet() {} - static constexpr size_t DecayValueType(CompanyID value) { return to_underlying(value); } + static constexpr size_t DecayValueType(CompanyID value) { return value.base(); } constexpr auto operator <=>(const CompanyMask &) const noexcept = default; }; diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 3104a611ac..bac12d079c 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -1082,9 +1082,9 @@ DEF_CONSOLE_CMD(ConNetworkReconnect) } CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR; - switch (playas) { + switch (playas.base()) { case 0: playas = COMPANY_NEW_COMPANY; break; - case COMPANY_SPECTATOR: /* nothing to do */ break; + case COMPANY_SPECTATOR.base(): /* nothing to do */ break; default: /* From a user pov 0 is a new company, internally it's different and all * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */ @@ -1922,10 +1922,10 @@ DEF_CONSOLE_CMD(ConSayCompany) } if (!_network_server) { - NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]); + NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2]); } else { bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID); - NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin); + NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2], CLIENT_ID_SERVER, from_admin); } return true; diff --git a/src/core/random_func.cpp b/src/core/random_func.cpp index 355eeff616..6893ff65c7 100644 --- a/src/core/random_func.cpp +++ b/src/core/random_func.cpp @@ -73,7 +73,7 @@ void SetRandomSeed(uint32_t seed) uint32_t Random(const std::source_location location) { if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE))) { - Debug(random, 0, "{:08x}; {:02x}; {:04x}; {:02x}; {}:{}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _frame_counter, (uint8_t)_current_company, location.file_name(), location.line()); + Debug(random, 0, "{:08x}; {:02x}; {:04x}; {:02x}; {}:{}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _frame_counter, _current_company, location.file_name(), location.line()); } return _random.Next(); diff --git a/src/crashlog.cpp b/src/crashlog.cpp index 04129d7c3b..7e57ef2cf0 100644 --- a/src/crashlog.cpp +++ b/src/crashlog.cpp @@ -134,8 +134,8 @@ void CrashLog::FillCrashLog() { auto &game = this->survey["game"]; - game["local_company"] = _local_company; - game["current_company"] = _current_company; + game["local_company"] = _local_company.base(); + game["current_company"] = _current_company.base(); if (!this->TryExecute("timers", [&game]() { SurveyTimers(game["timers"]); return true; })) { game["libraries"] = "crashed while gathering information"; diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp index 04ed904565..bade233ac7 100644 --- a/src/graph_gui.cpp +++ b/src/graph_gui.cpp @@ -57,7 +57,7 @@ struct GraphLegendWindow : Window { for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { if (!_legend_excluded_companies.Test(c)) this->LowerWidget(WID_GL_FIRST_COMPANY + c); - this->OnInvalidateData(c); + this->OnInvalidateData(c.base()); } } @@ -710,7 +710,7 @@ public: DataSet &dataset = this->data.emplace_back(); dataset.colour = GetColourGradient(c->colour, SHADE_LIGHTER); - dataset.exclude_bit = k; + dataset.exclude_bit = k.base(); for (int j = this->num_on_x_axis, i = 0; --j >= 0;) { if (j >= c->num_valid_stat_ent) { @@ -1269,7 +1269,7 @@ struct PerformanceRatingDetailWindow : Window { this->UpdateCompanyStats(); this->InitNested(window_number); - this->OnInvalidateData(INVALID_COMPANY); + this->OnInvalidateData(INVALID_COMPANY.base()); } void UpdateCompanyStats() diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 237ab899a1..ff1893e1dd 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -385,7 +385,7 @@ struct MainWindow : Window const NetworkClientInfo *cio = NetworkClientInfo::GetByClientID(_network_own_client_id); if (cio == nullptr) break; - ShowNetworkChatQueryWindow(NetworkClientPreferTeamChat(cio) ? DESTTYPE_TEAM : DESTTYPE_BROADCAST, cio->client_playas); + ShowNetworkChatQueryWindow(NetworkClientPreferTeamChat(cio) ? DESTTYPE_TEAM : DESTTYPE_BROADCAST, cio->client_playas.base()); } break; @@ -398,7 +398,7 @@ struct MainWindow : Window const NetworkClientInfo *cio = NetworkClientInfo::GetByClientID(_network_own_client_id); if (cio == nullptr) break; - ShowNetworkChatQueryWindow(DESTTYPE_TEAM, cio->client_playas); + ShowNetworkChatQueryWindow(DESTTYPE_TEAM, cio->client_playas.base()); } break; diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 9d8cc258bb..ff38342106 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -1436,7 +1436,7 @@ private: */ static void OnClickCompanyChat([[maybe_unused]] NetworkClientListWindow *w, [[maybe_unused]] Point pt, CompanyID company_id) { - ShowNetworkChatQueryWindow(DESTTYPE_TEAM, company_id); + ShowNetworkChatQueryWindow(DESTTYPE_TEAM, company_id.base()); } /** diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index adde5230fd..fc1e36ee8b 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -879,13 +879,13 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; /* join another company does not affect these values */ - switch (playas) { - case COMPANY_NEW_COMPANY: // New company + switch (playas.base()) { + case COMPANY_NEW_COMPANY.base(): // New company if (Company::GetNumItems() >= _settings_client.network.max_companies) { return this->SendError(NETWORK_ERROR_FULL); } break; - case COMPANY_SPECTATOR: // Spectator + case COMPANY_SPECTATOR.base(): // Spectator break; default: // Join another company (companies 1..MAX_COMPANIES (index 0..(MAX_COMPANIES-1))) if (!Company::IsValidHumanID(playas)) { @@ -918,7 +918,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet ci->client_name = client_name; ci->client_playas = playas; ci->public_key = this->peer_public_key; - Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)ci->client_playas, ci->index); + Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, ci->index); /* Make sure companies to which people try to join are not autocleaned */ Company *c = Company::GetIfValid(playas); @@ -1531,7 +1531,7 @@ void NetworkUpdateClientInfo(ClientID client_id) if (ci == nullptr) return; - Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)ci->client_playas, client_id); + Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, client_id); for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { diff --git a/src/newgrf_commons.cpp b/src/newgrf_commons.cpp index e0018b7243..7bd895c39d 100644 --- a/src/newgrf_commons.cpp +++ b/src/newgrf_commons.cpp @@ -457,7 +457,7 @@ uint32_t GetNearbyTileInformation(TileIndex tile, bool grf_version8) uint32_t GetCompanyInfo(CompanyID owner, const Livery *l) { if (l == nullptr && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT]; - return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != nullptr ? (l->colour1 << 24) | (l->colour2 << 28) : 0); + return owner.base() | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != nullptr ? (l->colour1 << 24) | (l->colour2 << 28) : 0); } /** diff --git a/src/newgrf_industries.cpp b/src/newgrf_industries.cpp index 3bcf48eda7..ece78af90e 100644 --- a/src/newgrf_industries.cpp +++ b/src/newgrf_industries.cpp @@ -248,7 +248,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t param_setID, uint8_ colours = l->colour1 + l->colour2 * 16; } - return this->industry->founder | (is_ai ? 0x10000 : 0) | (colours << 24); + return this->industry->founder.base() | (is_ai ? 0x10000 : 0) | (colours << 24); } case 0x46: return this->industry->construction_date.base(); // Date when built - long format - (in days) @@ -401,7 +401,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t param_setID, uint8_ case 0xA5: return GB(this->industry->GetProduced(1).history[LAST_MONTH].transported, 8, 8); case 0xA6: return indspec->grf_prop.local_id; - case 0xA7: return this->industry->founder; + case 0xA7: return this->industry->founder.base(); case 0xA8: return this->industry->random_colour; case 0xA9: return ClampTo(this->industry->last_prod_year - EconomyTime::ORIGINAL_BASE_YEAR); case 0xAA: return this->industry->counter; diff --git a/src/newgrf_object.cpp b/src/newgrf_object.cpp index 5ba5f07d3d..5b42eda793 100644 --- a/src/newgrf_object.cpp +++ b/src/newgrf_object.cpp @@ -281,7 +281,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t local_id, uint32_t case 0x42: return TimerGameCalendar::date.base(); /* Object founder information */ - case 0x44: return _current_company; + case 0x44: return _current_company.base(); /* Object view */ case 0x48: return this->view; @@ -322,7 +322,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t local_id, uint32_t case 0x43: return GetAnimationFrame(this->tile); /* Object founder information */ - case 0x44: return GetTileOwner(this->tile); + case 0x44: return GetTileOwner(this->tile).base(); /* Get town zone and Manhattan distance of closest town */ case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | ClampTo(DistanceManhattan(this->tile, t->xy)); diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 72169bf6cc..9db92e4a27 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -2416,8 +2416,8 @@ static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, R Company *c; - switch (owner) { - case OWNER_NONE: + switch (owner.base()) { + case OWNER_NONE.base(): SetRoadOwner(tile, GetRoadTramType(to_type), (Owner)_current_company); UpdateCompanyRoadInfrastructure(to_type, _current_company, num_pieces); break; diff --git a/src/road_map.h b/src/road_map.h index a99e94be1a..3010378de4 100644 --- a/src/road_map.h +++ b/src/road_map.h @@ -251,9 +251,9 @@ inline Owner GetRoadOwner(Tile t, RoadTramType rtt) inline void SetRoadOwner(Tile t, RoadTramType rtt, Owner o) { if (rtt == RTT_ROAD) { - SB(IsNormalRoadTile(t) ? t.m1() : t.m7(), 0, 5, o); + SB(IsNormalRoadTile(t) ? t.m1() : t.m7(), 0, 5, o.base()); } else { - SB(t.m3(), 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); + SB(t.m3(), 4, 4, (o == OWNER_NONE ? OWNER_TOWN : o).base()); } } @@ -666,7 +666,7 @@ inline void MakeRoadCrossing(Tile t, Owner road, Owner tram, Owner rail, Axis ro t.m4() = INVALID_ROADTYPE; t.m5() = ROAD_TILE_CROSSING << 6 | roaddir; SB(t.m6(), 2, 4, 0); - t.m7() = road; + t.m7() = road.base(); t.m8() = INVALID_ROADTYPE << 6 | rat; SetRoadTypes(t, road_rt, tram_rt); SetRoadOwner(t, RTT_TRAM, tram); @@ -700,7 +700,7 @@ inline void MakeRoadDepot(Tile tile, Owner owner, DepotID depot_id, DiagDirectio tile.m4() = INVALID_ROADTYPE; tile.m5() = ROAD_TILE_DEPOT << 6 | dir; SB(tile.m6(), 2, 4, 0); - tile.m7() = owner; + tile.m7() = owner.base(); tile.m8() = INVALID_ROADTYPE << 6; SetRoadType(tile, GetRoadTramType(rt), rt); SetRoadOwner(tile, RTT_TRAM, owner); diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 60d39b2ea0..b3bced4467 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -162,7 +162,7 @@ static void ConvertTownOwner() switch (GetTileType(tile)) { case MP_ROAD: if (GB(tile.m5(), 4, 2) == ROAD_TILE_CROSSING && HasBit(tile.m3(), 7)) { - tile.m3() = OWNER_TOWN; + tile.m3() = OWNER_TOWN.base(); } [[fallthrough]]; @@ -1160,7 +1160,7 @@ bool AfterLoadGame() if (!IsStationRoadStop(t)) break; if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3)); - SB(t.m7(), 0, 5, HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t)); + SB(t.m7(), 0, 5, (HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t)).base()); SB(t.m3(), 4, 4, t.m1()); t.m4() = 0; break; @@ -1171,8 +1171,8 @@ bool AfterLoadGame() if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3)); Owner o = GetTileOwner(t); - SB(t.m7(), 0, 5, o); // road owner - SB(t.m3(), 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner + SB(t.m7(), 0, 5, o.base()); // road owner + SB(t.m3(), 4, 4, (o == OWNER_NONE ? OWNER_TOWN : o).base()); // tram owner } SB(t.m6(), 2, 4, GB(t.m2(), 4, 4)); // bridge type SB(t.m7(), 5, 1, GB(t.m4(), 7, 1)); // snow/desert @@ -1731,7 +1731,7 @@ bool AfterLoadGame() if (IsSavegameVersionBefore(SLV_83)) { for (auto t : Map::Iterate()) { if (IsShipDepotTile(t)) { - t.m4() = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE; + t.m4() = (TileHeight(t) == 0 ? OWNER_WATER : OWNER_NONE).base(); } } } diff --git a/src/saveload/ai_sl.cpp b/src/saveload/ai_sl.cpp index 223200e7d1..6e8887ed66 100644 --- a/src/saveload/ai_sl.cpp +++ b/src/saveload/ai_sl.cpp @@ -162,7 +162,7 @@ struct AIPLChunkHandler : ChunkHandler { for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; ++i) { SlSetArrayIndex(i); - SlAutolength(SaveReal_AIPL, i); + SlAutolength(SaveReal_AIPL, i.base()); } } }; diff --git a/src/screenshot_png.cpp b/src/screenshot_png.cpp index c90fa10b89..1abc0fb198 100644 --- a/src/screenshot_png.cpp +++ b/src/screenshot_png.cpp @@ -92,9 +92,9 @@ public: message += "\nCompanies:\n"; for (const Company *c : Company::Iterate()) { if (c->ai_info == nullptr) { - fmt::format_to(std::back_inserter(message), "{:2d}: Human\n", (int)c->index); + fmt::format_to(std::back_inserter(message), "{:2d}: Human\n", c->index); } else { - fmt::format_to(std::back_inserter(message), "{:2d}: {} (v{})\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion()); + fmt::format_to(std::back_inserter(message), "{:2d}: {} (v{})\n", c->index, c->ai_info->GetName(), c->ai_info->GetVersion()); } } text[1].key = const_cast("Description"); diff --git a/src/script/api/script_company.cpp b/src/script/api/script_company.cpp index ef177674fa..7ba6bab47b 100644 --- a/src/script/api/script_company.cpp +++ b/src/script/api/script_company.cpp @@ -40,7 +40,7 @@ /* static */ ScriptCompany::CompanyID ScriptCompany::ToScriptCompanyID(::CompanyID company) { if (company == ::INVALID_COMPANY) return ScriptCompany::COMPANY_INVALID; - return static_cast<::ScriptCompany::CompanyID>(company); + return static_cast<::ScriptCompany::CompanyID>(company.base()); } /* static */ ScriptCompany::CompanyID ScriptCompany::ResolveCompanyID(ScriptCompany::CompanyID company) diff --git a/src/script/api/script_company.hpp b/src/script/api/script_company.hpp index 8fa8a3353b..58e2f5242a 100644 --- a/src/script/api/script_company.hpp +++ b/src/script/api/script_company.hpp @@ -30,7 +30,7 @@ public: /** Different constants related to CompanyID. */ enum CompanyID { /* Note: these values represent part of the in-game Owner enum */ - COMPANY_FIRST = ::COMPANY_FIRST, ///< The first available company. + COMPANY_FIRST = ::COMPANY_FIRST.base(), ///< The first available company. COMPANY_LAST = ::MAX_COMPANIES, ///< The last available company. /* Custom added value, only valid for this API */ diff --git a/src/script/api/script_goal.cpp b/src/script/api/script_goal.cpp index 48f091f1e9..0393cd864c 100644 --- a/src/script/api/script_goal.cpp +++ b/src/script/api/script_goal.cpp @@ -136,7 +136,7 @@ /* static */ bool ScriptGoal::Question(SQInteger uniqueid, ScriptCompany::CompanyID company, Text *question, QuestionType type, SQInteger buttons) { EnforcePrecondition(false, company == ScriptCompany::COMPANY_INVALID || ScriptCompany::ResolveCompanyID(company) != ScriptCompany::COMPANY_INVALID); - return DoQuestion(uniqueid, ScriptCompany::FromScriptCompanyID(company), false, question, type, buttons); + return DoQuestion(uniqueid, ScriptCompany::FromScriptCompanyID(company).base(), false, question, type, buttons); } /* static */ bool ScriptGoal::QuestionClient(SQInteger uniqueid, ScriptClient::ClientID client, Text *question, QuestionType type, SQInteger buttons) diff --git a/src/script/api/script_log.cpp b/src/script/api/script_log.cpp index bb6fb0060f..f40d907b93 100644 --- a/src/script/api/script_log.cpp +++ b/src/script/api/script_log.cpp @@ -57,6 +57,6 @@ } /* Also still print to debug window */ - Debug(script, level, "[{}] [{}] {}", (uint)ScriptObject::GetRootCompany(), logc, line.text); + Debug(script, level, "[{}] [{}] {}", ScriptObject::GetRootCompany(), logc, line.text); InvalidateWindowClassesData(WC_SCRIPT_DEBUG, ScriptObject::GetRootCompany()); } diff --git a/src/script/api/script_object.hpp b/src/script/api/script_object.hpp index 796aed9459..57af7178e5 100644 --- a/src/script/api/script_object.hpp +++ b/src/script/api/script_object.hpp @@ -330,7 +330,7 @@ private: static std::tuple DoCommandPrep(); static bool DoCommandProcessResult(const CommandCost &res, Script_SuspendCallbackProc *callback, bool estimate_only, bool asynchronous); static CommandCallbackData *GetDoCommandCallback(); - using RandomizerArray = ReferenceThroughBaseContainer>; + using RandomizerArray = ReferenceThroughBaseContainer>; static RandomizerArray random_states; ///< Random states for each of the scripts (game script uses OWNER_DEITY) }; diff --git a/src/script/api/script_viewport.cpp b/src/script/api/script_viewport.cpp index 9a899a1dd4..82b42d0b1c 100644 --- a/src/script/api/script_viewport.cpp +++ b/src/script/api/script_viewport.cpp @@ -42,7 +42,7 @@ company = ScriptCompany::ResolveCompanyID(company); EnforcePrecondition(false, company != ScriptCompany::COMPANY_INVALID); - return ScriptObject::Command::Do(tile, VST_COMPANY, ScriptCompany::FromScriptCompanyID(company)); + return ScriptObject::Command::Do(tile, VST_COMPANY, ScriptCompany::FromScriptCompanyID(company).base()); } /* static */ bool ScriptViewport::ScrollClientTo(ScriptClient::ClientID client, TileIndex tile) diff --git a/src/script/script_gui.cpp b/src/script/script_gui.cpp index 3dc5daa069..40222441ce 100644 --- a/src/script/script_gui.cpp +++ b/src/script/script_gui.cpp @@ -742,9 +742,9 @@ struct ScriptDebugWindow : public Window { */ bool IsValidDebugCompany(CompanyID company) const { - switch (company) { - case INVALID_COMPANY: return false; - case OWNER_DEITY: return Game::GetInstance() != nullptr; + switch (company.base()) { + case INVALID_COMPANY.base(): return false; + case OWNER_DEITY.base(): return Game::GetInstance() != nullptr; default: return Company::IsValidAiID(company); } } diff --git a/src/smallmap_gui.cpp b/src/smallmap_gui.cpp index a0cf7b01da..d7d606abea 100644 --- a/src/smallmap_gui.cpp +++ b/src/smallmap_gui.cpp @@ -219,7 +219,7 @@ void BuildIndustriesLegend() void BuildLinkStatsLegend() { /* Clear the legend */ - memset(_legend_linkstats, 0, sizeof(_legend_linkstats)); + std::fill(std::begin(_legend_linkstats), std::end(_legend_linkstats), LegendAndColour{}); uint i = 0; for (; i < _sorted_cargo_specs.size(); ++i) { diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 1199f23ba0..01eff04757 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -4426,8 +4426,8 @@ uint MoveGoodsToStation(CargoType type, uint amount, Source source, const Statio return UpdateStationWaiting(first_station, type, amount, source); } - ReferenceThroughBaseContainer> company_best = {}; // best rating for each company, including OWNER_NONE - ReferenceThroughBaseContainer> company_sum = {}; // sum of ratings for each company + ReferenceThroughBaseContainer> company_best = {}; // best rating for each company, including OWNER_NONE + ReferenceThroughBaseContainer> company_sum = {}; // sum of ratings for each company uint best_rating = 0; uint best_sum = 0; // sum of best ratings for each company @@ -4448,7 +4448,7 @@ uint MoveGoodsToStation(CargoType type, uint amount, Source source, const Statio uint moving = 0; for (auto &p : used_stations) { - uint owner = p.first->owner; + Owner owner = p.first->owner; /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company * and by (station rating / sum of ratings in a company) to get the result for a single station. */ p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner]; diff --git a/src/survey.cpp b/src/survey.cpp index a4140dbdca..c282e56fa1 100644 --- a/src/survey.cpp +++ b/src/survey.cpp @@ -308,7 +308,7 @@ void SurveyFont(nlohmann::json &survey) void SurveyCompanies(nlohmann::json &survey) { for (const Company *c : Company::Iterate()) { - auto &company = survey[std::to_string(c->index)]; + auto &company = survey[std::to_string(c->index.base())]; if (c->ai_info == nullptr) { company["type"] = "human"; } else { diff --git a/src/tile_map.h b/src/tile_map.h index 6fbb3a53fa..5f900e8ddc 100644 --- a/src/tile_map.h +++ b/src/tile_map.h @@ -201,7 +201,7 @@ inline void SetTileOwner(Tile tile, Owner owner) assert(!IsTileType(tile, MP_HOUSE)); assert(!IsTileType(tile, MP_INDUSTRY)); - SB(tile.m1(), 0, 5, owner); + SB(tile.m1(), 0, 5, owner.base()); } /** diff --git a/src/toolbar_gui.cpp b/src/toolbar_gui.cpp index 3cd4a43196..5f1688fa5d 100644 --- a/src/toolbar_gui.cpp +++ b/src/toolbar_gui.cpp @@ -98,7 +98,7 @@ static CallBackFunction _last_started_action = CBF_NONE; ///< Last started user */ class DropDownListCompanyItem : public DropDownIcon, true>> { public: - DropDownListCompanyItem(CompanyID company, bool shaded) : DropDownIcon, true>>(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(company), NetworkCanJoinCompany(company) ? SPR_EMPTY : SPR_LOCK, PAL_NONE, STR_NULL, company, false, shaded) + DropDownListCompanyItem(CompanyID company, bool shaded) : DropDownIcon, true>>(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(company), NetworkCanJoinCompany(company) ? SPR_EMPTY : SPR_LOCK, PAL_NONE, STR_NULL, company.base(), false, shaded) { this->SetString(GetString(STR_COMPANY_NAME_COMPANY_NUM, company, company)); } @@ -178,7 +178,7 @@ static void PopupMainCompanyToolbMenu(Window *w, WidgetID widget, CompanyMask gr list.push_back(std::make_unique(c, grey.Test(c))); } - PopupMainToolbarMenu(w, widget, std::move(list), _local_company == COMPANY_SPECTATOR ? (widget == WID_TN_COMPANIES ? CTMN_CLIENT_LIST : CTMN_SPECTATOR) : (int)_local_company); + PopupMainToolbarMenu(w, widget, std::move(list), _local_company == COMPANY_SPECTATOR ? (widget == WID_TN_COMPANIES ? CTMN_CLIENT_LIST : CTMN_SPECTATOR) : _local_company.base()); } static ToolbarMode _toolbar_mode; diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 3b62bb6dd8..f6013056ab 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -2329,7 +2329,7 @@ void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type) if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) { ShowCompanyGroup(company, vehicle_type); } else { - ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company); + ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company.base()); } } diff --git a/src/vehiclelist.cpp b/src/vehiclelist.cpp index e24fd147da..1bfebabf54 100644 --- a/src/vehiclelist.cpp +++ b/src/vehiclelist.cpp @@ -22,7 +22,7 @@ */ WindowNumber VehicleListIdentifier::ToWindowNumber() const { - uint8_t c = this->company == OWNER_NONE ? 0xF : (uint8_t)this->company; + uint8_t c = this->company == OWNER_NONE ? 0xF : this->company.base(); assert(c < (1 << 4)); assert(this->vtype < (1 << 2)); assert(this->index < (1 << 20));