From 1bfbf09891387d910de86292bd627be7fc2f3775 Mon Sep 17 00:00:00 2001 From: Martin Michelsen Date: Sun, 28 Jul 2024 11:54:41 -0700 Subject: [PATCH] use phosg namespace --- src/AFSArchive.cc | 18 +- src/AFSArchive.hh | 6 +- src/Account.cc | 96 ++--- src/Account.hh | 24 +- src/AddressTranslator.cc | 26 +- src/BMLArchive.cc | 31 +- src/BMLArchive.hh | 4 +- src/BattleParamsIndex.cc | 2 +- src/CatSession.cc | 15 +- src/CatSession.hh | 4 +- src/Channel.cc | 38 +- src/Channel.hh | 12 +- src/ChatCommands.cc | 96 ++--- src/ChoiceSearch.hh | 16 +- src/Client.cc | 106 ++--- src/Client.hh | 6 +- src/CommandFormats.hh | 48 +-- src/CommonItemSet.cc | 88 ++-- src/CommonItemSet.hh | 64 ++- src/Compression.cc | 24 +- src/Compression.hh | 4 +- src/DCSerialNumbers.cc | 40 +- src/DNSServer.cc | 10 +- src/EnemyType.cc | 12 +- src/EnemyType.hh | 5 +- src/Episode3/BattleRecord.cc | 51 ++- src/Episode3/BattleRecord.hh | 6 +- src/Episode3/Card.cc | 18 +- src/Episode3/CardSpecial.cc | 41 +- src/Episode3/DataIndexes.cc | 400 +++++++++--------- src/Episode3/DataIndexes.hh | 59 +-- src/Episode3/PlayerState.cc | 8 +- src/Episode3/PlayerStateSubordinates.cc | 30 +- src/Episode3/PlayerStateSubordinates.hh | 2 +- src/Episode3/RulerServer.cc | 10 +- src/Episode3/RulerServer.hh | 2 +- src/Episode3/Server.cc | 48 +-- src/Episode3/Server.hh | 8 +- src/Episode3/Tournament.cc | 52 +-- src/Episode3/Tournament.hh | 10 +- src/FileContentsCache.cc | 6 +- src/FileContentsCache.hh | 2 +- src/FunctionCompiler.cc | 98 ++--- src/GSLArchive.cc | 27 +- src/GSLArchive.hh | 6 +- src/GVMEncoder.cc | 4 +- src/GVMEncoder.hh | 2 +- src/HTTPServer.cc | 306 +++++++------- src/HTTPServer.hh | 34 +- src/IPFrameInfo.cc | 20 +- src/IPFrameInfo.hh | 4 +- src/IPStackSimulator.cc | 101 +++-- src/IPV4RangeSet.cc | 12 +- src/IPV4RangeSet.hh | 4 +- src/IntegralExpression.cc | 6 +- src/ItemCreator.cc | 14 +- src/ItemCreator.hh | 2 +- src/ItemData.cc | 14 +- src/ItemData.hh | 2 +- src/ItemNameIndex.cc | 136 +++--- src/ItemParameterTable.cc | 60 ++- src/ItemParameterTable.hh | 223 +++++----- src/LevelTable.cc | 18 +- src/LevelTable.hh | 52 +-- src/Lobby.cc | 18 +- src/Lobby.hh | 12 +- src/Loggers.cc | 38 +- src/Loggers.hh | 32 +- src/Main.cc | 538 ++++++++++++------------ src/Map.cc | 146 ++++--- src/Map.hh | 16 +- src/NetworkAddresses.cc | 12 +- src/PSOEncryption.cc | 24 +- src/PSOEncryption.hh | 44 +- src/PSOGCObjectGraph.cc | 37 +- src/PSOGCObjectGraph.hh | 4 +- src/PSOProtocol.cc | 6 +- src/PSOProtocol.hh | 4 +- src/PatchFileIndex.cc | 38 +- src/PatchServer.cc | 34 +- src/PatchServer.hh | 2 +- src/PlayerFilesManager.cc | 2 +- src/PlayerInventory.hh | 50 +-- src/PlayerSubordinates.cc | 42 +- src/PlayerSubordinates.hh | 165 ++++---- src/ProxyCommands.cc | 119 +++--- src/ProxyServer.cc | 60 +-- src/ProxyServer.hh | 8 +- src/Quest.cc | 146 ++++--- src/Quest.hh | 4 +- src/QuestScript.cc | 438 +++++++++---------- src/RareItemSet.cc | 95 ++--- src/RareItemSet.hh | 23 +- src/ReceiveCommands.cc | 106 +++-- src/ReceiveSubcommands.cc | 100 ++--- src/ReceiveSubcommands.hh | 2 +- src/ReplaySession.cc | 104 +++-- src/SaveFileFormats.cc | 30 +- src/SaveFileFormats.hh | 113 +++-- src/SendCommands.cc | 86 ++-- src/SendCommands.hh | 4 +- src/Server.cc | 24 +- src/ServerShell.cc | 104 ++--- src/ServerState.cc | 212 +++++----- src/ServerState.hh | 10 +- src/StaticGameData.cc | 4 +- src/TeamIndex.cc | 42 +- src/TeamIndex.hh | 10 +- src/Text.cc | 26 +- src/Text.hh | 18 +- src/TextIndex.cc | 110 +++-- src/TextIndex.hh | 26 +- src/Version.cc | 8 +- src/Version.hh | 8 +- src/WordSelectTable.cc | 58 ++- src/WordSelectTable.hh | 2 +- 116 files changed, 2969 insertions(+), 3088 deletions(-) diff --git a/src/AFSArchive.cc b/src/AFSArchive.cc index c3d791c4..f78bf60e 100644 --- a/src/AFSArchive.cc +++ b/src/AFSArchive.cc @@ -23,7 +23,7 @@ AFSArchive::AFSArchive(shared_ptr data) le_uint32_t size; } __packed_ws__(FileEntry, 8); - StringReader r(*this->data); + phosg::StringReader r(*this->data); const auto& header = r.get(); if (header.magic != 0x41465300) { // 'AFS\0' throw runtime_error("file is not an AFS archive"); @@ -52,29 +52,27 @@ string AFSArchive::get_copy(size_t index) const { return string(reinterpret_cast(ret.first), ret.second); } -StringReader AFSArchive::get_reader(size_t index) const { +phosg::StringReader AFSArchive::get_reader(size_t index) const { auto ret = this->get(index); - return StringReader(ret.first, ret.second); + return phosg::StringReader(ret.first, ret.second); } string AFSArchive::generate(const vector& files, bool big_endian) { return big_endian ? AFSArchive::generate_t(files) : AFSArchive::generate_t(files); } -template +template string AFSArchive::generate_t(const vector& files) { - using U32T = typename std::conditional::type; - - StringWriter w; + phosg::StringWriter w; w.put_u32b(0x41465300); // 'AFS\0' - w.put(files.size()); + w.put>(files.size()); // It seems entries are aligned to 0x800-byte boundaries, and the file's // header is always 0x80000 (!) bytes, most of which is unused uint32_t data_offset = 0x80000; for (const auto& file : files) { - w.put(data_offset); - w.put(file.size()); + w.put>(data_offset); + w.put>(file.size()); data_offset = (data_offset + file.size() + 0x7FF) & (~0x7FF); } diff --git a/src/AFSArchive.hh b/src/AFSArchive.hh index ad44a656..38df53d4 100644 --- a/src/AFSArchive.hh +++ b/src/AFSArchive.hh @@ -8,6 +8,8 @@ #include #include +#include "Types.hh" + class AFSArchive { public: AFSArchive(std::shared_ptr data); @@ -23,12 +25,12 @@ public: std::pair get(size_t index) const; std::string get_copy(size_t index) const; - StringReader get_reader(size_t index) const; + phosg::StringReader get_reader(size_t index) const; static std::string generate(const std::vector& files, bool big_endian); private: - template + template static std::string generate_t(const std::vector& files); std::shared_ptr data; diff --git a/src/Account.cc b/src/Account.cc index 94378cd4..2003dfd0 100644 --- a/src/Account.cc +++ b/src/Account.cc @@ -11,7 +11,7 @@ using namespace std; -shared_ptr DCNTELicense::from_json(const JSON& json) { +shared_ptr DCNTELicense::from_json(const phosg::JSON& json) { auto ret = make_shared(); ret->serial_number = json.get_string("SerialNumber"); ret->access_key = json.get_string("AccessKey"); @@ -30,14 +30,14 @@ shared_ptr DCNTELicense::from_json(const JSON& json) { return ret; } -JSON DCNTELicense::json() const { - return JSON::dict({ +phosg::JSON DCNTELicense::json() const { + return phosg::JSON::dict({ {"SerialNumber", this->serial_number}, {"AccessKey", this->access_key}, }); } -shared_ptr V1V2License::from_json(const JSON& json) { +shared_ptr V1V2License::from_json(const phosg::JSON& json) { auto ret = make_shared(); ret->serial_number = json.get_int("SerialNumber"); ret->access_key = json.get_string("AccessKey"); @@ -50,14 +50,14 @@ shared_ptr V1V2License::from_json(const JSON& json) { return ret; } -JSON V1V2License::json() const { - return JSON::dict({ +phosg::JSON V1V2License::json() const { + return phosg::JSON::dict({ {"SerialNumber", this->serial_number}, {"AccessKey", this->access_key}, }); } -shared_ptr GCLicense::from_json(const JSON& json) { +shared_ptr GCLicense::from_json(const phosg::JSON& json) { auto ret = make_shared(); ret->serial_number = json.get_int("SerialNumber"); ret->access_key = json.get_string("AccessKey"); @@ -74,15 +74,15 @@ shared_ptr GCLicense::from_json(const JSON& json) { return ret; } -JSON GCLicense::json() const { - return JSON::dict({ +phosg::JSON GCLicense::json() const { + return phosg::JSON::dict({ {"SerialNumber", this->serial_number}, {"AccessKey", this->access_key}, {"Password", this->password}, }); } -shared_ptr XBLicense::from_json(const JSON& json) { +shared_ptr XBLicense::from_json(const phosg::JSON& json) { auto ret = make_shared(); ret->gamertag = json.get_string("GamerTag"); ret->user_id = json.get_int("UserID"); @@ -99,15 +99,15 @@ shared_ptr XBLicense::from_json(const JSON& json) { return ret; } -JSON XBLicense::json() const { - return JSON::dict({ +phosg::JSON XBLicense::json() const { + return phosg::JSON::dict({ {"GamerTag", this->gamertag}, {"UserID", this->user_id}, {"AccountID", this->account_id}, }); } -shared_ptr BBLicense::from_json(const JSON& json) { +shared_ptr BBLicense::from_json(const phosg::JSON& json) { auto ret = make_shared(); ret->username = json.get_string("UserName"); ret->password = json.get_string("Password"); @@ -126,14 +126,14 @@ shared_ptr BBLicense::from_json(const JSON& json) { return ret; } -JSON BBLicense::json() const { - return JSON::dict({ +phosg::JSON BBLicense::json() const { + return phosg::JSON::dict({ {"UserName", this->username}, {"Password", this->password}, }); } -Account::Account(const JSON& json) +Account::Account(const phosg::JSON& json) : account_id(0), flags(0), ban_end_time(0), @@ -237,38 +237,38 @@ Account::Account(const JSON& json) } } -JSON Account::json() const { - JSON dc_nte_json = JSON::list(); +phosg::JSON Account::json() const { + phosg::JSON dc_nte_json = phosg::JSON::list(); for (const auto& it : this->dc_nte_licenses) { dc_nte_json.emplace_back(it.second->json()); } - JSON dc_json = JSON::list(); + phosg::JSON dc_json = phosg::JSON::list(); for (const auto& it : this->dc_licenses) { dc_json.emplace_back(it.second->json()); } - JSON pc_json = JSON::list(); + phosg::JSON pc_json = phosg::JSON::list(); for (const auto& it : this->pc_licenses) { pc_json.emplace_back(it.second->json()); } - JSON gc_json = JSON::list(); + phosg::JSON gc_json = phosg::JSON::list(); for (const auto& it : this->gc_licenses) { gc_json.emplace_back(it.second->json()); } - JSON xb_json = JSON::list(); + phosg::JSON xb_json = phosg::JSON::list(); for (const auto& it : this->xb_licenses) { xb_json.emplace_back(it.second->json()); } - JSON bb_json = JSON::list(); + phosg::JSON bb_json = phosg::JSON::list(); for (const auto& it : this->bb_licenses) { bb_json.emplace_back(it.second->json()); } - JSON auto_patches_json = JSON::list(); + phosg::JSON auto_patches_json = phosg::JSON::list(); for (const auto& it : this->auto_patches_enabled) { auto_patches_json.emplace_back(it); } - return JSON::dict({ + return phosg::JSON::dict({ {"FormatVersion", 1}, {"AccountID", this->account_id}, {"DCNTELicenses", std::move(dc_nte_json)}, @@ -333,14 +333,14 @@ void Account::print(FILE* stream) const { } if (flags_str.empty()) { flags_str = "none"; - } else if (ends_with(flags_str, ",")) { + } else if (phosg::ends_with(flags_str, ",")) { flags_str.pop_back(); } fprintf(stream, " Flags: %08" PRIX32 " (%s)\n", this->flags, flags_str.c_str()); } if (this->ban_end_time) { - string time_str = format_time(this->ban_end_time); + string time_str = phosg::format_time(this->ban_end_time); fprintf(stream, " Banned until: %" PRIu64 " (%s)\n", this->ban_end_time, time_str.c_str()); } if (this->ep3_current_meseta || this->ep3_total_meseta_earned) { @@ -388,14 +388,14 @@ void Account::print(FILE* stream) const { void Account::save() const { if (!this->is_temporary) { auto json = this->json(); - string json_data = json.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::HEX_INTEGERS); - string filename = string_printf("system/licenses/%010" PRIu32 ".json", this->account_id); - save_file(filename, json_data); + string json_data = json.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS); + string filename = phosg::string_printf("system/licenses/%010" PRIu32 ".json", this->account_id); + phosg::save_file(filename, json_data); } } void Account::delete_file() const { - string filename = string_printf("system/licenses/%010" PRIu32 ".json", this->account_id); + string filename = phosg::string_printf("system/licenses/%010" PRIu32 ".json", this->account_id); remove(filename.c_str()); } @@ -420,7 +420,7 @@ shared_ptr AccountIndex::from_dc_nte_credentials_locked(const string& ser if (login->dc_nte_license->access_key != access_key) { throw incorrect_access_key(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } return login; @@ -448,7 +448,7 @@ shared_ptr AccountIndex::from_dc_nte_credentials( auto login = make_shared(); login->account_was_created = true; login->account = make_shared(); - login->account->account_id = fnv1a32(serial_number) & 0x7FFFFFFF; + login->account->account_id = phosg::fnv1a32(serial_number) & 0x7FFFFFFF; auto lic = make_shared(); lic->serial_number = serial_number; lic->access_key = access_key; @@ -470,7 +470,7 @@ shared_ptr AccountIndex::from_dc_credentials_locked( if (!is_shared && (login->dc_license->access_key != access_key)) { throw incorrect_access_key(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } if (is_shared) { @@ -519,7 +519,7 @@ shared_ptr AccountIndex::from_pc_nte_credentials(uint32_t guild_card_numb throw missing_account(); } if (guild_card_number == 0xFFFFFFFF) { - guild_card_number = random_object() & 0x7FFFFFFF; + guild_card_number = phosg::random_object() & 0x7FFFFFFF; } auto login = make_shared(); login->account_was_created = true; @@ -543,7 +543,7 @@ shared_ptr AccountIndex::from_pc_credentials_locked( if (!is_shared && (login->pc_license->access_key != access_key)) { throw incorrect_access_key(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } if (is_shared) { @@ -599,7 +599,7 @@ shared_ptr AccountIndex::from_gc_credentials_locked( if (password && (login->gc_license->password != *password)) { throw incorrect_password(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } if (is_shared) { @@ -652,7 +652,7 @@ shared_ptr AccountIndex::from_xb_credentials_locked(const string& gamerta (login->xb_license->account_id && (login->xb_license->account_id != account_id))) { throw incorrect_access_key(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } return login; @@ -680,7 +680,7 @@ shared_ptr AccountIndex::from_xb_credentials( auto login = make_shared(); login->account_was_created = true; login->account = make_shared(); - login->account->account_id = fnv1a32(gamertag) & 0x7FFFFFFF; + login->account->account_id = phosg::fnv1a32(gamertag) & 0x7FFFFFFF; auto lic = make_shared(); lic->gamertag = gamertag; lic->user_id = user_id; @@ -701,7 +701,7 @@ shared_ptr AccountIndex::from_bb_credentials_locked(const string& usernam if (password && (login->bb_license->password != *password)) { throw incorrect_password(); } - if (login->account->ban_end_time && (login->account->ban_end_time >= now())) { + if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) { throw invalid_argument("user is banned"); } return login; @@ -728,7 +728,7 @@ shared_ptr AccountIndex::from_bb_credentials(const string& username, cons auto login = make_shared(); login->account_was_created = true; login->account = make_shared(); - login->account->account_id = fnv1a32(username) & 0x7FFFFFFF; + login->account->account_id = phosg::fnv1a32(username) & 0x7FFFFFFF; auto lic = make_shared(); lic->username = username; lic->password = *password; @@ -976,24 +976,24 @@ shared_ptr AccountIndex::create_temporary_account_for_shared_account( shared_ptr src_a, const string& variation_data) const { auto ret = make_shared(*src_a); ret->is_temporary = true; - ret->account_id = fnv1a32(&src_a->account_id, sizeof(src_a->account_id)); - ret->account_id = fnv1a32(variation_data, ret->account_id); + ret->account_id = phosg::fnv1a32(&src_a->account_id, sizeof(src_a->account_id)); + ret->account_id = phosg::fnv1a32(variation_data, ret->account_id); return ret; } AccountIndex::AccountIndex(bool force_all_temporary) : force_all_temporary(force_all_temporary) { if (!this->force_all_temporary) { - if (!isdir("system/licenses")) { + if (!phosg::isdir("system/licenses")) { mkdir("system/licenses", 0755); } else { - for (const auto& item : list_directory("system/licenses")) { - if (ends_with(item, ".json")) { + for (const auto& item : phosg::list_directory("system/licenses")) { + if (phosg::ends_with(item, ".json")) { try { - JSON json = JSON::parse(load_file("system/licenses/" + item)); + phosg::JSON json = phosg::JSON::parse(phosg::load_file("system/licenses/" + item)); this->add(make_shared(json)); } catch (const exception& e) { - log_error("Failed to index account %s", item.c_str()); + phosg::log_error("Failed to index account %s", item.c_str()); throw; } } diff --git a/src/Account.hh b/src/Account.hh index 8665d5e2..3963c941 100644 --- a/src/Account.hh +++ b/src/Account.hh @@ -16,16 +16,16 @@ struct DCNTELicense { std::string serial_number; std::string access_key; - static std::shared_ptr from_json(const JSON& json); - JSON json() const; + static std::shared_ptr from_json(const phosg::JSON& json); + phosg::JSON json() const; }; struct V1V2License { uint32_t serial_number = 0; std::string access_key; - static std::shared_ptr from_json(const JSON& json); - JSON json() const; + static std::shared_ptr from_json(const phosg::JSON& json); + phosg::JSON json() const; }; struct GCLicense { @@ -33,8 +33,8 @@ struct GCLicense { std::string access_key; std::string password; - static std::shared_ptr from_json(const JSON& json); - JSON json() const; + static std::shared_ptr from_json(const phosg::JSON& json); + phosg::JSON json() const; }; struct XBLicense { @@ -42,16 +42,16 @@ struct XBLicense { uint64_t user_id = 0; uint64_t account_id = 0; - static std::shared_ptr from_json(const JSON& json); - JSON json() const; + static std::shared_ptr from_json(const phosg::JSON& json); + phosg::JSON json() const; }; struct BBLicense { std::string username; std::string password; - static std::shared_ptr from_json(const JSON& json); - JSON json() const; + static std::shared_ptr from_json(const phosg::JSON& json); + phosg::JSON json() const; }; struct Account { @@ -101,10 +101,10 @@ struct Account { std::unordered_map> bb_licenses; Account() = default; - explicit Account(const JSON& json); + explicit Account(const phosg::JSON& json); virtual ~Account() = default; - JSON json() const; + phosg::JSON json() const; virtual void save() const; virtual void delete_file() const; diff --git a/src/AddressTranslator.cc b/src/AddressTranslator.cc index 65804496..b2d1cca0 100644 --- a/src/AddressTranslator.cc +++ b/src/AddressTranslator.cc @@ -108,11 +108,11 @@ public: : log("[addr-trans] "), directory(directory), enable_ppc(false) { - while (ends_with(this->directory, "/")) { + while (phosg::ends_with(this->directory, "/")) { this->directory.pop_back(); } - for (const auto& filename : list_directory(this->directory)) { - if (ends_with(filename, ".dol")) { + for (const auto& filename : phosg::list_directory(this->directory)) { + if (phosg::ends_with(filename, ".dol")) { string name = filename.substr(0, filename.size() - 4); string path = directory + "/" + filename; ResourceDASM::DOLFile dol(path.c_str()); @@ -121,7 +121,7 @@ public: this->mems.emplace(name, mem); this->enable_ppc = true; this->log.info("Loaded %s", name.c_str()); - } else if (ends_with(filename, ".xbe")) { + } else if (phosg::ends_with(filename, ".xbe")) { string name = filename.substr(0, filename.size() - 4); string path = directory + "/" + filename; ResourceDASM::XBEFile xbe(path.c_str()); @@ -129,10 +129,10 @@ public: xbe.load_into(mem); this->mems.emplace(name, mem); this->log.info("Loaded %s", name.c_str()); - } else if (ends_with(filename, ".bin")) { + } else if (phosg::ends_with(filename, ".bin")) { string name = filename.substr(0, filename.size() - 4); string path = directory + "/" + filename; - string data = load_file(path); + string data = phosg::load_file(path); auto mem = make_shared(); mem->allocate_at(0x8C010000, data.size()); mem->memcpy(0x8C010000, data.data(), data.size()); @@ -160,7 +160,7 @@ public: uint32_t r2 = 0; uint32_t r13 = 0; for (const auto& block : it.second->allocated_blocks()) { - StringReader r = it.second->reader(block.first, block.second); + phosg::StringReader r = it.second->reader(block.first, block.second); while (!r.eof() && r.where()) { uint32_t opcode = r.get_u32b(); if ((opcode & 0xFFFF0000) == 0x3DA00000) { @@ -243,13 +243,13 @@ public: size_t num_matches = 0; size_t last_match_address = 0; size_t match_length = match_bytes_before + match_bytes_after + 4; - StringReader src_r = this->src_mem->reader(src_section.first + src_offset - match_bytes_before, match_length); + phosg::StringReader src_r = this->src_mem->reader(src_section.first + src_offset - match_bytes_before, match_length); for (const auto& dest_section : dest_mem->allocated_blocks()) { for (size_t dest_match_offset = 0; dest_match_offset + match_length < dest_section.second; dest_match_offset += (is_ppc ? 4 : 1)) { src_r.go(0); - StringReader dest_r = dest_mem->reader(dest_section.first + dest_match_offset, match_length); + phosg::StringReader dest_r = dest_mem->reader(dest_section.first + dest_match_offset, match_length); size_t z; if (is_ppc) { for (z = 0; z < match_length; z += 4) { @@ -429,11 +429,11 @@ public: } void handle_command(const string& command) { - auto tokens = split(command, ' '); + auto tokens = phosg::split(command, ' '); if (tokens.empty()) { throw runtime_error("no command given"); } - strip_trailing_whitespace(tokens[tokens.size() - 1]); + phosg::strip_trailing_whitespace(tokens[tokens.size() - 1]); if (tokens[0] == "use") { this->set_source_file(tokens.at(1)); @@ -457,7 +457,7 @@ public: } fflush(stdout); - string command = fgets(stdin); + string command = phosg::fgets(stdin); try { this->handle_command(command); } catch (const exception& e) { @@ -468,7 +468,7 @@ public: } private: - PrefixedLogger log; + phosg::PrefixedLogger log; string directory; unordered_map> mems; string src_filename; diff --git a/src/BMLArchive.cc b/src/BMLArchive.cc index 4f8ee4a4..973e3ab6 100644 --- a/src/BMLArchive.cc +++ b/src/BMLArchive.cc @@ -5,15 +5,14 @@ #include #include "Text.hh" +#include "Types.hh" using namespace std; -template +template struct BMLHeaderT { - using U32T = typename std::conditional::type; - parray unknown_a1; - U32T num_entries; + U32T num_entries; parray unknown_a2; } __packed__; @@ -22,16 +21,14 @@ using BMLHeaderBE = BMLHeaderT; check_struct_size(BMLHeader, 0x40); check_struct_size(BMLHeaderBE, 0x40); -template +template struct BMLHeaderEntryT { - using U32T = typename std::conditional::type; - pstring filename; - U32T compressed_size; + U32T compressed_size; parray unknown_a1; - U32T decompressed_size; - U32T compressed_gvm_size; - U32T decompressed_gvm_size; + U32T decompressed_size; + U32T compressed_gvm_size; + U32T decompressed_gvm_size; parray unknown_a2; } __packed__; @@ -40,15 +37,15 @@ using BMLHeaderEntryBE = BMLHeaderEntryT; check_struct_size(BMLHeaderEntry, 0x40); check_struct_size(BMLHeaderEntryBE, 0x40); -template +template void BMLArchive::load_t() { - StringReader r(*this->data); + phosg::StringReader r(*this->data); - const auto& header = r.get>(); + const auto& header = r.get>(); size_t offset = 0x800; while (this->entries.size() < header.num_entries) { - const auto& entry = r.get>(); + const auto& entry = r.get>(); if (offset + entry.compressed_size > this->data->size()) { throw runtime_error("BML data entry extends beyond end of data"); @@ -106,10 +103,10 @@ string BMLArchive::get_copy(const string& name) const { } } -StringReader BMLArchive::get_reader(const string& name) const { +phosg::StringReader BMLArchive::get_reader(const string& name) const { try { const auto& entry = this->entries.at(name); - return StringReader(this->data->data() + entry.offset, entry.size); + return phosg::StringReader(this->data->data() + entry.offset, entry.size); } catch (const out_of_range&) { throw out_of_range("BML does not contain file: " + name); } diff --git a/src/BMLArchive.hh b/src/BMLArchive.hh index 4eafad1a..2c13389a 100644 --- a/src/BMLArchive.hh +++ b/src/BMLArchive.hh @@ -24,10 +24,10 @@ public: std::pair get(const std::string& name) const; std::pair get_gvm(const std::string& name) const; std::string get_copy(const std::string& name) const; - StringReader get_reader(const std::string& name) const; + phosg::StringReader get_reader(const std::string& name) const; private: - template + template void load_t(); std::shared_ptr data; diff --git a/src/BattleParamsIndex.cc b/src/BattleParamsIndex.cc index 8cf63439..4385e900 100644 --- a/src/BattleParamsIndex.cc +++ b/src/BattleParamsIndex.cc @@ -54,7 +54,7 @@ BattleParamsIndex::BattleParamsIndex( for (uint8_t episode = 0; episode < 3; episode++) { auto& file = this->files[is_solo][episode]; if (file.data->size() < sizeof(Table)) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "battle params table size is incorrect (expected %zX bytes, have %zX bytes; is_solo=%hhu, episode=%hhu)", sizeof(Table), file.data->size(), is_solo, episode)); } diff --git a/src/CatSession.cc b/src/CatSession.cc index 3066e3c1..a8e7cf23 100644 --- a/src/CatSession.cc +++ b/src/CatSession.cc @@ -38,7 +38,7 @@ CatSession::CatSession( const struct sockaddr_storage& remote, Version version, shared_ptr bb_key_file) - : log(string_printf("[CatSession:%s] ", name_for_enum(version)), proxy_server_log.min_level), + : log(phosg::string_printf("[CatSession:%s] ", phosg::name_for_enum(version)), proxy_server_log.min_level), base(base), read_event(event_new(this->base.get(), 0, EV_READ | EV_PERSIST, CatSession::dispatch_read_stdin, this), event_free), channel(version, 1, CatSession::dispatch_on_channel_input, CatSession::dispatch_on_channel_error, this, "CatSession"), @@ -48,19 +48,19 @@ CatSession::CatSession( throw runtime_error("remote is not AF_INET"); } - string netloc_str = render_sockaddr_storage(remote); + string netloc_str = phosg::render_sockaddr_storage(remote); this->log.info("Connecting to %s", netloc_str.c_str()); struct bufferevent* bev = bufferevent_socket_new( this->base.get(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); if (!bev) { - throw runtime_error(string_printf("failed to open socket (%d)", EVUTIL_SOCKET_ERROR())); + throw runtime_error(phosg::string_printf("failed to open socket (%d)", EVUTIL_SOCKET_ERROR())); } this->channel.set_bufferevent(bev, 0); if (bufferevent_socket_connect(this->channel.bev.get(), reinterpret_cast(&remote), sizeof(struct sockaddr_in)) != 0) { - throw runtime_error(string_printf("failed to connect (%d)", EVUTIL_SOCKET_ERROR())); + throw runtime_error(phosg::string_printf("failed to connect (%d)", EVUTIL_SOCKET_ERROR())); } event_add(this->read_event.get(), nullptr); @@ -68,7 +68,7 @@ CatSession::CatSession( } void CatSession::execute_command(const std::string& command) { - string full_cmd = parse_data_string(command, nullptr, ParseDataFlags::ALLOW_FILES); + string full_cmd = phosg::parse_data_string(command, nullptr, phosg::ParseDataFlags::ALLOW_FILES); send_command_with_header(this->channel, full_cmd.data(), full_cmd.size()); } @@ -109,9 +109,8 @@ void CatSession::on_channel_input( // TODO: Use the iovec form of print_data here instead of // prepend_command_header (which copies the string) - string full_cmd = prepend_command_header( - this->channel.version, this->channel.crypt_in.get(), command, flag, data); - print_data(stdout, full_cmd, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::OFFSET_16_BITS); + string full_cmd = prepend_command_header(this->channel.version, this->channel.crypt_in.get(), command, flag, data); + phosg::print_data(stdout, full_cmd, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::OFFSET_16_BITS); } void CatSession::dispatch_on_channel_error(Channel& ch, short events) { diff --git a/src/CatSession.hh b/src/CatSession.hh index 88f465c6..6cd664c0 100644 --- a/src/CatSession.hh +++ b/src/CatSession.hh @@ -29,10 +29,10 @@ public: virtual ~CatSession() = default; protected: - PrefixedLogger log; + phosg::PrefixedLogger log; std::shared_ptr base; std::unique_ptr read_event; - Poll poll; + phosg::Poll poll; Channel channel; std::shared_ptr bb_key_file; diff --git a/src/Channel.cc b/src/Channel.cc index 3532726d..e26d858f 100644 --- a/src/Channel.cc +++ b/src/Channel.cc @@ -29,8 +29,8 @@ Channel::Channel( on_error_t on_error, void* context_obj, const string& name, - TerminalFormat terminal_send_color, - TerminalFormat terminal_recv_color) + phosg::TerminalFormat terminal_send_color, + phosg::TerminalFormat terminal_recv_color) : bev(nullptr, flush_and_free_bufferevent), virtual_network_id(0), version(version), @@ -52,8 +52,8 @@ Channel::Channel( on_error_t on_error, void* context_obj, const string& name, - TerminalFormat terminal_send_color, - TerminalFormat terminal_recv_color) + phosg::TerminalFormat terminal_send_color, + phosg::TerminalFormat terminal_recv_color) : bev(nullptr, flush_and_free_bufferevent), version(version), language(language), @@ -98,7 +98,7 @@ void Channel::set_bufferevent(struct bufferevent* bev, uint64_t virtual_network_ memset(&this->local_addr, 0, sizeof(this->local_addr)); memset(&this->remote_addr, 0, sizeof(this->remote_addr)); } else { - get_socket_addresses(fd, &this->local_addr, &this->remote_addr); + phosg::get_socket_addresses(fd, &this->local_addr, &this->remote_addr); } bufferevent_setcb(this->bev.get(), &Channel::dispatch_on_input, nullptr, &Channel::dispatch_on_error, this); @@ -206,9 +206,9 @@ Channel::Message Channel::recv() { } command_data.resize(command_logical_size - header_size); - if (command_data_log.should_log(LogLevel::INFO) && (this->terminal_recv_color != TerminalFormat::END)) { - if (use_terminal_colors && this->terminal_recv_color != TerminalFormat::NORMAL) { - print_color_escape(stderr, this->terminal_recv_color, TerminalFormat::BOLD, TerminalFormat::END); + if (command_data_log.should_log(phosg::LogLevel::INFO) && (this->terminal_recv_color != phosg::TerminalFormat::END)) { + if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) { + print_color_escape(stderr, this->terminal_recv_color, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END); } if (version == Version::BB_V4) { @@ -221,7 +221,7 @@ Channel::Message Channel::recv() { command_data_log.info( "Received from %s (version=%s command=%02hX flag=%02" PRIX32 ")", this->name.c_str(), - name_for_enum(this->version), + phosg::name_for_enum(this->version), header.command(this->version), header.flag(this->version)); } @@ -229,10 +229,10 @@ Channel::Message Channel::recv() { vector iovs; iovs.emplace_back(iovec{.iov_base = header_data.data(), .iov_len = header_data.size()}); iovs.emplace_back(iovec{.iov_base = command_data.data(), .iov_len = command_data.size()}); - print_data(stderr, iovs, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stderr, iovs, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); - if (use_terminal_colors && this->terminal_recv_color != TerminalFormat::NORMAL) { - print_color_escape(stderr, TerminalFormat::NORMAL, TerminalFormat::END); + if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) { + phosg::print_color_escape(stderr, phosg::TerminalFormat::NORMAL, phosg::TerminalFormat::END); } } @@ -342,20 +342,20 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vectorterminal_send_color != TerminalFormat::END)) { - if (use_terminal_colors && this->terminal_send_color != TerminalFormat::NORMAL) { - print_color_escape(stderr, TerminalFormat::FG_YELLOW, TerminalFormat::BOLD, TerminalFormat::END); + if (!silent && (command_data_log.should_log(phosg::LogLevel::INFO)) && (this->terminal_send_color != phosg::TerminalFormat::END)) { + if (use_terminal_colors && this->terminal_send_color != phosg::TerminalFormat::NORMAL) { + print_color_escape(stderr, phosg::TerminalFormat::FG_YELLOW, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END); } if (version == Version::BB_V4) { command_data_log.info("Sending to %s (version=BB command=%04hX flag=%08" PRIX32 ")", this->name.c_str(), cmd, flag); } else { command_data_log.info("Sending to %s (version=%s command=%02hX flag=%02" PRIX32 ")", - this->name.c_str(), name_for_enum(version), cmd, flag); + this->name.c_str(), phosg::name_for_enum(version), cmd, flag); } - print_data(stderr, send_data.data(), logical_size, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); - if (use_terminal_colors && this->terminal_send_color != TerminalFormat::NORMAL) { - print_color_escape(stderr, TerminalFormat::NORMAL, TerminalFormat::END); + phosg::print_data(stderr, send_data.data(), logical_size, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); + if (use_terminal_colors && this->terminal_send_color != phosg::TerminalFormat::NORMAL) { + print_color_escape(stderr, phosg::TerminalFormat::NORMAL, phosg::TerminalFormat::END); } } diff --git a/src/Channel.hh b/src/Channel.hh index a6cc3685..cb539774 100644 --- a/src/Channel.hh +++ b/src/Channel.hh @@ -21,8 +21,8 @@ struct Channel { std::shared_ptr crypt_out; std::string name; - TerminalFormat terminal_send_color; - TerminalFormat terminal_recv_color; + phosg::TerminalFormat terminal_send_color; + phosg::TerminalFormat terminal_recv_color; struct Message { uint16_t command; @@ -45,8 +45,8 @@ struct Channel { on_error_t on_error, void* context_obj, const std::string& name, - TerminalFormat terminal_send_color = TerminalFormat::END, - TerminalFormat terminal_recv_color = TerminalFormat::END); + phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END, + phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END); // Creates a connected channel Channel( struct bufferevent* bev, @@ -57,8 +57,8 @@ struct Channel { on_error_t on_error, void* context_obj, const std::string& name = "", - TerminalFormat terminal_send_color = TerminalFormat::END, - TerminalFormat terminal_recv_color = TerminalFormat::END); + phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END, + phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END); Channel(const Channel& other) = delete; Channel(Channel&& other) = delete; Channel& operator=(const Channel& other) = delete; diff --git a/src/ChatCommands.cc b/src/ChatCommands.cc index 61ff0f31..ea2a4e6e 100644 --- a/src/ChatCommands.cc +++ b/src/ChatCommands.cc @@ -103,7 +103,7 @@ static void check_is_leader(shared_ptr l, shared_ptr c) { static void server_command_server_info(shared_ptr c, const std::string&) { auto s = c->require_server_state(); - string uptime_str = format_duration(now() - s->creation_time); + string uptime_str = phosg::format_duration(phosg::now() - s->creation_time); send_text_message_printf(c, "Uptime: $C6%s$C7\nLobbies: $C6%zu$C7\nClients: $C6%zu$C7(g) $C6%zu$C7(p)", uptime_str.c_str(), @@ -123,11 +123,11 @@ static void server_command_lobby_info(shared_ptr c, const std::string&) if (l->is_game()) { if (!l->is_ep3()) { if (l->max_level == 0xFFFFFFFF) { - lines.emplace_back(string_printf("$C6%08X$C7 L$C6%d+$C7", l->lobby_id, l->min_level + 1)); + lines.emplace_back(phosg::string_printf("$C6%08X$C7 L$C6%d+$C7", l->lobby_id, l->min_level + 1)); } else { - lines.emplace_back(string_printf("$C6%08X$C7 L$C6%d-%d$C7", l->lobby_id, l->min_level + 1, l->max_level + 1)); + lines.emplace_back(phosg::string_printf("$C6%08X$C7 L$C6%d-%d$C7", l->lobby_id, l->min_level + 1, l->max_level + 1)); } - lines.emplace_back(string_printf("$C7Section ID: $C6%s$C7", name_for_section_id(l->effective_section_id()))); + lines.emplace_back(phosg::string_printf("$C7Section ID: $C6%s$C7", name_for_section_id(l->effective_section_id()))); switch (l->drop_mode) { case Lobby::DropMode::DISABLED: @@ -153,45 +153,45 @@ static void server_command_lobby_info(shared_ptr c, const std::string&) } } else { - lines.emplace_back(string_printf("$C7State seed: $C6%08X$C7", l->random_seed)); + lines.emplace_back(phosg::string_printf("$C7State seed: $C6%08X$C7", l->random_seed)); } } else { - lines.emplace_back(string_printf("$C7Lobby ID: $C6%08X$C7", l->lobby_id)); + lines.emplace_back(phosg::string_printf("$C7Lobby ID: $C6%08X$C7", l->lobby_id)); } string slots_str = "Slots: "; for (size_t z = 0; z < l->clients.size(); z++) { if (!l->clients[z]) { - slots_str += string_printf("$C0%zX$C7", z); + slots_str += phosg::string_printf("$C0%zX$C7", z); } else { bool is_self = l->clients[z] == c; bool is_leader = z == l->leader_id; if (is_self && is_leader) { - slots_str += string_printf("$C6%zX$C7", z); + slots_str += phosg::string_printf("$C6%zX$C7", z); } else if (is_self) { - slots_str += string_printf("$C2%zX$C7", z); + slots_str += phosg::string_printf("$C2%zX$C7", z); } else if (is_leader) { - slots_str += string_printf("$C4%zX$C7", z); + slots_str += phosg::string_printf("$C4%zX$C7", z); } else { - slots_str += string_printf("%zX", z); + slots_str += phosg::string_printf("%zX", z); } } } lines.emplace_back(std::move(slots_str)); } - send_text_message(c, join(lines, "\n")); + send_text_message(c, phosg::join(lines, "\n")); } static void server_command_ping(shared_ptr c, const std::string&) { - c->ping_start_time = now(); + c->ping_start_time = phosg::now(); send_command(c, 0x1D, 0x00); } static void proxy_command_ping(shared_ptr ses, const std::string&) { - ses->client_ping_start_time = now(); - ses->server_ping_start_time = now(); + ses->client_ping_start_time = phosg::now(); + ses->server_ping_start_time = ses->client_ping_start_time; C_GuildCardSearch_40 cmd = {0x00010000, ses->remote_guild_card_number, ses->remote_guild_card_number}; ses->client_channel.send(0x1D, 0x00); @@ -204,7 +204,7 @@ static void proxy_command_lobby_info(shared_ptr ses, // don't show it. (The user can see it in the pause menu, unlike in masked-GC // sessions like GC.) if (ses->remote_guild_card_number >= 0) { - msg = string_printf("$C7GC: $C6%" PRId64 "$C7\n", ses->remote_guild_card_number); + msg = phosg::string_printf("$C7GC: $C6%" PRId64 "$C7\n", ses->remote_guild_card_number); } msg += "Slots: "; @@ -212,15 +212,15 @@ static void proxy_command_lobby_info(shared_ptr ses, bool is_self = z == ses->lobby_client_id; bool is_leader = z == ses->leader_client_id; if (ses->lobby_players[z].guild_card_number == 0) { - msg += string_printf("$C0%zX$C7", z); + msg += phosg::string_printf("$C0%zX$C7", z); } else if (is_self && is_leader) { - msg += string_printf("$C6%zX$C7", z); + msg += phosg::string_printf("$C6%zX$C7", z); } else if (is_self) { - msg += string_printf("$C2%zX$C7", z); + msg += phosg::string_printf("$C2%zX$C7", z); } else if (is_leader) { - msg += string_printf("$C4%zX$C7", z); + msg += phosg::string_printf("$C4%zX$C7", z); } else { - msg += string_printf("%zX", z); + msg += phosg::string_printf("%zX", z); } } @@ -233,7 +233,7 @@ static void proxy_command_lobby_info(shared_ptr ses, } if (!cheats_tokens.empty()) { msg += "\n$C7Cheats: $C6"; - msg += join(cheats_tokens, ","); + msg += phosg::join(cheats_tokens, ","); } vector behaviors_tokens; @@ -251,7 +251,7 @@ static void proxy_command_lobby_info(shared_ptr ses, } if (!behaviors_tokens.empty()) { msg += "\n$C7Flags: $C6"; - msg += join(behaviors_tokens, ","); + msg += phosg::join(behaviors_tokens, ","); } if (ses->config.override_section_id != 0xFF) { @@ -353,7 +353,7 @@ static void server_command_swset_swclear(shared_ptr c, const std::string return; } - auto tokens = split(args, ' '); + auto tokens = phosg::split(args, ' '); uint8_t floor, flag_num; if (tokens.size() == 1) { floor = c->floor; @@ -391,7 +391,7 @@ static void proxy_command_swset_swclear(shared_ptr s return; } - auto tokens = split(args, ' '); + auto tokens = phosg::split(args, ' '); uint8_t floor, flag_num; if (tokens.size() == 1) { floor = ses->floor; @@ -589,7 +589,7 @@ static void server_command_qgwrite(shared_ptr c, const std::string& args return; } - auto tokens = split(args, ' '); + auto tokens = phosg::split(args, ' '); if (tokens.size() != 2) { send_text_message(c, "$C6Incorrect number\nof arguments"); return; @@ -616,7 +616,7 @@ static void server_command_qsync_qsyncall(shared_ptr c, const std::strin return; } - auto tokens = split(args, ' '); + auto tokens = phosg::split(args, ' '); if (tokens.size() != 2) { send_text_message(c, "$C6Incorrect number of\narguments"); return; @@ -655,7 +655,7 @@ static void proxy_command_qsync_qsyncall(shared_ptr return; } - auto tokens = split(args, ' '); + auto tokens = phosg::split(args, ' '); if (tokens.size() != 2) { send_text_message(ses->client_channel, "$C6Incorrect number of\narguments"); return; @@ -896,26 +896,26 @@ static void proxy_command_get_player_card(shared_ptr static void server_command_send_client(shared_ptr c, const std::string& args) { check_debug_enabled(c); - string data = parse_data_string(args); + string data = phosg::parse_data_string(args); data.resize((data.size() + 3) & (~3)); c->channel.send(data); } static void server_command_send_server(shared_ptr c, const std::string& args) { check_debug_enabled(c); - string data = parse_data_string(args); + string data = phosg::parse_data_string(args); data.resize((data.size() + 3) & (~3)); on_command_with_header(c, data); } static void proxy_command_send_client(shared_ptr ses, const std::string& args) { - string data = parse_data_string(args); + string data = phosg::parse_data_string(args); data.resize((data.size() + 3) & (~3)); ses->client_channel.send(data); } static void proxy_command_send_server(shared_ptr ses, const std::string& args) { - string data = parse_data_string(args); + string data = phosg::parse_data_string(args); data.resize((data.size() + 3) & (~3)); ses->server_channel.send(data); } @@ -1044,7 +1044,7 @@ static string file_path_for_recording(const std::string& args, uint32_t account_ throw runtime_error("invalid recording name"); } } - return string_printf("system/ep3/battle-records/%010" PRIu32 "_%s.mzrd", account_id, args.c_str()); + return phosg::string_printf("system/ep3/battle-records/%010" PRIu32 "_%s.mzrd", account_id, args.c_str()); } static void server_command_saverec(shared_ptr c, const std::string& args) { @@ -1054,7 +1054,7 @@ static void server_command_saverec(shared_ptr c, const std::string& args } string file_path = file_path_for_recording(args, c->login->account->account_id); string data = c->ep3_prev_battle_record->serialize(); - save_file(file_path, data); + phosg::save_file(file_path, data); send_text_message(c, "$C7Recording saved"); c->ep3_prev_battle_record.reset(); } @@ -1080,8 +1080,8 @@ static void server_command_playrec(shared_ptr c, const std::string& args string data; try { - data = load_file(file_path); - } catch (const cannot_open_file&) { + data = phosg::load_file(file_path); + } catch (const phosg::cannot_open_file&) { send_text_message(c, "$C4The recording does\nnot exist"); return; } @@ -1307,8 +1307,8 @@ static void server_command_edit(shared_ptr c, const std::string& args) { bool cheats_allowed = ((s->cheat_mode_behavior != ServerState::BehaviorSwitch::OFF) || c->login->account->check_flag(Account::Flag::CHEAT_ANYWHERE)); - string encoded_args = tolower(args); - vector tokens = split(encoded_args, ' '); + string encoded_args = phosg::tolower(args); + vector tokens = phosg::split(encoded_args, ' '); try { auto p = c->character(); @@ -1360,7 +1360,7 @@ static void server_command_edit(shared_ptr c, const std::string& args) { p->disp.visual.section_id = secid; } } else if (tokens.at(0) == "name") { - vector orig_tokens = split(args, ' '); + vector orig_tokens = phosg::split(args, ' '); p->disp.name.encode(orig_tokens.at(1), p->inventory.language); } else if (tokens.at(0) == "npc") { if (tokens.at(1) == "none") { @@ -1457,7 +1457,7 @@ static void server_command_bbchar_savechar(shared_ptr c, const std::stri auto pending_export = make_unique(); if (is_bb_conversion) { - vector tokens = split(args, ' '); + vector tokens = phosg::split(args, ' '); if (tokens.size() != 3) { send_text_message(c, "$C6Incorrect argument count"); return; @@ -1632,7 +1632,7 @@ static string name_for_client(shared_ptr c) { } if (c->login) { - return string_printf("SN:%" PRIu32, c->login->account->account_id); + return phosg::string_printf("SN:%" PRIu32, c->login->account->account_id); } return "Player"; @@ -1727,7 +1727,7 @@ static void server_command_ban(shared_ptr c, const std::string& args) { usecs *= 60 * 60 * 24 * 365; } - target->login->account->ban_end_time = now() + usecs; + target->login->account->ban_end_time = phosg::now() + usecs; target->login->account->save(); send_message_box(target, "$C6You have been banned."); target->should_disconnect = true; @@ -2135,7 +2135,7 @@ static void proxy_command_item(shared_ptr ses, const bool set_drop = (!args.empty() && (args[0] == '!')); ItemData item = s->parse_item_description(ses->version(), (set_drop ? args.substr(1) : args)); - item.id = random_object() | 0x80000000; + item.id = phosg::random_object() | 0x80000000; if (set_drop) { ses->next_drop_item = item; @@ -2224,7 +2224,7 @@ static void server_command_ep3_set_dice_range(shared_ptr c, const std::s } auto parse_dice_range = +[](const string& spec) -> uint8_t { - auto tokens = split(spec, '-'); + auto tokens = phosg::split(spec, '-'); if (tokens.size() == 1) { uint8_t v = stoull(spec); return (v << 4) | (v & 0x0F); @@ -2238,8 +2238,8 @@ static void server_command_ep3_set_dice_range(shared_ptr c, const std::s uint8_t def_dice_range = 0; uint8_t atk_dice_range_2v1 = 0; uint8_t def_dice_range_2v1 = 0; - for (const auto& spec : split(args, ' ')) { - auto tokens = split(spec, ':'); + for (const auto& spec : phosg::split(args, ' ')) { + auto tokens = phosg::split(spec, ':'); if (tokens.size() != 2) { send_text_message(c, "$C6Invalid dice spec\nformat"); return; @@ -2305,7 +2305,7 @@ static void server_command_ep3_replace_assist_card(shared_ptr c, const s size_t client_id; string card_name; if (isdigit(args[0])) { - auto tokens = split(args, ' ', 1); + auto tokens = phosg::split(args, ' ', 1); client_id = stoul(tokens.at(0), nullptr, 0) - 1; card_name = tokens.at(1); } else { @@ -2408,7 +2408,7 @@ static void server_command_get_ep3_battle_stat(shared_ptr c, const std:: const char* rank_name = ps->stats.name_for_rank(rank); send_text_message_printf(c, "$C7Score: %g\nRank: %hhu (%s)", score, rank, rank_name); } else if (args == "duration") { - string s = format_duration(now() - l->ep3_server->battle_start_usecs); + string s = phosg::format_duration(phosg::now() - l->ep3_server->battle_start_usecs); send_text_message_printf(c, "$C7Duration: %s", s.c_str()); } else if (args == "fcs-destroyed") { send_text_message_printf(c, "$C7Team FCs destroyed:\n%" PRIu32, l->ep3_server->team_num_ally_fcs_destroyed[team_id]); diff --git a/src/ChoiceSearch.hh b/src/ChoiceSearch.hh index 15116fbd..3d1e3666 100644 --- a/src/ChoiceSearch.hh +++ b/src/ChoiceSearch.hh @@ -7,18 +7,16 @@ #include #include "Text.hh" +#include "Types.hh" class Client; -template +template struct ChoiceSearchConfigT { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; - - U32T disabled = 1; // 0 = enabled, 1 = disabled. Unused in command C3 + U32T disabled = 1; // 0 = enabled, 1 = disabled. Unused in command C3 struct Entry { - U16T parent_choice_id = 0; - U16T choice_id = 0; + U16T parent_choice_id = 0; + U16T choice_id = 0; } __packed_ws__(Entry, 4); parray entries; @@ -31,8 +29,8 @@ struct ChoiceSearchConfigT { return -1; } - operator ChoiceSearchConfigT() const { - ChoiceSearchConfigT ret; + operator ChoiceSearchConfigT() const { + ChoiceSearchConfigT ret; ret.disabled = this->disabled.load(); for (size_t z = 0; z < this->entries.size(); z++) { auto& ret_e = ret.entries[z]; diff --git a/src/Client.cc b/src/Client.cc index fb961ab9..ad92edd3 100644 --- a/src/Client.cc +++ b/src/Client.cc @@ -144,7 +144,7 @@ void Client::Config::set_flags_for_version(Version version, int64_t sub_version) this->set_flag(Flag::CAN_RECEIVE_ENABLE_B2_QUEST); break; default: - throw runtime_error(string_printf("unknown sub_version %" PRIX64, sub_version)); + throw runtime_error(phosg::string_printf("unknown sub_version %" PRIX64, sub_version)); } } @@ -188,8 +188,8 @@ Client::Client( ServerBehavior server_behavior) : server(server), id(next_id++), - log(string_printf("[C-%" PRIX64 "] ", this->id), client_log.min_level), - channel(bev, virtual_network_id, version, 1, nullptr, nullptr, this, "", TerminalFormat::FG_YELLOW, TerminalFormat::FG_GREEN), + log(phosg::string_printf("[C-%" PRIX64 "] ", this->id), client_log.min_level), + channel(bev, virtual_network_id, version, 1, nullptr, nullptr, this, "", phosg::TerminalFormat::FG_YELLOW, phosg::TerminalFormat::FG_GREEN), server_behavior(server_behavior), should_disconnect(false), should_send_to_lobby_server(false), @@ -248,8 +248,8 @@ Client::Client( // more annoying than helpful at this point. if ((s->hide_download_commands) && ((this->channel.version == Version::PC_PATCH) || (this->channel.version == Version::BB_PATCH))) { - this->channel.terminal_recv_color = TerminalFormat::END; - this->channel.terminal_send_color = TerminalFormat::END; + this->channel.terminal_recv_color = phosg::TerminalFormat::END; + this->channel.terminal_send_color = phosg::TerminalFormat::END; } this->log.info("Created"); @@ -276,24 +276,24 @@ void Client::update_channel_name() { auto player = this->character(false, false); if (player) { string name_str = player->disp.name.decode(this->language()); - this->channel.name = string_printf("C-%" PRIX64 " (%s) @ %s", this->id, name_str.c_str(), ip_str.c_str()); + this->channel.name = phosg::string_printf("C-%" PRIX64 " (%s) @ %s", this->id, name_str.c_str(), ip_str.c_str()); } else { - this->channel.name = string_printf("C-%" PRIX64 " @ %s", this->id, ip_str.c_str()); + this->channel.name = phosg::string_printf("C-%" PRIX64 " @ %s", this->id, ip_str.c_str()); } } void Client::reschedule_save_game_data_event() { if (this->version() == Version::BB_V4) { - struct timeval tv = usecs_to_timeval(60000000); // 1 minute + struct timeval tv = phosg::usecs_to_timeval(60000000); // 1 minute event_add(this->save_game_data_event.get(), &tv); } } void Client::reschedule_ping_and_timeout_events() { auto s = this->require_server_state(); - struct timeval ping_tv = usecs_to_timeval(s->client_ping_interval_usecs); + struct timeval ping_tv = phosg::usecs_to_timeval(s->client_ping_interval_usecs); event_add(this->send_ping_event.get(), &ping_tv); - struct timeval idle_tv = usecs_to_timeval(s->client_idle_timeout_usecs); + struct timeval idle_tv = phosg::usecs_to_timeval(s->client_idle_timeout_usecs); event_add(this->idle_timeout_event.get(), &idle_tv); } @@ -393,7 +393,7 @@ bool Client::evaluate_quest_availability_expression( .v1_present = v1_present, }; int64_t ret = expr->evaluate(env); - if (this->log.should_log(LogLevel::INFO)) { + if (this->log.should_log(phosg::LogLevel::INFO)) { string expr_str = expr->str(); this->log.info("Evaluated integral expression %s => %s", expr_str.c_str(), ret ? "TRUE" : "FALSE"); } @@ -451,7 +451,7 @@ void Client::send_ping() { if (!is_patch(this->version())) { this->log.info("Sending ping command"); // The game doesn't use this timestamp; we only use it for debugging purposes - be_uint64_t timestamp = now(); + be_uint64_t timestamp = phosg::now(); try { this->channel.send(0x1D, 0x00, ×tamp, sizeof(be_uint64_t)); } catch (const exception& e) { @@ -643,7 +643,7 @@ string Client::system_filename() const { if (!this->login || !this->login->bb_license) { throw logic_error("client is not logged in"); } - return string_printf("system/players/system_%s.psosys", this->login->bb_license->username.c_str()); + return phosg::string_printf("system/players/system_%s.psosys", this->login->bb_license->username.c_str()); } string Client::character_filename(const std::string& bb_username, int8_t index) { @@ -653,11 +653,11 @@ string Client::character_filename(const std::string& bb_username, int8_t index) if (index < 0) { throw logic_error("character index is not set"); } - return string_printf("system/players/player_%s_%hhd.psochar", bb_username.c_str(), index); + return phosg::string_printf("system/players/player_%s_%hhd.psochar", bb_username.c_str(), index); } string Client::backup_character_filename(uint32_t account_id, size_t index, bool is_ep3) { - return string_printf("system/players/backup_player_%" PRIu32 "_%zu.%s", + return phosg::string_printf("system/players/backup_player_%" PRIu32 "_%zu.%s", account_id, index, is_ep3 ? "pso3char" : "psochar"); } @@ -678,7 +678,7 @@ string Client::guild_card_filename() const { if (!this->login || !this->login->bb_license) { throw logic_error("client is not logged in"); } - return string_printf("system/players/guild_cards_%s.psocard", this->login->bb_license->username.c_str()); + return phosg::string_printf("system/players/guild_cards_%s.psocard", this->login->bb_license->username.c_str()); } string Client::shared_bank_filename() const { @@ -688,7 +688,7 @@ string Client::shared_bank_filename() const { if (!this->login || !this->login->bb_license) { throw logic_error("client is not logged in"); } - return string_printf("system/players/shared_bank_%s.psobank", this->login->bb_license->username.c_str()); + return phosg::string_printf("system/players/shared_bank_%s.psobank", this->login->bb_license->username.c_str()); } string Client::legacy_account_filename() const { @@ -698,7 +698,7 @@ string Client::legacy_account_filename() const { if (!this->login || !this->login->bb_license) { throw logic_error("client is not logged in"); } - return string_printf("system/players/account_%s.nsa", this->login->bb_license->username.c_str()); + return phosg::string_printf("system/players/account_%s.nsa", this->login->bb_license->username.c_str()); } string Client::legacy_player_filename() const { @@ -711,7 +711,7 @@ string Client::legacy_player_filename() const { if (this->bb_character_index < 0) { throw logic_error("character index is not set"); } - return string_printf( + return phosg::string_printf( "system/players/player_%s_%hhd.nsc", this->login->bb_license->username.c_str(), static_cast(this->bb_character_index + 1)); @@ -747,8 +747,8 @@ void Client::load_all_files() { this->system_data = files_manager->get_system(sys_filename); if (this->system_data) { player_data_log.info("Using loaded system file %s", sys_filename.c_str()); - } else if (isfile(sys_filename)) { - this->system_data = make_shared(load_object_file(sys_filename, true)); + } else if (phosg::isfile(sys_filename)) { + this->system_data = make_shared(phosg::load_object_file(sys_filename, true)); files_manager->set_system(sys_filename, this->system_data); player_data_log.info("Loaded system data from %s", sys_filename.c_str()); } else { @@ -760,9 +760,9 @@ void Client::load_all_files() { this->character_data = files_manager->get_character(char_filename); if (this->character_data) { player_data_log.info("Using loaded character file %s", char_filename.c_str()); - } else if (isfile(char_filename)) { - auto f = fopen_unique(char_filename, "rb"); - auto header = freadx(f.get()); + } else if (phosg::isfile(char_filename)) { + auto f = phosg::fopen_unique(char_filename, "rb"); + auto header = phosg::freadx(f.get()); if (header.size != 0x399C) { throw runtime_error("incorrect size in character file header"); } @@ -773,14 +773,14 @@ void Client::load_all_files() { throw runtime_error("incorrect flag in character file header"); } static_assert(sizeof(PSOBBCharacterFile) + sizeof(PSOBBFullSystemFile) == 0x3994, ".psochar size is incorrect"); - this->character_data = make_shared(freadx(f.get())); + this->character_data = make_shared(phosg::freadx(f.get())); files_manager->set_character(char_filename, this->character_data); player_data_log.info("Loaded character data from %s", char_filename.c_str()); // If there was no .psosys file, load the system file from the .psochar // file instead if (!this->system_data) { - this->system_data = make_shared(freadx(f.get())); + this->system_data = make_shared(phosg::freadx(f.get())); files_manager->set_system(sys_filename, this->system_data); player_data_log.info("Loaded system data from %s", char_filename.c_str()); } @@ -797,8 +797,8 @@ void Client::load_all_files() { this->guild_card_data = files_manager->get_guild_card(card_filename); if (this->guild_card_data) { player_data_log.info("Using loaded Guild Card file %s", card_filename.c_str()); - } else if (isfile(card_filename)) { - this->guild_card_data = make_shared(load_object_file(card_filename)); + } else if (phosg::isfile(card_filename)) { + this->guild_card_data = make_shared(phosg::load_object_file(card_filename)); files_manager->set_guild_card(card_filename, this->guild_card_data); player_data_log.info("Loaded Guild Card data from %s", card_filename.c_str()); } else { @@ -809,8 +809,8 @@ void Client::load_all_files() { if (!this->system_data || (!this->character_data && (this->bb_character_index >= 0)) || !this->guild_card_data) { string nsa_filename = this->legacy_account_filename(); shared_ptr nsa_data; - if (isfile(nsa_filename)) { - nsa_data = make_shared(load_object_file(nsa_filename)); + if (phosg::isfile(nsa_filename)) { + nsa_data = make_shared(phosg::load_object_file(nsa_filename)); if (!nsa_data->signature.eq(LegacySavedAccountDataBB::SIGNATURE)) { throw runtime_error("account data header is incorrect"); } @@ -839,7 +839,7 @@ void Client::load_all_files() { if (!this->character_data && (this->bb_character_index >= 0)) { string nsc_filename = this->legacy_player_filename(); - auto nsc_data = load_object_file(nsc_filename); + auto nsc_data = phosg::load_object_file(nsc_filename); if (nsc_data.signature == LegacySavedPlayerDataBB::SIGNATURE_V0) { nsc_data.signature = LegacySavedPlayerDataBB::SIGNATURE_V0; nsc_data.unused.clear(); @@ -895,7 +895,7 @@ void Client::load_all_files() { this->character_data->disp.name.clear_after_bytes(0x18); this->login->account->auto_reply_message = this->character_data->auto_reply.decode(); this->login->account->save(); - this->last_play_time_update = now(); + this->last_play_time_update = phosg::now(); } } @@ -920,7 +920,7 @@ void Client::save_all() { } if (this->external_bank) { string filename = this->shared_bank_filename(); - save_object_file(filename, *this->external_bank); + phosg::save_object_file(filename, *this->external_bank); player_data_log.info("Saved shared bank file %s", filename.c_str()); } if (this->external_bank_character) { @@ -936,7 +936,7 @@ void Client::save_system_file() const { throw logic_error("no system file loaded"); } string filename = this->system_filename(); - save_object_file(filename, *this->system_data); + phosg::save_object_file(filename, *this->system_data); player_data_log.info("Saved system file %s", filename.c_str()); } @@ -944,11 +944,11 @@ void Client::save_character_file( const string& filename, shared_ptr system, shared_ptr character) { - auto f = fopen_unique(filename, "wb"); + auto f = phosg::fopen_unique(filename, "wb"); PSOCommandHeaderBB header = {sizeof(PSOCommandHeaderBB) + sizeof(PSOBBCharacterFile) + sizeof(PSOBBBaseSystemFile) + sizeof(PSOBBTeamMembership), 0x00E7, 0x00000000}; - fwritex(f.get(), header); - fwritex(f.get(), *character); - fwritex(f.get(), *system); + phosg::fwritex(f.get(), header); + phosg::fwritex(f.get(), *character); + phosg::fwritex(f.get(), *system); // TODO: Technically, we should write the actual team membership struct to the // file here, but that would cause Client to depend on Account, which // it currently does not. This data doesn't matter at all for correctness @@ -960,14 +960,14 @@ void Client::save_character_file( // of teams with a different set of team IDs anyway, so the membership struct // here would be useless either way. static const PSOBBTeamMembership empty_membership; - fwritex(f.get(), empty_membership); + phosg::fwritex(f.get(), empty_membership); player_data_log.info("Saved character file %s", filename.c_str()); } void Client::save_ep3_character_file( const string& filename, const PSOGCEp3CharacterFile::Character& character) { - save_file(filename, &character, sizeof(character)); + phosg::save_file(filename, &character, sizeof(character)); player_data_log.info("Saved Episode 3 character file %s", filename.c_str()); } @@ -981,7 +981,7 @@ void Client::save_character_file() { if (this->should_update_play_time) { // This is slightly inaccurate, since fractions of a second are truncated // off each time we save. I'm lazy, so insert shrug emoji here. - uint64_t t = now(); + uint64_t t = phosg::now(); uint64_t seconds = (t - this->last_play_time_update) / 1000000; this->character_data->play_time_seconds += seconds; player_data_log.info("Added %" PRIu64 " seconds to play time", seconds); @@ -996,14 +996,14 @@ void Client::save_guild_card_file() const { throw logic_error("no Guild Card file loaded"); } string filename = this->guild_card_filename(); - save_object_file(filename, *this->guild_card_data); + phosg::save_object_file(filename, *this->guild_card_data); player_data_log.info("Saved Guild Card file %s", filename.c_str()); } void Client::load_backup_character(uint32_t account_id, size_t index) { string filename = this->backup_character_filename(account_id, index, false); - auto f = fopen_unique(filename, "rb"); - auto header = freadx(f.get()); + auto f = phosg::fopen_unique(filename, "rb"); + auto header = phosg::freadx(f.get()); if (header.size != 0x399C) { throw runtime_error("incorrect size in character file header"); } @@ -1013,14 +1013,14 @@ void Client::load_backup_character(uint32_t account_id, size_t index) { if (header.flag != 0x00000000) { throw runtime_error("incorrect flag in character file header"); } - this->character_data = make_shared(freadx(f.get())); + this->character_data = make_shared(phosg::freadx(f.get())); this->update_character_data_after_load(this->character_data); this->v1_v2_last_reported_disp.reset(); } shared_ptr Client::load_ep3_backup_character(uint32_t account_id, size_t index) { string filename = this->backup_character_filename(account_id, index, true); - auto ch = make_shared(load_object_file(filename)); + auto ch = make_shared(phosg::load_object_file(filename)); this->character_data = PSOBBCharacterFile::create_from_ep3(*ch); this->ep3_config = make_shared(ch->ep3_config); this->update_character_data_after_load(this->character_data); @@ -1052,7 +1052,7 @@ std::shared_ptr Client::current_bank_character() { void Client::use_default_bank() { if (this->external_bank) { string filename = this->shared_bank_filename(); - save_object_file(filename, *this->external_bank); + phosg::save_object_file(filename, *this->external_bank); this->external_bank.reset(); player_data_log.info("Detached shared bank %s", filename.c_str()); } @@ -1073,8 +1073,8 @@ bool Client::use_shared_bank() { if (this->external_bank) { player_data_log.info("Using loaded shared bank %s", filename.c_str()); return true; - } else if (isfile(filename)) { - this->external_bank = make_shared(load_object_file(filename)); + } else if (phosg::isfile(filename)) { + this->external_bank = make_shared(phosg::load_object_file(filename)); files_manager->set_bank(filename, this->external_bank); player_data_log.info("Loaded shared bank %s", filename.c_str()); return true; @@ -1096,9 +1096,9 @@ void Client::use_character_bank(int8_t index) { if (this->external_bank_character) { this->external_bank_character_index = index; player_data_log.info("Using loaded character file %s for external bank", filename.c_str()); - } else if (isfile(filename)) { - auto f = fopen_unique(filename, "rb"); - auto header = freadx(f.get()); + } else if (phosg::isfile(filename)) { + auto f = phosg::fopen_unique(filename, "rb"); + auto header = phosg::freadx(f.get()); if (header.size != 0x399C) { throw runtime_error("incorrect size in character file header"); } @@ -1108,7 +1108,7 @@ void Client::use_character_bank(int8_t index) { if (header.flag != 0x00000000) { throw runtime_error("incorrect flag in character file header"); } - this->external_bank_character = make_shared(freadx(f.get())); + this->external_bank_character = make_shared(phosg::freadx(f.get())); this->update_character_data_after_load(this->external_bank_character); this->external_bank_character_index = index; files_manager->set_character(filename, this->external_bank_character); diff --git a/src/Client.hh b/src/Client.hh index 7c17ef41..dabbe334 100644 --- a/src/Client.hh +++ b/src/Client.hh @@ -147,7 +147,7 @@ public: template void parse_from(const parray& data) { - StringReader r(data.data(), data.size()); + phosg::StringReader r(data.data(), data.size()); if (r.get_u32l() != CLIENT_CONFIG_MAGIC) { throw std::invalid_argument("config signature is incorrect"); } @@ -163,7 +163,7 @@ public: template void serialize_into(parray& data) const { - StringWriter w; + phosg::StringWriter w; w.put_u32l(CLIENT_CONFIG_MAGIC); w.put_u32l(this->specific_version); w.put_u64l(this->enabled_flags & static_cast(Flag::CLIENT_SIDE_MASK)); @@ -184,7 +184,7 @@ public: std::weak_ptr server; uint64_t id; - PrefixedLogger log; + phosg::PrefixedLogger log; std::shared_ptr login; diff --git a/src/CommandFormats.hh b/src/CommandFormats.hh index e2dc8ddb..1ac0300e 100644 --- a/src/CommandFormats.hh +++ b/src/CommandFormats.hh @@ -2228,10 +2228,9 @@ struct S_ExecuteCode_B2 { // The code immediately follows, ending with an S_ExecuteCode_Footer_B2 } __packed_ws__(S_ExecuteCode_B2, 0x0C); -template +template struct S_ExecuteCode_FooterT_B2 { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; + static constexpr bool IsBE = BE; // Needed by generate_client_command_t // Relocations is a list of words (le_uint16_t on DC/PC/XB/BB, be_uint16_t on // GC) containing the number of doublewords (uint32_t) to skip for each @@ -2251,14 +2250,14 @@ struct S_ExecuteCode_FooterT_B2 { // relocations_offset points there, so those 12 bytes may also be omitted from // the command entirely (without changing code_size - so code_size would // technically extend beyond the end of the B2 command). - U32T relocations_offset = 0; // Relative to code base (after checksum_size) - U32T num_relocations = 0; - parray unused1; + U32T relocations_offset = 0; // Relative to code base (after checksum_size) + U32T num_relocations = 0; + parray, 2> unused1; // entrypoint_offset is doubly indirect - it points to a pointer to a 32-bit // value that itself is the actual entrypoint. This is presumably done so the // entrypoint can be optionally relocated. - U32T entrypoint_addr_offset = 0; // Relative to code base (after checksum_size). - parray unused2; + U32T entrypoint_addr_offset = 0; // Relative to code base (after checksum_size). + parray, 3> unused2; } __packed__; using S_ExecuteCode_Footer_GC_B2 = S_ExecuteCode_FooterT_B2; using S_ExecuteCode_Footer_DC_PC_XB_BB_B2 = S_ExecuteCode_FooterT_B2; @@ -3951,7 +3950,7 @@ struct G_Unknown_6x09 { // 6x0A: Update enemy state -template +template struct G_UpdateEnemyStateT_6x0A { G_EnemyIDHeader header; le_uint16_t enemy_index = 0; // [0, 0xB50) @@ -3959,7 +3958,7 @@ struct G_UpdateEnemyStateT_6x0A { // Flags: // 00000400 - should play hit animation // 00000800 - is dead - typename std::conditional_t flags = 0; + typename std::conditional_t flags = 0; } __packed__; using G_UpdateEnemyState_GC_6x0A = G_UpdateEnemyStateT_6x0A; using G_UpdateEnemyState_DC_PC_XB_BB_6x0A = G_UpdateEnemyStateT_6x0A; @@ -4005,15 +4004,14 @@ struct G_Unknown_6x10_6x11_6x12_6x14 { // 6x12: Dragon boss actions (not valid on Episode 3) -template +template struct G_DragonBossActionsT_6x12 { - using F32T = typename std::conditional::type; G_EnemyIDHeader header; le_uint16_t unknown_a2 = 0; le_uint16_t unknown_a3 = 0; le_uint32_t unknown_a4 = 0; - F32T x = 0.0f; - F32T z = 0.0f; + F32T x = 0.0f; + F32T z = 0.0f; } __packed__; using G_DragonBossActions_DC_PC_XB_BB_6x12 = G_DragonBossActionsT_6x12; using G_DragonBossActions_GC_6x12 = G_DragonBossActionsT_6x12; @@ -5043,12 +5041,11 @@ struct G_ExitQuest_6x73 { // There is a bug in PSO GC with regard to this command: the client does not // byteswap the header, which means the client_id field is big-endian. -template +template struct G_WordSelectT_6x74 { - using U16T = typename std::conditional::type; uint8_t subcommand = 0; uint8_t size = 0; - U16T client_id = 0; + U16T client_id = 0; WordSelectMessage message; } __packed__; using G_WordSelect_6x74 = G_WordSelectT_6x74; @@ -5170,14 +5167,12 @@ struct G_SetBattleModeData_6x7D { // 6x7F: Battle scores and places (not valid on Episode 3) -template +template struct G_BattleScoresT_6x7F { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; struct Entry { - U16T client_id = 0; - U16T place = 0; - U32T score = 0; + U16T client_id = 0; + U16T place = 0; + U32T score = 0; } __packed_ws__(Entry, 8); G_UnusedHeader header; parray entries; @@ -5513,15 +5508,14 @@ struct G_ModifyTradeProposal_6xA6 { // 6xA8: Gol Dragon boss actions (not valid on pre-V3 or Episode 3) -template +template struct G_GolDragonBossActionsT_6xA8 { - using F32T = typename std::conditional::type; G_EnemyIDHeader header; le_uint16_t unknown_a2 = 0; le_uint16_t unknown_a3 = 0; le_uint32_t unknown_a4 = 0; - F32T x = 0.0f; - F32T z = 0.0f; + F32T x = 0.0f; + F32T z = 0.0f; uint8_t unknown_a5 = 0; parray unused; } __packed__; diff --git a/src/CommonItemSet.cc b/src/CommonItemSet.cc index 69608418..5722b036 100644 --- a/src/CommonItemSet.cc +++ b/src/CommonItemSet.cc @@ -4,12 +4,13 @@ #include "EnemyType.hh" #include "GSLArchive.hh" #include "StaticGameData.hh" +#include "Types.hh" using namespace std; template -JSON to_json(const parray& v) { - auto ret = JSON::list(); +phosg::JSON to_json(const parray& v) { + auto ret = phosg::JSON::list(); for (size_t z = 0; z < Count; z++) { ret.emplace_back(v[z]); } @@ -17,7 +18,7 @@ JSON to_json(const parray& v) { } template -void from_json_into(const JSON& json, parray& ret) { +void from_json_into(const phosg::JSON& json, parray& ret) { if (json.size() != Count) { throw runtime_error("incorrect array length"); } @@ -27,8 +28,8 @@ void from_json_into(const JSON& json, parray& ret) { } template -JSON to_json(const parray, Count>& v) { - auto ret = JSON::list(); +phosg::JSON to_json(const parray, Count>& v) { + auto ret = phosg::JSON::list(); for (size_t z = 0; z < Count; z++) { ret.emplace_back(to_json(v[z])); } @@ -36,7 +37,7 @@ JSON to_json(const parray, Count>& v) { } template -void from_json_into(const JSON& json, parray, Count>& ret) { +void from_json_into(const phosg::JSON& json, parray, Count>& ret) { if (json.size() != Count) { throw runtime_error("incorrect array length"); } @@ -46,16 +47,16 @@ void from_json_into(const JSON& json, parray, } template -JSON to_json(const CommonItemSet::Table::Range& v) { +phosg::JSON to_json(const CommonItemSet::Table::Range& v) { if (v.min == v.max) { - return JSON(v.min); + return phosg::JSON(v.min); } else { - return JSON::list({v.min, v.max}); + return phosg::JSON::list({v.min, v.max}); } } template -void from_json_into(const JSON& json, CommonItemSet::Table::Range& ret) { +void from_json_into(const phosg::JSON& json, CommonItemSet::Table::Range& ret) { if (json.is_int()) { IntT v = json.as_int(); ret.min = v; @@ -71,8 +72,8 @@ void from_json_into(const JSON& json, CommonItemSet::Table::Range& ret) { } template -JSON to_json(const parray, Count1>& v) { - auto ret = JSON::list(); +phosg::JSON to_json(const parray, Count1>& v) { + auto ret = phosg::JSON::list(); for (size_t z = 0; z < Count1; z++) { ret.emplace_back(to_json(v[z])); } @@ -80,7 +81,7 @@ JSON to_json(const parray, Count1>& v) { } template -void from_json_into(const JSON& json, parray, Count1>& ret) { +void from_json_into(const phosg::JSON& json, parray, Count1>& ret) { if (json.size() != Count1) { throw runtime_error("incorrect array length"); } @@ -90,7 +91,7 @@ void from_json_into(const JSON& json, parray, Count1>& ret) } template -void from_json_into(const JSON& json, parray, Count2>, Count1>& ret) { +void from_json_into(const phosg::JSON& json, parray, Count2>, Count1>& ret) { if (json.size() != Count1) { throw runtime_error("incorrect array length"); } @@ -99,7 +100,7 @@ void from_json_into(const JSON& json, parraybase_weapon_type_prob_table); from_json_into(json.at("SubtypeBaseTable"), this->subtype_base_table); @@ -128,7 +129,7 @@ CommonItemSet::Table::Table(const JSON& json, Episode episode) static const array episodes = {Episode::EP1, Episode::EP2, Episode::EP4}; for (Episode episode : episodes) { for (auto type : enemy_types_for_rare_table_index(episode, z)) { - string name = string_printf("%s:%s", abbreviation_for_episode(episode), name_for_enum(type)); + string name = phosg::string_printf("%s:%s", abbreviation_for_episode(episode), phosg::name_for_enum(type)); from_json_into(*enemy_meseta_ranges_json.at(name), this->enemy_meseta_ranges[z]); this->enemy_type_drop_probs[z] = enemy_type_drop_probs_json.at(name)->as_int(); this->enemy_item_classes[z] = enemy_item_classes_json.at(name)->as_int(); @@ -170,7 +171,7 @@ void CommonItemSet::Table::print(FILE* stream) const { if (!enemies_str.empty()) { enemies_str += ", "; } - enemies_str += name_for_enum(enemy_type); + enemies_str += phosg::name_for_enum(enemy_type); } if (drop_probs[z]) { fprintf(stream, " %02zX %5hu %5hu %3hhu%% %02hX:%s %s\n", @@ -335,22 +336,22 @@ void CommonItemSet::Table::print(FILE* stream) const { } } -JSON CommonItemSet::Table::json() const { - JSON enemy_meseta_ranges_json = JSON::dict(); - JSON enemy_type_drop_probs_json = JSON::dict(); - JSON enemy_item_classes_json = JSON::dict(); +phosg::JSON CommonItemSet::Table::json() const { + phosg::JSON enemy_meseta_ranges_json = phosg::JSON::dict(); + phosg::JSON enemy_type_drop_probs_json = phosg::JSON::dict(); + phosg::JSON enemy_item_classes_json = phosg::JSON::dict(); for (size_t z = 0; z < 0x64; z++) { static const array episodes = {Episode::EP1, Episode::EP2, Episode::EP4}; for (Episode episode : episodes) { for (auto type : enemy_types_for_rare_table_index(episode, z)) { - string name = string_printf("%s:%s", abbreviation_for_episode(episode), name_for_enum(type)); + string name = phosg::string_printf("%s:%s", abbreviation_for_episode(episode), phosg::name_for_enum(type)); enemy_meseta_ranges_json.emplace(name, to_json(this->enemy_meseta_ranges[z])); enemy_type_drop_probs_json.emplace(name, this->enemy_type_drop_probs[z]); enemy_item_classes_json.emplace(name, this->enemy_item_classes[z]); } } } - return JSON::dict({ + return phosg::JSON::dict({ {"BaseWeaponTypeProbTable", to_json(this->base_weapon_type_prob_table)}, {"SubtypeBaseTable", to_json(this->subtype_base_table)}, {"SubtypeAreaLengthTable", to_json(this->subtype_area_length_table)}, @@ -376,16 +377,16 @@ JSON CommonItemSet::Table::json() const { }); } -JSON CommonItemSet::json() const { - auto modes_dict = JSON::dict(); +phosg::JSON CommonItemSet::json() const { + auto modes_dict = phosg::JSON::dict(); static const array modes = {GameMode::NORMAL, GameMode::BATTLE, GameMode::CHALLENGE, GameMode::SOLO}; for (const auto& mode : modes) { - auto episodes_dict = JSON::dict(); + auto episodes_dict = phosg::JSON::dict(); static const array episodes = {Episode::EP1, Episode::EP2, Episode::EP4}; for (const auto& episode : episodes) { - auto difficulty_dict = JSON::dict(); + auto difficulty_dict = phosg::JSON::dict(); for (uint8_t difficulty = 0; difficulty < 4; difficulty++) { - auto section_id_dict = JSON::dict(); + auto section_id_dict = phosg::JSON::dict(); for (uint8_t section_id = 0; section_id < 10; section_id++) { try { auto table = this->get_table(episode, mode, difficulty, section_id); @@ -423,7 +424,7 @@ void CommonItemSet::print(FILE* stream) const { } } -CommonItemSet::Table::Table(const StringReader& r, bool is_big_endian, bool is_v3, Episode episode) +CommonItemSet::Table::Table(const phosg::StringReader& r, bool is_big_endian, bool is_v3, Episode episode) : episode(episode) { if (is_big_endian) { this->parse_itempt_t(r, is_v3); @@ -432,12 +433,9 @@ CommonItemSet::Table::Table(const StringReader& r, bool is_big_endian, bool is_v } } -template -void CommonItemSet::Table::parse_itempt_t(const StringReader& r, bool is_v3) { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; - - const auto& offsets = r.pget>(r.pget(r.size() - 0x10)); +template +void CommonItemSet::Table::parse_itempt_t(const phosg::StringReader& r, bool is_v3) { + const auto& offsets = r.pget>(r.pget>(r.size() - 0x10)); this->base_weapon_type_prob_table = r.pget>(offsets.base_weapon_type_prob_table_offset); this->subtype_base_table = r.pget>(offsets.subtype_base_table_offset); @@ -445,14 +443,14 @@ void CommonItemSet::Table::parse_itempt_t(const StringReader& r, bool is_v3) { this->grind_prob_table = r.pget, 9>>(offsets.grind_prob_table_offset); this->armor_shield_type_index_prob_table = r.pget>(offsets.armor_shield_type_index_prob_table_offset); this->armor_slot_count_prob_table = r.pget>(offsets.armor_slot_count_prob_table_offset); - const auto& data = r.pget, 0x64>>(offsets.enemy_meseta_ranges_offset); + const auto& data = r.pget>, 0x64>>(offsets.enemy_meseta_ranges_offset); for (size_t z = 0; z < data.size(); z++) { this->enemy_meseta_ranges[z] = Range{data[z].min, data[z].max}; } this->enemy_type_drop_probs = r.pget>(offsets.enemy_type_drop_probs_offset); this->enemy_item_classes = r.pget>(offsets.enemy_item_classes_offset); { - const auto& data = r.pget, 0x0A>>(offsets.box_meseta_ranges_offset); + const auto& data = r.pget>, 0x0A>>(offsets.box_meseta_ranges_offset); for (size_t z = 0; z < data.size(); z++) { this->box_meseta_ranges[z] = Range{data[z].min, data[z].max}; } @@ -466,7 +464,7 @@ void CommonItemSet::Table::parse_itempt_t(const StringReader& r, bool is_v3) { } } } else { // V3 - const auto& data = r.pget, 0x17>>(offsets.bonus_value_prob_table_offset); + const auto& data = r.pget, 6>, 0x17>>(offsets.bonus_value_prob_table_offset); for (size_t z = 0; z < data.size(); z++) { for (size_t x = 0; x < data[z].size(); x++) { this->bonus_value_prob_table[z][x] = data[z][x]; @@ -478,7 +476,7 @@ void CommonItemSet::Table::parse_itempt_t(const StringReader& r, bool is_v3) { this->special_mult = r.pget>(offsets.special_mult_offset); this->special_percent = r.pget>(offsets.special_percent_offset); { - const auto& data = r.pget, 0x1C>>(offsets.tool_class_prob_table_offset); + const auto& data = r.pget, 0x0A>, 0x1C>>(offsets.tool_class_prob_table_offset); for (size_t z = 0; z < data.size(); z++) { for (size_t x = 0; x < data[z].size(); x++) { this->tool_class_prob_table[z][x] = data[z][x]; @@ -505,7 +503,7 @@ shared_ptr CommonItemSet::get_table( try { return this->tables.at(this->key_for_table(episode, mode, difficulty, secid)); } catch (const out_of_range&) { - throw runtime_error(string_printf("common item table not available for episode=%s, mode=%s, difficulty=%hu, secid=%hu", + throw runtime_error(phosg::string_printf("common item table not available for episode=%s, mode=%s, difficulty=%hu, secid=%hu", name_for_episode(episode), name_for_mode(mode), difficulty, secid)); } } @@ -518,7 +516,7 @@ AFSV2CommonItemSet::AFSV2CommonItemSet( for (size_t difficulty = 0; difficulty < 4; difficulty++) { for (size_t section_id = 0; section_id < 10; section_id++) { auto entry = pt_afs.get(difficulty * 10 + section_id); - StringReader r(entry.first, entry.second); + phosg::StringReader r(entry.first, entry.second); auto table = make_shared(r, false, false, Episode::EP1); this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::NORMAL, difficulty, section_id), table); this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::BATTLE, difficulty, section_id), table); @@ -556,7 +554,7 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr gs default: throw runtime_error("invalid episode"); } - return string_printf( + return phosg::string_printf( "ItemPT%s%s%c%1hhu.rel", is_challenge ? "c" : "", episode_token, @@ -568,7 +566,7 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr gs for (Episode episode : episodes) { for (size_t difficulty = 0; difficulty < 4; difficulty++) { for (size_t section_id = 0; section_id < 10; section_id++) { - StringReader r; + phosg::StringReader r; try { r = gsl.get_reader(filename_for_table(episode, difficulty, section_id, false)); } catch (const exception&) { @@ -602,7 +600,7 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr gs } } -JSONCommonItemSet::JSONCommonItemSet(const JSON& json) { +JSONCommonItemSet::JSONCommonItemSet(const phosg::JSON& json) { for (const auto& mode_it : json.as_dict()) { static const unordered_map mode_keys( {{"Normal", GameMode::NORMAL}, {"Battle", GameMode::BATTLE}, {"Challenge", GameMode::CHALLENGE}, {"Solo", GameMode::SOLO}}); @@ -791,7 +789,7 @@ const ProbabilityTable& TekkerAdjustmentSet::get_bonus_delta_prob_ } int8_t TekkerAdjustmentSet::get_luck(uint32_t start_offset, uint8_t delta_index) const { - StringReader sub_r = r.sub(start_offset); + phosg::StringReader sub_r = r.sub(start_offset); while (!sub_r.eof()) { const auto& entry = sub_r.get(); if (entry.delta_index == 0xFF) { diff --git a/src/CommonItemSet.hh b/src/CommonItemSet.hh index cf840dea..98fdf525 100644 --- a/src/CommonItemSet.hh +++ b/src/CommonItemSet.hh @@ -8,14 +8,15 @@ #include "PSOEncryption.hh" #include "StaticGameData.hh" #include "Text.hh" +#include "Types.hh" class CommonItemSet { public: class Table { public: Table() = delete; - Table(const JSON& json, Episode episode); - Table(const StringReader& r, bool big_endian, bool is_v3, Episode episode); + Table(const phosg::JSON& json, Episode episode); + Table(const phosg::StringReader& r, bool big_endian, bool is_v3, Episode episode); template struct Range { @@ -47,18 +48,15 @@ public: parray unit_max_stars_table; parray, 7> box_item_class_prob_table; - JSON json() const; + phosg::JSON json() const; void print(FILE* stream) const; private: - template - void parse_itempt_t(const StringReader& r, bool is_v3); + template + void parse_itempt_t(const phosg::StringReader& r, bool is_v3); - template + template struct OffsetsT { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; - // This data structure uses index probability tables in multiple places. An // index probability table is a table where each entry holds the probability // that that entry's index is used. For example, if the armor slot count @@ -80,7 +78,7 @@ public: // The indexes in this table correspond to the non-rare weapon types 01 // through 0C (Saber through Wand). // V2/V3: -> parray - /* 00 */ U32T base_weapon_type_prob_table_offset; + /* 00 */ U32T base_weapon_type_prob_table_offset; // This table specifies the base subtype for each weapon type. Negative // values here mean that the weapon cannot be found in the first N areas (so @@ -90,7 +88,7 @@ public: // of weapon that actually appears depends on this value and a value from // the following table. // V2/V3: -> parray - /* 04 */ U32T subtype_base_table_offset; + /* 04 */ U32T subtype_base_table_offset; // This table specifies how many areas each weapon subtype appears in. For // example, if Sword (subtype 02, which is index 1 in this table and the @@ -99,7 +97,7 @@ public: // through Mine 1), and Gigush (the next sword subtype) can be found in Mine // 1 through Ruins 3. // V2/V3: -> parray - /* 08 */ U32T subtype_area_length_table_offset; + /* 08 */ U32T subtype_area_length_table_offset; // This index probability table specifies how likely each possible grind // value is. The table is indexed as [grind][subtype_area_index], where the @@ -114,28 +112,28 @@ public: // ... // C1 C2 C3 M1 // (Episode 1 area values from the example for reference) // V2/V3: -> parray, 9> - /* 0C */ U32T grind_prob_table_offset; + /* 0C */ U32T grind_prob_table_offset; // TODO: Figure out exactly how this table is used. Anchor: 80106D34 // V2/V3: -> parray - /* 10 */ U32T armor_shield_type_index_prob_table_offset; + /* 10 */ U32T armor_shield_type_index_prob_table_offset; // This index probability table specifies how common each possible slot // count is for armor drops. // V2/V3: -> parray - /* 14 */ U32T armor_slot_count_prob_table_offset; + /* 14 */ U32T armor_slot_count_prob_table_offset; // This array (indexed by enemy_type) specifies the range of meseta values // that each enemy can drop. // V2/V3: -> parray, 0x64> - /* 18 */ U32T enemy_meseta_ranges_offset; + /* 18 */ U32T enemy_meseta_ranges_offset; // Each byte in this table (indexed by enemy_type) represents the percent // chance that the enemy drops anything at all. (This check is done before // the rare drop check, so the chance of getting a rare item from an enemy // is essentially this probability multiplied by the rare drop rate.) // V2/V3: -> parray - /* 1C */ U32T enemy_type_drop_probs_offset; + /* 1C */ U32T enemy_type_drop_probs_offset; // Each byte in this table (indexed by enemy_type) represents the class of // item that the enemy can drop. The values are: @@ -147,12 +145,12 @@ public: // 05 = meseta // Anything else = no item // V2/V3: -> parray - /* 20 */ U32T enemy_item_classes_offset; + /* 20 */ U32T enemy_item_classes_offset; // This table (indexed by area - 1) specifies the ranges of meseta values // that can drop from boxes. // V2/V3: -> parray, 0x0A> - /* 24 */ U32T box_meseta_ranges_offset; + /* 24 */ U32T box_meseta_ranges_offset; // This array specifies the chance that a rare weapon will have each // possible bonus value. This is indexed as [(bonus_value - 10 / 5)][spec], @@ -162,7 +160,7 @@ public: // for rare items, spec is always 5. // V2: -> parray, 0x17> // V3: -> parray, 0x17> - /* 28 */ U32T bonus_value_prob_table_offset; + /* 28 */ U32T bonus_value_prob_table_offset; // This array specifies the value of spec to be used in the above lookup for // non-rare items. This is NOT an index probability table; this is a direct @@ -178,7 +176,7 @@ public: // bonus; in all other areas except Ruins 3, they can have at most two // bonuses, and in Ruins 3, they can have up to three bonuses. // V2/V3: // -> parray, 3> - /* 2C */ U32T nonrare_bonus_prob_spec_offset; + /* 2C */ U32T nonrare_bonus_prob_spec_offset; // This array specifies the chance that a weapon will have each bonus type. // The table is indexed as [bonus_type][area - 1] for non-rare items; for @@ -193,37 +191,37 @@ public: // [00 00 00 00 00 01 01 01 01 01] // Chance of getting Hit bonus // F1 F2 C1 C2 C3 M1 M2 R1 R2 R3 // (Episode 1 areas, for reference) // V2/V3: -> parray, 6> - /* 30 */ U32T bonus_type_prob_table_offset; + /* 30 */ U32T bonus_type_prob_table_offset; // This array (indexed by area - 1) specifies a multiplier of used in // special ability determination. It seems this uses the star values from // ItemPMT, but not yet clear exactly in what way. // TODO: Figure out exactly what this does. Anchor: 80106FEC // V2/V3: -> parray - /* 34 */ U32T special_mult_offset; + /* 34 */ U32T special_mult_offset; // This array (indexed by area - 1) specifies the probability that any // non-rare weapon will have a special ability. // V2/V3: -> parray - /* 38 */ U32T special_percent_offset; + /* 38 */ U32T special_percent_offset; // This index probability table is indexed by [tool_class][area - 1]. The // tool class refers to an entry in ItemPMT, which links it to the actual // item code. // V2/V3: -> parray, 0x1C> - /* 3C */ U32T tool_class_prob_table_offset; + /* 3C */ U32T tool_class_prob_table_offset; // This index probability table determines how likely each technique is to // appear. The table is indexed as [technique_num][area - 1]. // V2/V3: -> parray, 0x13> - /* 40 */ U32T technique_index_prob_table_offset; + /* 40 */ U32T technique_index_prob_table_offset; // This table specifies the ranges for technique disk levels. The table is // indexed as [technique_num][area - 1]. If either min or max in the range // is 0xFF, or if max < min, technique disks are not dropped for that // technique and area pair. // V2/V3: -> parray, 0x0A>, 0x13> - /* 44 */ U32T technique_level_ranges_offset; + /* 44 */ U32T technique_level_ranges_offset; /* 48 */ uint8_t armor_or_shield_type_bias; /* 49 */ parray unused1; @@ -234,7 +232,7 @@ public: // game uniformly chooses a random number of stars in the acceptable // range, then uniformly chooses a random unit with that many stars. // V2/V3: -> parray - /* 4C */ U32T unit_max_stars_offset; + /* 4C */ U32T unit_max_stars_offset; // This index probability table determines which type of items drop from // boxes. The table is indexed as [item_class][area - 1], with item_class @@ -253,7 +251,7 @@ public: // [16 16 11 11 11 11 11 0F 0C 0B] // Chances per area of an empty box // F1 F2 C1 C2 C3 M1 M2 R1 R2 R3 // (Episode 1 areas, for reference) // V2/V3: -> parray, 7> - /* 50 */ U32T box_item_class_prob_table_offset; + /* 50 */ U32T box_item_class_prob_table_offset; // There are several unused fields here. } __packed__; @@ -264,7 +262,7 @@ public: }; std::shared_ptr get_table(Episode episode, GameMode mode, uint8_t difficulty, uint8_t secid) const; - JSON json() const; + phosg::JSON json() const; void print(FILE* stream) const; protected: @@ -287,7 +285,7 @@ public: class JSONCommonItemSet : public CommonItemSet { public: - explicit JSONCommonItemSet(const JSON& json); + explicit JSONCommonItemSet(const phosg::JSON& json); }; // Note: There are clearly better ways of doing this, but this implementation @@ -348,7 +346,7 @@ public: protected: std::shared_ptr data; - StringReader r; + phosg::StringReader r; struct TableSpec { be_uint32_t offset; @@ -463,7 +461,7 @@ private: int8_t get_luck(uint32_t start_offset, uint8_t delta_index) const; std::shared_ptr data; - StringReader r; + phosg::StringReader r; struct DeltaProbabilityEntry { uint8_t delta_index; diff --git a/src/Compression.cc b/src/Compression.cc index 6bfc4c37..24a5b4b7 100644 --- a/src/Compression.cc +++ b/src/Compression.cc @@ -14,7 +14,7 @@ using namespace std; template <> -const char* name_for_enum(CompressPhase v) { +const char* phosg::name_for_enum(CompressPhase v) { switch (v) { case CompressPhase::INDEX: return "INDEX"; @@ -118,7 +118,7 @@ struct WindowIndex { }; struct LZSSInterleavedWriter { - StringWriter w; + phosg::StringWriter w; size_t buf_offset; uint8_t next_control_bit; uint8_t buf[0x19]; @@ -166,7 +166,7 @@ struct LZSSInterleavedWriter { class ControlStreamReader { public: - ControlStreamReader(StringReader& r) + ControlStreamReader(phosg::StringReader& r) : r(r), bits(0x0000) {} @@ -188,7 +188,7 @@ public: } private: - StringReader& r; + phosg::StringReader& r; uint16_t bits; }; @@ -493,7 +493,7 @@ void PRSCompressor::add(const void* data, size_t size) { throw logic_error("compressor is closed"); } - StringReader r(data, size); + phosg::StringReader r(data, size); while (!r.eof()) { this->add_byte(r.get_u8()); } @@ -874,8 +874,8 @@ PRSDecompressResult prs_decompress_with_meta( // is encountered partway through an opcode, we throw instead, because it's // likely the input has been truncated or is malformed in some way. - StringWriter w; - StringReader r(data, size); + phosg::StringWriter w; + phosg::StringReader r(data, size); ControlStreamReader cr(r); while (!r.eof()) { @@ -959,7 +959,7 @@ string prs_decompress(const string& data, size_t max_output_size, bool allow_unt size_t prs_decompress_size(const void* data, size_t size, size_t max_output_size, bool allow_unterminated) { size_t ret = 0; - StringReader r(data, size); + phosg::StringReader r(data, size); ControlStreamReader cr(r); while (!r.eof()) { @@ -1011,7 +1011,7 @@ size_t prs_decompress_size(const string& data, size_t max_output_size, bool allo void prs_disassemble(FILE* stream, const void* data, size_t size) { size_t output_bytes = 0; - StringReader r(data, size); + phosg::StringReader r(data, size); ControlStreamReader cr(r); while (!r.eof()) { @@ -1249,8 +1249,8 @@ string bc0_decompress(const string& data) { } string bc0_decompress(const void* data, size_t size) { - StringReader r(data, size); - StringWriter w; + phosg::StringReader r(data, size); + phosg::StringWriter w; // Unlike PRS, BC0 uses a memo which "rolls over" every 0x1000 bytes. The // boundaries of these "memo pages" are offset by -0x12 bytes for some reason, @@ -1322,7 +1322,7 @@ void bc0_disassemble(FILE* stream, const string& data) { } void bc0_disassemble(FILE* stream, const void* data, size_t size) { - StringReader r(data, size); + phosg::StringReader r(data, size); uint16_t control_stream_bits = 0x0000; size_t output_bytes = 0; diff --git a/src/Compression.hh b/src/Compression.hh index 55abe11a..6144f97c 100644 --- a/src/Compression.hh +++ b/src/Compression.hh @@ -18,7 +18,7 @@ enum class CompressPhase { }; template <> -const char* name_for_enum(CompressPhase v); +const char* phosg::name_for_enum(CompressPhase v); typedef std::function ProgressCallback; @@ -146,7 +146,7 @@ private: WrappedLog<0x101> forward_log; IndexedLog<0x2000> reverse_log; - StringWriter output; + phosg::StringWriter output; }; // These functions use PRSCompressor to compress a buffer of data. This is diff --git a/src/DCSerialNumbers.cc b/src/DCSerialNumbers.cc index c0fa5ee4..0c418f81 100644 --- a/src/DCSerialNumbers.cc +++ b/src/DCSerialNumbers.cc @@ -1174,7 +1174,7 @@ static uint64_t decode_dc_serial_number_str(const string& s) { if (new_ch == '\0') { return INVALID_PRODUCT; } - serial_number = (serial_number << 4) | value_for_hex_char(new_ch); + serial_number = (serial_number << 4) | phosg::value_for_hex_char(new_ch); } return serial_number; } @@ -1291,12 +1291,12 @@ string generate_dc_serial_number(uint8_t domain, uint8_t subdomain) { throw runtime_error("invalid domain"); } - size_t det1 = (subdomain == 0xFF) ? random_object() : subdomain; + size_t det1 = (subdomain == 0xFF) ? phosg::random_object() : subdomain; size_t index1 = offset1 + (det1 % (limit1 - offset1)); - size_t index2 = random_object() % (sizeof(primes2) / sizeof(primes2[0])); - size_t index3 = random_object() % (sizeof(primes3) / sizeof(primes3[0])); + size_t index2 = phosg::random_object() % (sizeof(primes2) / sizeof(primes2[0])); + size_t index3 = phosg::random_object() % (sizeof(primes3) / sizeof(primes3[0])); uint32_t value = primes1[index1] * primes2[index2] * primes3[index3]; - string s = string_printf("%08X", value); + string s = phosg::string_printf("%08X", value); string ret; for (char ch : s) { @@ -1355,7 +1355,7 @@ unordered_map generate_all_dc_serial_numbers(uint8_t domain, u } void dc_serial_number_speed_test(uint64_t seed) { - uint32_t effective_seed = (seed & 0xFFFFFFFF00000000) ? random_object() : seed; + uint32_t effective_seed = (seed & 0xFFFFFFFF00000000) ? phosg::random_object() : seed; fprintf(stderr, "Product speed test with seed=%08" PRIX32 "\n", effective_seed); PSOV2Encryption crypt(effective_seed); uint64_t time_slow = 0; @@ -1363,15 +1363,15 @@ void dc_serial_number_speed_test(uint64_t seed) { size_t num_disagreements = 0; static constexpr size_t count = 0x1000; for (size_t z = 0; z < count; z++) { - string s = string_printf("%08X", crypt.next()); + string s = phosg::string_printf("%08X", crypt.next()); - uint64_t start = now(); + uint64_t start = phosg::now(); bool is_valid_fast = dc_serial_number_is_valid_fast(s, 1, 0xFF); - time_fast += now() - start; + time_fast += phosg::now() - start; - start = now(); + start = phosg::now(); bool is_valid_slow = dc_serial_number_is_valid_slow(s, 1, 0xFF); - time_slow += now() - start; + time_slow += phosg::now() - start; if (((z & 0xF) == 0) || is_valid_slow || is_valid_fast) { fprintf(stderr, "... %02zX: %s => %s %s%s\n", z, s.c_str(), is_valid_slow ? "SLOW" : "----", is_valid_fast ? "FAST" : "----", is_valid_slow != is_valid_fast ? " !!!" : ""); @@ -1391,13 +1391,13 @@ string decrypt_dp_address_jpn( const string& executable, const string& values, const string& indexes) { - StringReader values_r(values); - StringReader indexes_r(indexes); + phosg::StringReader values_r(values); + phosg::StringReader indexes_r(indexes); size_t fixup_values_offset = values_r.pget_u32l(0x3FFC) - 0x8C004000; size_t fixup_steps_offset = indexes_r.pget_u32l(0x3BFC) - 0x8C008400; - StringReader fixup_values_r = values_r.sub(fixup_values_offset); - StringReader fixup_steps_r = indexes_r.sub(fixup_steps_offset); + phosg::StringReader fixup_values_r = values_r.sub(fixup_values_offset); + phosg::StringReader fixup_steps_r = indexes_r.sub(fixup_steps_offset); auto decrypted = decrypt_pr2_data(executable); size_t fixup_offset = 0; @@ -1417,9 +1417,9 @@ EncryptedDCv2Executables encrypt_dp_address_jpn(const string& executable, const EncryptedDCv2Executables ret; string compressed = prs_compress(executable); - ret.executable = encrypt_pr2_data(compressed, executable.size(), random_object() & 0x7FFFFF7F); + ret.executable = encrypt_pr2_data(compressed, executable.size(), phosg::random_object() & 0x7FFFFF7F); - StringReader indexes_r(indexes); + phosg::StringReader indexes_r(indexes); size_t fixup_steps_offset = indexes_r.pget_u32l(0x3BFC) - 0x8C008400; ret.indexes = indexes; ret.indexes.at(fixup_steps_offset) = 0; @@ -1431,7 +1431,7 @@ std::string crypt_dp_address_jpn_simple(const std::string& data, int64_t mask_ke throw runtime_error("size is not a multiple of 4"); } - StringReader r(data); + phosg::StringReader r(data); if (mask_key < 0) { unordered_map key_freq; while (!r.eof()) { @@ -1447,11 +1447,11 @@ std::string crypt_dp_address_jpn_simple(const std::string& data, int64_t mask_ke if (mask_key < 0) { throw runtime_error("cannot determine mask key"); } - log_info("Determined %08" PRIX64 " to be the most likely mask key", mask_key); + phosg::log_info("Determined %08" PRIX64 " to be the most likely mask key", mask_key); r.go(0); } - StringWriter w; + phosg::StringWriter w; while (!r.eof()) { w.put_u32l(r.get_u32l() ^ mask_key); } diff --git a/src/DNSServer.cc b/src/DNSServer.cc index 304bbdd0..eb4c8290 100644 --- a/src/DNSServer.cc +++ b/src/DNSServer.cc @@ -34,15 +34,15 @@ DNSServer::~DNSServer() { } void DNSServer::listen(const std::string& socket_path) { - this->add_socket(::listen(socket_path, 0, 0)); + this->add_socket(phosg::listen(socket_path, 0, 0)); } void DNSServer::listen(const std::string& addr, int port) { - this->add_socket(::listen(addr, port, 0)); + this->add_socket(phosg::listen(addr, port, 0)); } void DNSServer::listen(int port) { - this->add_socket(::listen("", port, 0)); + this->add_socket(phosg::listen("", port, 0)); } void DNSServer::add_socket(int fd) { @@ -66,7 +66,7 @@ string DNSServer::response_for_query(const void* vdata, size_t size, uint32_t re const char* data = reinterpret_cast(vdata); size_t name_len = strlen(&data[12]) + 1; - be_uint32_t be_resolved_address = resolved_address; + phosg::be_uint32_t be_resolved_address = resolved_address; string response; response.append(data, 2); @@ -104,7 +104,7 @@ void DNSServer::on_receive_message(int fd, short) { } else if (bytes < 0x0C) { dns_server_log.warning("input query too small"); - print_data(stderr, input.data(), bytes); + phosg::print_data(stderr, input.data(), bytes); } else if (!this->banned_ipv4_ranges->check(remote)) { input.resize(bytes); diff --git a/src/EnemyType.cc b/src/EnemyType.cc index d73d2c52..160e1642 100644 --- a/src/EnemyType.cc +++ b/src/EnemyType.cc @@ -10,7 +10,7 @@ using namespace std; template <> -const char* name_for_enum(EnemyType type) { +const char* phosg::name_for_enum(EnemyType type) { switch (type) { case EnemyType::UNKNOWN: return "UNKNOWN"; @@ -274,7 +274,7 @@ const char* name_for_enum(EnemyType type) { } template <> -EnemyType enum_for_name(const char* name) { +EnemyType phosg::enum_for_name(const char* name) { static const unordered_map names({ {"UNKNOWN", EnemyType::UNKNOWN}, {"NONE", EnemyType::NONE}, @@ -672,7 +672,7 @@ uint8_t battle_param_index_for_enemy_type(Episode episode, EnemyType enemy_type) case EnemyType::SO_DIMENIAN: return 0x55; default: - throw runtime_error(string_printf("%s does not have battle parameters in Episode 1", name_for_enum(enemy_type))); + throw runtime_error(phosg::string_printf("%s does not have battle parameters in Episode 1", phosg::name_for_enum(enemy_type))); } break; case Episode::EP2: @@ -787,7 +787,7 @@ uint8_t battle_param_index_for_enemy_type(Episode episode, EnemyType enemy_type) case EnemyType::SO_DIMENIAN: return 0x55; default: - throw runtime_error(string_printf("%s does not have battle parameters in Episode 2", name_for_enum(enemy_type))); + throw runtime_error(phosg::string_printf("%s does not have battle parameters in Episode 2", phosg::name_for_enum(enemy_type))); } break; case Episode::EP4: @@ -847,7 +847,7 @@ uint8_t battle_param_index_for_enemy_type(Episode episode, EnemyType enemy_type) case EnemyType::KONDRIEU: return 0x2A; default: - throw runtime_error(string_printf("%s does not have battle parameters in Episode 4", name_for_enum(enemy_type))); + throw runtime_error(phosg::string_printf("%s does not have battle parameters in Episode 4", phosg::name_for_enum(enemy_type))); } break; default: @@ -1072,7 +1072,7 @@ uint8_t rare_table_index_for_enemy_type(EnemyType enemy_type) { case EnemyType::ZU_ALT: return 0x4A; default: - throw runtime_error(string_printf("%s does not have a rare table entry", name_for_enum(enemy_type))); + throw runtime_error(phosg::string_printf("%s does not have a rare table entry", phosg::name_for_enum(enemy_type))); } } diff --git a/src/EnemyType.hh b/src/EnemyType.hh index 49f08d5d..72f58ffe 100644 --- a/src/EnemyType.hh +++ b/src/EnemyType.hh @@ -5,6 +5,7 @@ #include #include "StaticGameData.hh" +#include "Types.hh" enum class EnemyType { UNKNOWN = -1, @@ -138,9 +139,9 @@ enum class EnemyType { }; template <> -const char* name_for_enum(EnemyType type); +const char* phosg::name_for_enum(EnemyType type); template <> -EnemyType enum_for_name(const char* name); +EnemyType phosg::enum_for_name(const char* name); bool enemy_type_valid_for_episode(Episode episode, EnemyType enemy_type); uint8_t battle_param_index_for_enemy_type(Episode episode, EnemyType enemy_type); diff --git a/src/Episode3/BattleRecord.cc b/src/Episode3/BattleRecord.cc index ae1e9a2b..4112fc5d 100644 --- a/src/Episode3/BattleRecord.cc +++ b/src/Episode3/BattleRecord.cc @@ -12,10 +12,10 @@ namespace Episode3 { void BattleRecord::PlayerEntry::print(FILE* stream) const { // TODO: Format this nicely somehow. Maybe factor out the functions in // QuestScript that format some of these structures - print_data(stream, this, sizeof(*this), 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this, sizeof(*this), 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); } -BattleRecord::Event::Event(StringReader& r) { +BattleRecord::Event::Event(phosg::StringReader& r) { this->type = r.get(); this->timestamp = r.get_u64l(); switch (this->type) { @@ -46,7 +46,7 @@ BattleRecord::Event::Event(StringReader& r) { } } -void BattleRecord::Event::serialize(StringWriter& w) const { +void BattleRecord::Event::serialize(phosg::StringWriter& w) const { w.put(this->type); w.put_u64l(this->timestamp); switch (this->type) { @@ -81,7 +81,7 @@ void BattleRecord::Event::serialize(StringWriter& w) const { } void BattleRecord::Event::print(FILE* stream) const { - string time_str = format_time(this->timestamp); + string time_str = phosg::format_time(this->timestamp); fprintf(stream, "Event @%016" PRIX64 " (%s) ", this->timestamp, time_str.c_str()); switch (this->type) { case Type::PLAYER_JOIN: @@ -103,23 +103,23 @@ void BattleRecord::Event::print(FILE* stream) const { break; case Type::BATTLE_COMMAND: fprintf(stream, "BATTLE_COMMAND\n"); - print_data(stream, this->data, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); break; case Type::GAME_COMMAND: fprintf(stream, "GAME_COMMAND\n"); - print_data(stream, this->data, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); break; case Type::EP3_GAME_COMMAND: fprintf(stream, "EP3_GAME_COMMAND\n"); - print_data(stream, this->data, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); break; case Type::CHAT_MESSAGE: fprintf(stream, "CHAT_MESSAGE %08" PRIX32 "\n", this->guild_card_number); - print_data(stream, this->data, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); break; case Type::SERVER_DATA_COMMAND: fprintf(stream, "SERVER_DATA_COMMAND\n"); - print_data(stream, this->data, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); break; default: throw runtime_error("unknown event type in battle record"); @@ -137,7 +137,7 @@ BattleRecord::BattleRecord(const string& data) behavior_flags(0), battle_start_timestamp(0), battle_end_timestamp(0) { - StringReader r(data); + phosg::StringReader r(data); uint64_t signature = r.get_u64l(); bool has_random_stream; @@ -161,7 +161,7 @@ BattleRecord::BattleRecord(const string& data) } string BattleRecord::serialize() const { - StringWriter w; + phosg::StringWriter w; w.put_u64l(this->SIGNATURE_V2); w.put_u64l(this->battle_start_timestamp); w.put_u64l(this->battle_end_timestamp); @@ -202,7 +202,7 @@ void BattleRecord::add_player( } Event& ev = this->events.emplace_back(); ev.type = Event::Type::PLAYER_JOIN; - ev.timestamp = now(); + ev.timestamp = phosg::now(); auto& player = ev.players.emplace_back(); player.lobby_data = lobby_data; player.inventory = inventory; @@ -216,7 +216,7 @@ void BattleRecord::delete_player(uint8_t client_id) { } Event& ev = this->events.emplace_back(); ev.type = Event::Type::PLAYER_LEAVE; - ev.timestamp = now(); + ev.timestamp = phosg::now(); ev.leaving_client_id = client_id; } @@ -226,7 +226,7 @@ void BattleRecord::add_command(Event::Type type, const void* data, size_t size) } Event& ev = this->events.emplace_back(); ev.type = type; - ev.timestamp = now(); + ev.timestamp = phosg::now(); ev.data.assign(reinterpret_cast(data), size); } @@ -236,7 +236,7 @@ void BattleRecord::add_command(Event::Type type, string&& data) { } Event& ev = this->events.emplace_back(); ev.type = type; - ev.timestamp = now(); + ev.timestamp = phosg::now(); ev.data = std::move(data); } @@ -247,7 +247,7 @@ void BattleRecord::add_chat_message( } Event& ev = this->events.emplace_back(); ev.type = Event::Type::CHAT_MESSAGE; - ev.timestamp = now(); + ev.timestamp = phosg::now(); ev.guild_card_number = guild_card_number; ev.data = std::move(data); } @@ -287,7 +287,7 @@ void BattleRecord::set_battle_start_timestamp() { if (this->battle_start_timestamp != 0) { throw logic_error("battle start timestamp is already set"); } - this->battle_start_timestamp = now(); + this->battle_start_timestamp = phosg::now(); // First, find the correct map definition subcommand to keep, and execute // player join/leave events to get the present players @@ -357,12 +357,12 @@ void BattleRecord::set_battle_start_timestamp() { } void BattleRecord::set_battle_end_timestamp() { - this->battle_end_timestamp = now(); + this->battle_end_timestamp = phosg::now(); } void BattleRecord::print(FILE* stream) const { - string start_str = format_time(this->battle_start_timestamp); - string end_str = format_time(this->battle_end_timestamp); + string start_str = phosg::format_time(this->battle_start_timestamp); + string end_str = phosg::format_time(this->battle_end_timestamp); fprintf(stream, "BattleRecord %s behavior_flags=%08" PRIX32 " start=%016" PRIX64 " (%s) end=%016" PRIX64 " (%s); %zu events\n", this->is_writable ? "writable" : "read-only", this->behavior_flags, @@ -394,13 +394,12 @@ void BattleRecordPlayer::set_lobby(shared_ptr l) { void BattleRecordPlayer::start() { if (this->play_start_timestamp == 0) { - this->play_start_timestamp = now(); + this->play_start_timestamp = phosg::now(); this->schedule_events(); } } -void BattleRecordPlayer::dispatch_schedule_events( - evutil_socket_t, short, void* ctx) { +void BattleRecordPlayer::dispatch_schedule_events(evutil_socket_t, short, void* ctx) { reinterpret_cast(ctx)->schedule_events(); } @@ -413,7 +412,7 @@ void BattleRecordPlayer::schedule_events() { } for (;;) { - uint64_t relative_ts = now() - this->play_start_timestamp + this->record->battle_start_timestamp; + uint64_t relative_ts = phosg::now() - this->play_start_timestamp + this->record->battle_start_timestamp; if (this->event_it == this->record->events.end()) { if (relative_ts >= this->record->battle_end_timestamp) { @@ -426,7 +425,7 @@ void BattleRecordPlayer::schedule_events() { } else { // There are no more events to play, but the battle has not officially // ended yet - reschedule the event for the end time - auto tv = usecs_to_timeval(this->record->battle_end_timestamp - relative_ts); + auto tv = phosg::usecs_to_timeval(this->record->battle_end_timestamp - relative_ts); event_add(this->next_command_ev.get(), &tv); } break; @@ -467,7 +466,7 @@ void BattleRecordPlayer::schedule_events() { } else { // The next event should not occur yet, so reschedule for the time when // it should occur - auto tv = usecs_to_timeval(this->event_it->timestamp - relative_ts); + auto tv = phosg::usecs_to_timeval(this->event_it->timestamp - relative_ts); event_add(this->next_command_ev.get(), &tv); break; } diff --git a/src/Episode3/BattleRecord.hh b/src/Episode3/BattleRecord.hh index e4ddc806..d1e1f554 100644 --- a/src/Episode3/BattleRecord.hh +++ b/src/Episode3/BattleRecord.hh @@ -53,8 +53,8 @@ public: std::string data; Event() = default; - explicit Event(StringReader& r); - void serialize(StringWriter& w) const; + explicit Event(phosg::StringReader& r); + void serialize(phosg::StringWriter& w) const; void print(FILE* stream) const; }; @@ -126,7 +126,7 @@ private: std::shared_ptr base; std::weak_ptr lobby; std::shared_ptr next_command_ev; - StringReader random_r; + phosg::StringReader random_r; }; } // namespace Episode3 diff --git a/src/Episode3/Card.cc b/src/Episode3/Card.cc index 44432d92..81ee3a5f 100644 --- a/src/Episode3/Card.cc +++ b/src/Episode3/Card.cc @@ -123,7 +123,7 @@ ssize_t Card::apply_abnormal_condition( int8_t dice_roll_value, int8_t random_percent) { auto s = this->server(); - auto log = s->log_stack(string_printf("apply_abnormal_condition(%02hhX, @%04X, @%04X, %hd, %hhd, %hhd): ", def_effect_index, target_card_ref, sc_card_ref, value, dice_roll_value, random_percent)); + auto log = s->log_stack(phosg::string_printf("apply_abnormal_condition(%02hhX, @%04X, @%04X, %hd, %hhd, %hhd): ", def_effect_index, target_card_ref, sc_card_ref, value, dice_roll_value, random_percent)); bool is_nte = s->options.is_nte(); ssize_t existing_cond_index; @@ -298,7 +298,7 @@ void Card::commit_attack( size_t strike_number, int16_t* out_effective_damage) { auto s = this->server(); - auto log = s->log_stack(string_printf("commit_attack(@%04hX #%04hX, @%04hX #%04hX => %hd (str%zu)): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id(), damage, strike_number)); + auto log = s->log_stack(phosg::string_printf("commit_attack(@%04hX #%04hX, @%04hX #%04hX => %hd (str%zu)): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id(), damage, strike_number)); bool is_nte = s->options.is_nte(); int16_t effective_damage = damage; @@ -507,7 +507,7 @@ void Card::execute_attack(shared_ptr attacker_card) { } auto s = this->server(); - auto log = s->log_stack(string_printf("execute_attack(@%04X #%04X, @%04X #%04X): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id())); + auto log = s->log_stack(phosg::string_printf("execute_attack(@%04X #%04X, @%04X #%04X): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id())); bool is_nte = s->options.is_nte(); this->card_flags &= 0xFFFFFFF3; @@ -905,7 +905,7 @@ void Card::clear_action_chain_and_metadata_and_most_flags() { void Card::compute_action_chain_results(bool apply_action_conditions, bool ignore_this_card_ap_tp) { auto s = this->server(); - auto log = s->log_stack(string_printf("compute_action_chain_results(@%04hX #%04hX): ", this->get_card_ref(), this->get_card_id())); + auto log = s->log_stack(phosg::string_printf("compute_action_chain_results(@%04hX #%04hX): ", this->get_card_ref(), this->get_card_id())); bool is_nte = s->options.is_nte(); this->action_chain.compute_attack_medium(s); @@ -914,7 +914,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor this->action_chain.chain.tp_effect_bonus = 0; log.debug("(initial) medium=%s, strike_count=%hhu, ap_effect_bonus=%hhd, tp_effect_bonus=%hhd", - name_for_enum(this->action_chain.chain.attack_medium), + phosg::name_for_enum(this->action_chain.chain.attack_medium), this->action_chain.chain.strike_count, this->action_chain.chain.ap_effect_bonus, this->action_chain.chain.tp_effect_bonus); @@ -1220,7 +1220,7 @@ void Card::move_phase_before() { void Card::unknown_80236374(shared_ptr other_card, const ActionState* as) { auto s = this->server(); - auto log = s->log_stack(string_printf("unknown_80236374(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id())); + auto log = s->log_stack(phosg::string_printf("unknown_80236374(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id())); auto check_card = [&](shared_ptr card) -> void { if (card) { @@ -1361,8 +1361,8 @@ bool Card::is_guard_item() const { bool Card::unknown_80236554(shared_ptr other_card, const ActionState* as) { auto s = this->server(); auto log = s->log_stack(other_card - ? string_printf("unknown_80236554(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id()) - : string_printf("unknown_80236554(@%04hX #%04hX, null): ", this->get_card_ref(), this->get_card_id())); + ? phosg::string_printf("unknown_80236554(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id()) + : phosg::string_printf("unknown_80236554(@%04hX #%04hX, null): ", this->get_card_ref(), this->get_card_id())); if (as) { string as_str = as->str(s); log.debug("as = %s", as_str.c_str()); @@ -1439,7 +1439,7 @@ void Card::apply_attack_result() { auto ps = this->player_state(); bool is_nte = s->options.is_nte(); - auto log = s->log_stack(string_printf("apply_attack_result(@%04hX #%04hX): ", this->get_card_ref(), this->get_card_id())); + auto log = s->log_stack(phosg::string_printf("apply_attack_result(@%04hX #%04hX): ", this->get_card_ref(), this->get_card_id())); if (!this->action_chain.can_apply_attack()) { return; } diff --git a/src/Episode3/CardSpecial.cc b/src/Episode3/CardSpecial.cc index 7e71586e..fb2ca898 100644 --- a/src/Episode3/CardSpecial.cc +++ b/src/Episode3/CardSpecial.cc @@ -21,7 +21,7 @@ static string refs_str_for_cards_vector(const vector>& cards) { if (!ret.empty()) { ret += ", "; } - ret += string_printf("@%04hX", ref_for_card(card)); + ret += phosg::string_printf("@%04hX", ref_for_card(card)); } return ret; } @@ -453,7 +453,7 @@ bool CardSpecial::apply_stat_deltas_to_all_cards_from_all_conditions_with_card_r bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condition& cond, shared_ptr card) { auto s = this->server(); - auto log = s->log_stack(string_printf("apply_stat_deltas_to_card_from_condition_and_clear_cond(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); + auto log = s->log_stack(phosg::string_printf("apply_stat_deltas_to_card_from_condition_and_clear_cond(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); bool is_nte = s->options.is_nte(); string cond_str = cond.str(s); @@ -585,7 +585,7 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit break; trial_unimplemented: default: - log.debug("%s: no adjustments for condition type", name_for_enum(cond_type)); + log.debug("%s: no adjustments for condition type", phosg::name_for_enum(cond_type)); break; } @@ -1189,7 +1189,7 @@ shared_ptr CardSpecial::compute_replaced_target_based_on_conditions( StatSwapType CardSpecial::compute_stat_swap_type(shared_ptr card) const { auto s = this->server(); - auto log = s->log_stack(string_printf("compute_stat_swap_type(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); + auto log = s->log_stack(phosg::string_printf("compute_stat_swap_type(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); if (!card) { log.debug("card is missing"); return StatSwapType::NONE; @@ -1199,7 +1199,7 @@ StatSwapType CardSpecial::compute_stat_swap_type(shared_ptr card) co for (size_t cond_index = 0; cond_index < 9; cond_index++) { auto& cond = card->action_chain.conditions[cond_index]; if (cond.type != ConditionType::NONE) { - auto cond_log = log.sub(string_printf("(%zu) ", cond_index)); + auto cond_log = log.sub(phosg::string_printf("(%zu) ", cond_index)); string cond_str = cond.str(s); cond_log.debug("%s", cond_str.c_str()); if (!this->card_ref_has_ability_trap(cond)) { @@ -1675,7 +1675,7 @@ int32_t CardSpecial::evaluate_effect_expr( const char* expr, DiceRoll& dice_roll) const { auto log = this->server()->log_stack("evaluate_effect_expr: "); - if (log.min_level == LogLevel::DEBUG) { + if (log.min_level == phosg::LogLevel::DEBUG) { log.debug("ast, expr=\"%s\", dice_roll=(client_id=%02hhX, a2=%02hhX, value=%02hhX, value_used_in_expr=%s, a5=%04hX)", expr, dice_roll.client_id, dice_roll.unknown_a2, dice_roll.value, dice_roll.value_used_in_expr ? "true" : "false", dice_roll.unknown_a5); ast.print(stderr); } @@ -1769,10 +1769,10 @@ bool CardSpecial::execute_effect( uint32_t unknown_p7, uint16_t attacker_card_ref) { auto s = this->server(); - auto log = s->log_stack(string_printf("execute_effect(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); + auto log = s->log_stack(phosg::string_printf("execute_effect(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id())); { string cond_str = cond.str(s); - log.debug("cond=%s, card=@%04hX, expr_value=%hd, unknown_p5=%hd, cond_type=%s, unknown_p7=%" PRIu32 ", attacker_card_ref=@%04hX", cond_str.c_str(), ref_for_card(card), expr_value, unknown_p5, name_for_enum(cond_type), unknown_p7, attacker_card_ref); + log.debug("cond=%s, card=@%04hX, expr_value=%hd, unknown_p5=%hd, cond_type=%s, unknown_p7=%" PRIu32 ", attacker_card_ref=@%04hX", cond_str.c_str(), ref_for_card(card), expr_value, unknown_p5, phosg::name_for_enum(cond_type), unknown_p7, attacker_card_ref); } bool is_nte = s->options.is_nte(); @@ -2804,7 +2804,7 @@ vector> CardSpecial::get_targeted_cards_for_condition( int16_t p_target_type, bool apply_usability_filters) const { auto s = this->server(); - auto log = s->log_stack(string_printf("get_targeted_cards_for_condition(@%04hX, %hhu, @%04hX): ", card_ref, def_effect_index, setter_card_ref)); + auto log = s->log_stack(phosg::string_printf("get_targeted_cards_for_condition(@%04hX, %hhu, @%04hX): ", card_ref, def_effect_index, setter_card_ref)); log.debug("card_ref=@%04hX, def_effect_index=%02hhX, setter_card_ref=@%04hX, as, p_target_type=%hd, apply_usability_filters=%s", card_ref, def_effect_index, setter_card_ref, p_target_type, apply_usability_filters ? "true" : "false"); vector> ret; @@ -2836,7 +2836,7 @@ vector> CardSpecial::get_targeted_cards_for_condition( AttackMedium attack_medium = card2 ? card2->action_chain.chain.attack_medium : AttackMedium::UNKNOWN; - log.debug("attack_medium=%s", name_for_enum(attack_medium)); + log.debug("attack_medium=%s", phosg::name_for_enum(attack_medium)); auto add_card_refs = [&](const vector& result_card_refs) -> void { for (uint16_t result_card_ref : result_card_refs) { @@ -3944,13 +3944,13 @@ void CardSpecial::evaluate_and_apply_effects( bool apply_defense_condition_to_all_cards, uint16_t apply_defense_condition_to_card_ref) { auto s = this->server(); - auto log = s->log_stack(string_printf("evaluate_and_apply_effects(%s, @%04hX, @%04hX): ", name_for_enum(when), set_card_ref, sc_card_ref)); + auto log = s->log_stack(phosg::string_printf("evaluate_and_apply_effects(%s, @%04hX, @%04hX): ", phosg::name_for_enum(when), set_card_ref, sc_card_ref)); bool is_nte = s->options.is_nte(); { string as_str = as.str(s); log.debug("when=%s, set_card_ref=@%04hX, as=%s, sc_card_ref=@%04hX, apply_defense_condition_to_all_cards=%s, apply_defense_condition_to_card_ref=@%04hX", - name_for_enum(when), set_card_ref, as_str.c_str(), sc_card_ref, apply_defense_condition_to_all_cards ? "true" : "false", apply_defense_condition_to_card_ref); + phosg::name_for_enum(when), set_card_ref, as_str.c_str(), sc_card_ref, apply_defense_condition_to_all_cards ? "true" : "false", apply_defense_condition_to_card_ref); } if (!is_nte) { @@ -4010,12 +4010,12 @@ void CardSpecial::evaluate_and_apply_effects( log.debug("inputs: dice_roll=%02hhX, random_percent=%hhu, unknown_v1=%s", dice_roll.value, random_percent, unknown_v1 ? "true" : "false"); for (size_t def_effect_index = 0; (def_effect_index < 3) && !unknown_v1 && (ce->def.effects[def_effect_index].type != ConditionType::NONE); def_effect_index++) { - auto effect_log = log.sub(string_printf("(effect:%zu) ", def_effect_index)); + auto effect_log = log.sub(phosg::string_printf("(effect:%zu) ", def_effect_index)); const auto& card_effect = ce->def.effects[def_effect_index]; string card_effect_str = card_effect.str(); effect_log.debug("effect: %s", card_effect_str.c_str()); if (card_effect.when != when) { - effect_log.debug("does not apply (effect.when=%s, when=%s)", name_for_enum(card_effect.when), name_for_enum(when)); + effect_log.debug("does not apply (effect.when=%s, when=%s)", phosg::name_for_enum(card_effect.when), phosg::name_for_enum(when)); continue; } @@ -4067,7 +4067,7 @@ void CardSpecial::evaluate_and_apply_effects( } for (size_t z = 0; z < targeted_cards.size(); z++) { - auto target_log = effect_log.sub(string_printf("(target:@%04hX) ", targeted_cards[z]->get_card_ref())); + auto target_log = effect_log.sub(phosg::string_printf("(target:@%04hX) ", targeted_cards[z]->get_card_ref())); dice_roll.value_used_in_expr = false; string arg2_str = card_effect.arg2.decode(); target_log.debug("arg2_str = %s", arg2_str.c_str()); @@ -4075,8 +4075,7 @@ void CardSpecial::evaluate_and_apply_effects( this->evaluate_effect_arg2_condition( as, targeted_cards[z], arg2_str.c_str(), dice_roll, set_card_ref, sc_card_ref, random_percent, when)) { target_log.debug("arg2 condition passed"); - auto env_stats = this->compute_attack_env_stats( - as, targeted_cards[z], dice_roll, set_card_ref, sc_card_ref); + auto env_stats = this->compute_attack_env_stats(as, targeted_cards[z], dice_roll, set_card_ref, sc_card_ref); string expr_str = card_effect.expr.decode(); int16_t value = this->evaluate_effect_expr(env_stats, expr_str.c_str(), dice_roll); target_log.debug("expr = %s, value = %hd", expr_str.c_str(), value); @@ -4767,7 +4766,7 @@ void CardSpecial::dice_phase_before_for_card(shared_ptr card) { template void CardSpecial::apply_effects_on_phase_change_t(shared_ptr unknown_p2, const ActionState* existing_as) { auto s = this->server(); - auto log = s->log_stack(string_printf("apply_effects_on_phase_change_t<%s, %s>(@%04hX #%04hX): ", name_for_enum(When1), name_for_enum(When2), unknown_p2->get_card_ref(), unknown_p2->get_card_id())); + auto log = s->log_stack(phosg::string_printf("apply_effects_on_phase_change_t<%s, %s>(@%04hX #%04hX): ", phosg::name_for_enum(When1), phosg::name_for_enum(When2), unknown_p2->get_card_ref(), unknown_p2->get_card_id())); bool is_nte = s->options.is_nte(); ActionState as; @@ -4818,7 +4817,7 @@ void CardSpecial::unknown_8024945C(shared_ptr unknown_p2, const ActionStat } void CardSpecial::unknown_8024966C(shared_ptr unknown_p2, const ActionState* existing_as) { - auto log = this->server()->log_stack(string_printf("unknown_8024966C(@%04hX #%04hX): ", unknown_p2->get_card_ref(), unknown_p2->get_card_id())); + auto log = this->server()->log_stack(phosg::string_printf("unknown_8024966C(@%04hX #%04hX): ", unknown_p2->get_card_ref(), unknown_p2->get_card_id())); ActionState as; if (!existing_as) { @@ -4969,8 +4968,8 @@ template < EffectWhen WhenTargetsAndActionCards> void CardSpecial::apply_effects_before_or_after_attack(shared_ptr unknown_p2) { auto s = this->server(); - auto log = s->log_stack(string_printf("apply_effects_before_or_after_attack<%s, %s, %s, %s>(@%04hX #%04hX): ", - name_for_enum(WhenAllCards), name_for_enum(WhenAttackerAndActionCards), name_for_enum(WhenAttackerOrHunterSCCard), name_for_enum(WhenTargetsAndActionCards), unknown_p2->get_card_ref(), unknown_p2->get_card_id())); + auto log = s->log_stack(phosg::string_printf("apply_effects_before_or_after_attack<%s, %s, %s, %s>(@%04hX #%04hX): ", + phosg::name_for_enum(WhenAllCards), phosg::name_for_enum(WhenAttackerAndActionCards), phosg::name_for_enum(WhenAttackerOrHunterSCCard), phosg::name_for_enum(WhenTargetsAndActionCards), unknown_p2->get_card_ref(), unknown_p2->get_card_id())); ActionState as = this->create_attack_state_from_card_action_chain(unknown_p2); diff --git a/src/Episode3/DataIndexes.cc b/src/Episode3/DataIndexes.cc index 7353698a..9b33f962 100644 --- a/src/Episode3/DataIndexes.cc +++ b/src/Episode3/DataIndexes.cc @@ -80,8 +80,8 @@ const char* name_for_link_color(uint8_t color) { } } -JSON json_for_link_colors(const parray& colors) { - JSON ret = JSON::list(); +phosg::JSON json_for_link_colors(const parray& colors) { + phosg::JSON ret = phosg::JSON::list(); for (size_t z = 0; z < colors.size(); z++) { if (colors[z]) { ret.emplace_back(name_for_link_color(colors[z])); @@ -109,8 +109,8 @@ bool Location::operator!=(const Location& other) const { } std::string Location::str() const { - return string_printf("Location[x=%hhu, y=%hhu, dir=%hhu:%s, u=%hhu]", - this->x, this->y, static_cast(this->direction), name_for_enum(this->direction), this->unused); + return phosg::string_printf("Location[x=%hhu, y=%hhu, dir=%hhu:%s, u=%hhu]", + this->x, this->y, static_cast(this->direction), phosg::name_for_enum(this->direction), this->unused); } void Location::clear() { @@ -493,13 +493,13 @@ string CardDefinition::Stat::str() const { case Type::BLANK: return "(blank)"; case Type::STAT: - return string_printf("%hhd", this->stat); + return phosg::string_printf("%hhd", this->stat); case Type::PLUS_STAT: - return string_printf("+%hhd", this->stat); + return phosg::string_printf("+%hhd", this->stat); case Type::MINUS_STAT: - return string_printf("-%d", -this->stat); + return phosg::string_printf("-%d", -this->stat); case Type::EQUALS_STAT: - return string_printf("=%hhd", this->stat); + return phosg::string_printf("=%hhd", this->stat); case Type::UNKNOWN: return "?"; case Type::PLUS_UNKNOWN: @@ -509,7 +509,7 @@ string CardDefinition::Stat::str() const { case Type::EQUALS_UNKNOWN: return "=?"; default: - return string_printf("[%02hhX %02hhX]", this->type, this->stat); + return phosg::string_printf("[%02hhX %02hhX]", this->type, this->stat); } } @@ -541,44 +541,44 @@ string CardDefinition::Effect::str_for_arg(const string& arg) { switch (arg[0]) { case 'a': - return string_printf("%s (Each activation lasts for %zu attack%s)", arg.c_str(), value, (value == 1) ? "" : "s"); + return phosg::string_printf("%s (Each activation lasts for %zu attack%s)", arg.c_str(), value, (value == 1) ? "" : "s"); case 'C': case 'c': - return string_printf("%s (Req. linked item (%zu=>%zu))", arg.c_str(), value / 10, value % 10); + return phosg::string_printf("%s (Req. linked item (%zu=>%zu))", arg.c_str(), value / 10, value % 10); case 'd': - return string_printf("%s (Req. die roll in [%zu, %zu])", arg.c_str(), value / 10, value % 10); + return phosg::string_printf("%s (Req. die roll in [%zu, %zu])", arg.c_str(), value / 10, value % 10); case 'e': return arg + " (While equipped)"; case 'h': - return string_printf("%s (Req. HP >= %zu)", arg.c_str(), value); + return phosg::string_printf("%s (Req. HP >= %zu)", arg.c_str(), value); case 'i': - return string_printf("%s (Req. HP <= %zu)", arg.c_str(), value); + return phosg::string_printf("%s (Req. HP <= %zu)", arg.c_str(), value); case 'n': try { - return string_printf("%s (Req. condition: %s)", arg.c_str(), description_for_n_condition.at(value)); + return phosg::string_printf("%s (Req. condition: %s)", arg.c_str(), description_for_n_condition.at(value)); } catch (const out_of_range&) { return arg + " (Req. condition: unknown)"; } case 'o': { const char* suffix = ((value / 10) == 1) ? " on opponent card" : " on self"; if (value == 0) { - return string_printf("%s (Req. any previous effect%s)", arg.c_str(), suffix); + return phosg::string_printf("%s (Req. any previous effect%s)", arg.c_str(), suffix); } else { - return string_printf("%s (Req. effect %zu passed%s)", arg.c_str(), static_cast(value % 10), suffix); + return phosg::string_printf("%s (Req. effect %zu passed%s)", arg.c_str(), static_cast(value % 10), suffix); } } case 'p': try { - return string_printf("%s (Target: %s)", arg.c_str(), description_for_p_target.at(value)); + return phosg::string_printf("%s (Target: %s)", arg.c_str(), description_for_p_target.at(value)); } catch (const out_of_range&) { return arg + " (Target: unknown)"; } case 'r': - return string_printf("%s (Random with %zu%% chance)", arg.c_str(), value == 0 ? 100 : value); + return phosg::string_printf("%s (Random with %zu%% chance)", arg.c_str(), value == 0 ? 100 : value); case 's': - return string_printf("%s (Req. cost in [%zu, %zu])", arg.c_str(), value / 10, value % 10); + return phosg::string_printf("%s (Req. cost in [%zu, %zu])", arg.c_str(), value / 10, value % 10); case 't': - return string_printf("%s (Turns: %zu)", arg.c_str(), value); + return phosg::string_printf("%s (Turns: %zu)", arg.c_str(), value); default: return arg + " (unknown)"; } @@ -586,10 +586,10 @@ string CardDefinition::Effect::str_for_arg(const string& arg) { string CardDefinition::Effect::str(const char* separator, const TextSet* text_archive) const { vector tokens; - tokens.emplace_back(string_printf("%hhu:", this->effect_num)); + tokens.emplace_back(phosg::string_printf("%hhu:", this->effect_num)); { uint8_t type = static_cast(this->type); - string cmd_str = string_printf("cmd=%02hhX", type); + string cmd_str = phosg::string_printf("cmd=%02hhX", type); try { const char* name = description_for_condition_type.at(type).name; if (name) { @@ -603,15 +603,15 @@ string CardDefinition::Effect::str(const char* separator, const TextSet* text_ar if (!this->expr.empty()) { tokens.emplace_back("expr=" + this->expr.decode()); } - tokens.emplace_back(string_printf("when=%02hhX:%s", static_cast(this->when), name_for_enum(this->when))); + tokens.emplace_back(phosg::string_printf("when=%02hhX:%s", static_cast(this->when), phosg::name_for_enum(this->when))); tokens.emplace_back("arg1=" + this->str_for_arg(this->arg1.decode())); tokens.emplace_back("arg2=" + this->str_for_arg(this->arg2.decode())); tokens.emplace_back("arg3=" + this->str_for_arg(this->arg3.decode())); { uint8_t type = static_cast(this->apply_criterion); - string cond_str = string_printf("cond=%02hhX", type); + string cond_str = phosg::string_printf("cond=%02hhX", type); try { - const char* name = name_for_enum(this->apply_criterion); + const char* name = phosg::name_for_enum(this->apply_criterion); cond_str += ':'; cond_str += name; } catch (const invalid_argument&) { @@ -633,12 +633,12 @@ string CardDefinition::Effect::str(const char* separator, const TextSet* text_ar ch = '$'; } } - tokens.emplace_back(string_printf("name=%02hhX \"%s\"", this->name_index, formatted_name.c_str())); + tokens.emplace_back(phosg::string_printf("name=%02hhX \"%s\"", this->name_index, formatted_name.c_str())); } else { - tokens.emplace_back(string_printf("name=%02hhX", this->name_index)); + tokens.emplace_back(phosg::string_printf("name=%02hhX", this->name_index)); } - return join(tokens, separator); + return phosg::join(tokens, separator); } bool CardDefinition::is_sc() const { @@ -732,7 +732,7 @@ string name_for_rank(CardRank rank) { try { return names.at(static_cast(rank) - 1); } catch (const out_of_range&) { - return string_printf("(%02hhX)", static_cast(rank)); + return phosg::string_printf("(%02hhX)", static_cast(rank)); } } @@ -766,7 +766,7 @@ string string_for_colors(const parray& colors) { try { ret += name_for_link_color(colors[x]); } catch (const invalid_argument&) { - ret += string_printf("%02hhX", colors[x]); + ret += phosg::string_printf("%02hhX", colors[x]); } } } @@ -782,16 +782,16 @@ string string_for_assist_turns(uint8_t turns) { } else if (turns == 99) { return "FOREVER"; } else { - return string_printf("%hhu", turns); + return phosg::string_printf("%hhu", turns); } } string string_for_range(const parray& range) { string ret; for (size_t x = 0; x < 6; x++) { - ret += string_printf("%05" PRIX32 "/", range[x].load()); + ret += phosg::string_printf("%05" PRIX32 "/", range[x].load()); } - while (starts_with(ret, "00000/")) { + while (phosg::starts_with(ret, "00000/")) { ret = ret.substr(6); } if (!ret.empty()) { @@ -829,11 +829,11 @@ string string_for_drop_rate(uint16_t drop_rate) { } uint8_t environment_number = (drop_rate / 10) % 100; if (environment_number) { - tokens.emplace_back(string_printf("environment_number=%02hhX", static_cast(environment_number - 1))); + tokens.emplace_back(phosg::string_printf("environment_number=%02hhX", static_cast(environment_number - 1))); } else { tokens.emplace_back("environment_number=ANY"); } - tokens.emplace_back(string_printf("rarity_class=%hhu", static_cast((drop_rate / 1000) % 10))); + tokens.emplace_back(phosg::string_printf("rarity_class=%hhu", static_cast((drop_rate / 1000) % 10))); switch ((drop_rate / 10000) % 10) { case 0: tokens.emplace_back("deck_type=ANY"); @@ -847,8 +847,8 @@ string string_for_drop_rate(uint16_t drop_rate) { default: tokens.emplace_back("deck_type=__UNKNOWN__"); } - string description = join(tokens, ", "); - return string_printf("[%hu: %s]", drop_rate, description.c_str()); + string description = phosg::join(tokens, ", "); + return phosg::string_printf("[%hu: %s]", drop_rate, description.c_str()); } static const char* short_name_for_assist_ai_param_target(uint8_t target) { @@ -882,9 +882,9 @@ static const char* name_for_assist_ai_param_target(uint8_t target) { } string CardDefinition::str(bool single_line, const TextSet* text_archive) const { - string type_str = name_for_enum(this->type); - string criterion_str = name_for_enum(this->usable_criterion); - string card_class_str = name_for_enum(this->card_class()); + string type_str = phosg::name_for_enum(this->type); + string criterion_str = phosg::name_for_enum(this->usable_criterion); + string card_class_str = phosg::name_for_enum(this->card_class()); string rank_str = name_for_rank(this->rank); const char* target_mode_str = name_for_target_mode(this->target_mode); string assist_turns_str = string_for_assist_turns(this->assist_turns); @@ -914,19 +914,19 @@ string CardDefinition::str(bool single_line, const TextSet* text_archive) const string drop0_str = string_for_drop_rate(this->drop_rates[0]); string drop1_str = string_for_drop_rate(this->drop_rates[1]); - string cost_str = string_printf("%hhX", this->self_cost); + string cost_str = phosg::string_printf("%hhX", this->self_cost); if (this->ally_cost) { if (single_line) { - cost_str += string_printf("+%hhX", this->ally_cost); + cost_str += phosg::string_printf("+%hhX", this->ally_cost); } else { - cost_str += string_printf(" (self) + %hhX (ally)", this->ally_cost); + cost_str += phosg::string_printf(" (self) + %hhX (ally)", this->ally_cost); } } string en_name_s = this->en_name.decode(); if (single_line) { string range_str = string_for_range(this->range); - return string_printf( + return phosg::string_printf( "[Card: %04" PRIX32 " name=%s type=%s usable_condition=%s rank=%s " "cost=%s target=%s range=%s assist_turns=%s cannot_move=%s " "cannot_attack=%s cannot_drop=%s hp=%s ap=%s tp=%s mv=%s left=%s right=%s " @@ -975,7 +975,7 @@ string CardDefinition::str(bool single_line, const TextSet* text_archive) const } } } - return string_printf( + return phosg::string_printf( "\ Card: %04" PRIX32 " \"%s\"\n\ Type: %s, class: %s\n\ @@ -1026,7 +1026,7 @@ Card: %04" PRIX32 " \"%s\"\n\ } } -JSON CardDefinition::Stat::json() const { +phosg::JSON CardDefinition::Stat::json() const { const char* type_str = "unknown"; switch (this->type) { case Type::BLANK: @@ -1057,35 +1057,35 @@ JSON CardDefinition::Stat::json() const { type_str = "EQUALS_UNKNOWN"; break; } - return JSON::dict({ + return phosg::JSON::dict({ {"type", type_str}, {"value", this->stat}, }); } -JSON CardDefinition::Effect::json() const { - return JSON::dict({ +phosg::JSON CardDefinition::Effect::json() const { + return phosg::JSON::dict({ {"EffectNum", this->effect_num}, - {"ConditionType", name_for_enum(this->type)}, + {"ConditionType", phosg::name_for_enum(this->type)}, {"Expression", this->expr.decode()}, - {"When", name_for_enum(this->when)}, + {"When", phosg::name_for_enum(this->when)}, {"Arg1", this->arg1.decode()}, {"Arg2", this->arg2.decode()}, {"Arg3", this->arg3.decode()}, - {"ApplyCriterion", name_for_enum(this->apply_criterion)}, + {"ApplyCriterion", phosg::name_for_enum(this->apply_criterion)}, {"NameIndex", this->name_index}, }); } -JSON CardDefinition::json() const { - JSON range_json; +phosg::JSON CardDefinition::json() const { + phosg::JSON range_json; if (this->range[0] == 0x000FFFFF) { range_json = "ENTIRE_FIELD"; } else { - range_json = JSON::list(); + range_json = phosg::JSON::list(); for (size_t y = 0; y < 6; y++) { uint32_t row = this->range[y]; - auto& row_json = range_json.emplace_back(JSON::list()); + auto& row_json = range_json.emplace_back(phosg::JSON::list()); for (size_t x = 0; x < 5; x++) { row_json.emplace_back((row & 0x00010000) ? true : false); row <<= 4; @@ -1093,17 +1093,17 @@ JSON CardDefinition::json() const { } } - JSON effects_json = JSON::list(); + phosg::JSON effects_json = phosg::JSON::list(); for (size_t z = 0; z < this->effects.size(); z++) { if (!this->effects[z].is_empty()) { effects_json.emplace_back(this->effects[z].json()); } } - return JSON::dict({ + return phosg::JSON::dict({ {"CardID", this->card_id.load()}, {"JPName", this->jp_name.decode()}, - {"CardType", name_for_enum(this->type)}, + {"CardType", phosg::name_for_enum(this->type)}, {"SelfCost", this->self_cost}, {"AllyCost", this->ally_cost}, {"HP", this->hp.json()}, @@ -1119,11 +1119,11 @@ JSON CardDefinition::json() const { {"CannotMove", this->cannot_move ? true : false}, {"CannotAttack", this->cannot_attack ? true : false}, {"CannotDrop", this->cannot_drop ? true : false}, - {"UsableCriterion", name_for_enum(this->usable_criterion)}, + {"UsableCriterion", phosg::name_for_enum(this->usable_criterion)}, {"Rank", name_for_rank(this->rank)}, - {"CardClass", name_for_enum(this->card_class())}, + {"CardClass", phosg::name_for_enum(this->card_class())}, {"AssistAIParams", this->assist_ai_params.load()}, - {"DropRates", JSON::list({this->drop_rates[0].load(), this->drop_rates[1].load()})}, + {"DropRates", phosg::JSON::list({this->drop_rates[0].load(), this->drop_rates[1].load()})}, {"ENName", this->en_name.decode()}, {"JPShortName", this->jp_short_name.decode()}, {"ENShortName", this->en_short_name.decode()}, @@ -1214,7 +1214,7 @@ PlayerConfigNTE::operator PlayerConfig() const { return ret; } -Rules::Rules(const JSON& json) { +Rules::Rules(const phosg::JSON& json) { this->clear(); this->overall_time_limit = json.get_int("overall_time_limit", this->overall_time_limit); this->phase_time_limit = json.get_int("phase_time_limit", this->phase_time_limit); @@ -1240,20 +1240,20 @@ Rules::Rules(const JSON& json) { this->def_dice_value_range_2v1 = ((min_dice << 4) & 0xF0) | (max_dice & 0x0F); } -JSON Rules::json() const { - return JSON::dict({ +phosg::JSON Rules::json() const { + return phosg::JSON::dict({ {"overall_time_limit", this->overall_time_limit}, {"phase_time_limit", this->phase_time_limit}, - {"allowed_cards", name_for_enum(this->allowed_cards)}, + {"allowed_cards", phosg::name_for_enum(this->allowed_cards)}, {"min_dice", this->min_dice_value}, {"max_dice", this->max_dice_value}, {"disable_deck_shuffle", static_cast(this->disable_deck_shuffle)}, {"disable_deck_loop", static_cast(this->disable_deck_loop)}, {"char_hp", this->char_hp}, - {"hp_type", name_for_enum(this->hp_type)}, + {"hp_type", phosg::name_for_enum(this->hp_type)}, {"no_assist_cards", static_cast(this->no_assist_cards)}, {"disable_dialogue", static_cast(this->disable_dialogue)}, - {"dice_exchange_mode", name_for_enum(this->dice_exchange_mode)}, + {"dice_exchange_mode", phosg::name_for_enum(this->dice_exchange_mode)}, {"disable_dice_boost", static_cast(this->disable_dice_boost)}, {"min_def_dice", ((this->def_dice_value_range >> 4) & 0x0F)}, {"max_def_dice", (this->def_dice_value_range & 0x0F)}, @@ -1339,7 +1339,7 @@ string Rules::str() const { if (this->char_hp == 0xFF) { tokens.emplace_back("char_hp=(open)"); } else { - tokens.emplace_back(string_printf("char_hp=%hhu", this->char_hp)); + tokens.emplace_back(phosg::string_printf("char_hp=%hhu", this->char_hp)); } switch (this->hp_type) { @@ -1356,7 +1356,7 @@ string Rules::str() const { if (static_cast(this->hp_type) == 0xFF) { tokens.emplace_back("hp_type=(open)"); } else { - tokens.emplace_back(string_printf("hp_type=(%02hhX)", + tokens.emplace_back(phosg::string_printf("hp_type=(%02hhX)", static_cast(this->hp_type))); } break; @@ -1369,14 +1369,14 @@ string Rules::str() const { } else if (range.first == 0x00) { s += "min=(default), "; } else { - s += string_printf("min=%hhu, ", range.first); + s += phosg::string_printf("min=%hhu, ", range.first); } if (range.second == 0xFF) { s += "max=(open)]"; } else if (range.second == 0x00) { s += "max=(default)]"; } else { - s += string_printf("max=%hhu]", range.second); + s += phosg::string_printf("max=%hhu]", range.second); } return s; }; @@ -1405,7 +1405,7 @@ string Rules::str() const { if (static_cast(this->dice_exchange_mode) == 0xFF) { tokens.emplace_back("dice_exchange=(open)"); } else { - tokens.emplace_back(string_printf("dice_exchange=(%02hhX)", + tokens.emplace_back(phosg::string_printf("dice_exchange=(%02hhX)", static_cast(this->dice_exchange_mode))); } break; @@ -1420,7 +1420,7 @@ string Rules::str() const { case 0xFF: return "(open)"; default: - return string_printf("(%02hhX)", v); + return phosg::string_printf("(%02hhX)", v); } }; @@ -1445,7 +1445,7 @@ string Rules::str() const { if (static_cast(this->allowed_cards) == 0xFF) { tokens.emplace_back("allowed_cards=(open)"); } else { - tokens.emplace_back(string_printf("allowed_cards=(%02hhX)", + tokens.emplace_back(phosg::string_printf("allowed_cards=(%02hhX)", static_cast(this->allowed_cards))); } break; @@ -1455,21 +1455,21 @@ string Rules::str() const { if (this->overall_time_limit == 0xFF) { tokens.emplace_back("overall_time_limit=(open)"); } else if (this->overall_time_limit) { - tokens.emplace_back(string_printf("overall_time_limit=%zumin", static_cast(this->overall_time_limit * 5))); + tokens.emplace_back(phosg::string_printf("overall_time_limit=%zumin", static_cast(this->overall_time_limit * 5))); } else { tokens.emplace_back("overall_time_limit=(infinite)"); } if (this->phase_time_limit == 0xFF) { tokens.emplace_back("phase_time_limit=(open)"); } else if (this->phase_time_limit) { - tokens.emplace_back(string_printf("phase_time_limit=%hhusec", this->phase_time_limit)); + tokens.emplace_back(phosg::string_printf("phase_time_limit=%hhusec", this->phase_time_limit)); } else { tokens.emplace_back("phase_time_limit=(infinite)"); } tokens.emplace_back("dialogue=" + str_for_disable_bool(this->disable_dialogue)); - return "Rules[" + join(tokens, ", ") + "]"; + return "Rules[" + phosg::join(tokens, ", ") + "]"; } RulesTrial::RulesTrial(const Rules& r) @@ -1669,52 +1669,52 @@ void MapDefinition::assert_semantically_equivalent(const MapDefinition& other) c } } -JSON MapDefinition::CameraSpec::json() const { - return JSON::dict({ - {"Camera", JSON::list({this->camera_x.load(), this->camera_y.load(), this->camera_z.load()})}, - {"Focus", JSON::list({this->focus_x.load(), this->focus_y.load(), this->focus_z.load()})}, +phosg::JSON MapDefinition::CameraSpec::json() const { + return phosg::JSON::dict({ + {"Camera", phosg::JSON::list({this->camera_x.load(), this->camera_y.load(), this->camera_z.load()})}, + {"Focus", phosg::JSON::list({this->focus_x.load(), this->focus_y.load(), this->focus_z.load()})}, }); } -JSON MapDefinition::NPCDeck::json(uint8_t language) const { - JSON card_ids_json = JSON::list(); +phosg::JSON MapDefinition::NPCDeck::json(uint8_t language) const { + phosg::JSON card_ids_json = phosg::JSON::list(); for (size_t z = 0; z < this->card_ids.size(); z++) { if (this->card_ids[z] != 0xFFFF) { card_ids_json.emplace_back(this->card_ids[z].load()); } } - return JSON::dict({ + return phosg::JSON::dict({ {"Name", this->deck_name.decode(language)}, {"CardIDs", std::move(card_ids_json)}, }); } -JSON MapDefinition::AIParams::json(uint8_t language) const { - JSON params_json = JSON::list(); +phosg::JSON MapDefinition::AIParams::json(uint8_t language) const { + phosg::JSON params_json = phosg::JSON::list(); for (size_t z = 0; z < this->params.size(); z++) { params_json.emplace_back(this->params[z].load()); } - return JSON::dict({ + return phosg::JSON::dict({ {"IsArkz", this->is_arkz ? true : false}, {"Name", this->ai_name.decode(language)}, {"CardIDs", std::move(params_json)}, }); } -JSON MapDefinition::DialogueSet::json(uint8_t language) const { - JSON strings_json = JSON::list(); +phosg::JSON MapDefinition::DialogueSet::json(uint8_t language) const { + phosg::JSON strings_json = phosg::JSON::list(); for (size_t z = 0; z < this->strings.size(); z++) { strings_json.emplace_back(this->strings[z].decode(language)); } - return JSON::dict({ + return phosg::JSON::dict({ {"When", this->when.load()}, {"PercentChance", this->percent_chance.load()}, {"CardIDs", std::move(strings_json)}, }); } -JSON MapDefinition::EntryState::json() const { - JSON player_type_json; +phosg::JSON MapDefinition::EntryState::json() const { + phosg::JSON player_type_json; switch (this->player_type) { case 0x00: player_type_json = "Player"; @@ -1737,7 +1737,7 @@ JSON MapDefinition::EntryState::json() const { default: player_type_json = this->player_type; } - JSON deck_type_json; + phosg::JSON deck_type_json; switch (this->deck_type) { case 0x00: deck_type_json = "HERO ONLY"; @@ -1751,17 +1751,17 @@ JSON MapDefinition::EntryState::json() const { default: deck_type_json = this->deck_type; } - return JSON::dict({ + return phosg::JSON::dict({ {"PlayerType", std::move(player_type_json)}, {"DeckType", std::move(deck_type_json)}, }); } // TODO: -// JSON MapDefinition::json() const { ... } +// phosg::JSON MapDefinition::json() const { ... } string MapDefinition::CameraSpec::str() const { - return string_printf( + return phosg::string_printf( "CameraSpec[a1=(%g %g %g %g %g %g %g %g %g) camera=(%g %g %g) focus=(%g %g %g) a2=(%g %g %g)]", this->unknown_a1[0].load(), this->unknown_a1[1].load(), this->unknown_a1[2].load(), this->unknown_a1[3].load(), @@ -1780,20 +1780,20 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { for (size_t y = 0; y < this->height; y++) { string line = " "; for (size_t x = 0; x < this->width; x++) { - line += string_printf(" %02hhX", tiles[y][x]); + line += phosg::string_printf(" %02hhX", tiles[y][x]); } lines.emplace_back(std::move(line)); } }; - lines.emplace_back(string_printf("Map %08" PRIX32 ": %hhux%hhu", + lines.emplace_back(phosg::string_printf("Map %08" PRIX32 ": %hhux%hhu", this->map_number.load(), this->width, this->height)); - lines.emplace_back(string_printf(" tag: %08" PRIX32, this->tag.load())); - lines.emplace_back(string_printf(" environment_number: %02hhX (%s)", this->environment_number, name_for_environment_number(this->environment_number))); - lines.emplace_back(string_printf(" num_camera_zones: %02hhX", this->num_camera_zones)); + lines.emplace_back(phosg::string_printf(" tag: %08" PRIX32, this->tag.load())); + lines.emplace_back(phosg::string_printf(" environment_number: %02hhX (%s)", this->environment_number, name_for_environment_number(this->environment_number))); + lines.emplace_back(phosg::string_printf(" num_camera_zones: %02hhX", this->num_camera_zones)); lines.emplace_back(" tiles:"); add_map(this->map_tiles); - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " start_tile_definitions: A:[1p: %02hhX; 2p: %02hhX,%02hhX; 3p: %02hhX,%02hhX,%02hhX], B:[1p: %02hhX; 2p: %02hhX,%02hhX; 3p: %02hhX,%02hhX,%02hhX]", this->start_tile_definitions[0][0], this->start_tile_definitions[0][1], this->start_tile_definitions[0][2], this->start_tile_definitions[0][3], @@ -1803,7 +1803,7 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { this->start_tile_definitions[1][4], this->start_tile_definitions[1][5])); for (size_t z = 0; z < this->num_camera_zones; z++) { for (size_t w = 0; w < 2; w++) { - lines.emplace_back(string_printf(" camera zone %zu (team %c):", z, w ? 'A' : 'B')); + lines.emplace_back(phosg::string_printf(" camera zone %zu (team %c):", z, w ? 'A' : 'B')); add_map(this->camera_zone_maps[w][z]); lines.emplace_back(" " + this->camera_zone_specs[w][z].str()); } @@ -1811,20 +1811,20 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { for (size_t w = 0; w < 3; w++) { for (size_t z = 0; z < 2; z++) { string spec_str = this->overview_specs[w][z].str(); - lines.emplace_back(string_printf(" overview_specs[%zu][team %zu]: %s", w, z, spec_str.c_str())); + lines.emplace_back(phosg::string_printf(" overview_specs[%zu][team %zu]: %s", w, z, spec_str.c_str())); } } lines.emplace_back(" modification tiles:"); add_map(this->modification_tiles); for (size_t z = 0; z < 0x70; z += 0x10) { - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " a5[0x%02zX:0x%02zX]: %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX", z, z + 0x10, this->unknown_a5[z + 0x00], this->unknown_a5[z + 0x01], this->unknown_a5[z + 0x02], this->unknown_a5[z + 0x03], this->unknown_a5[z + 0x04], this->unknown_a5[z + 0x05], this->unknown_a5[z + 0x06], this->unknown_a5[z + 0x07], this->unknown_a5[z + 0x08], this->unknown_a5[z + 0x09], this->unknown_a5[z + 0x0A], this->unknown_a5[z + 0x0B], this->unknown_a5[z + 0x0C], this->unknown_a5[z + 0x0D], this->unknown_a5[z + 0x0E], this->unknown_a5[z + 0x0F])); } - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " a5[0x70:0x74]: %02hhX %02hhX %02hhX %02hhX", this->unknown_a5[0x70], this->unknown_a5[0x71], this->unknown_a5[0x72], this->unknown_a5[0x73])); lines.emplace_back(" default_rules: " + this->default_rules.str()); @@ -1832,17 +1832,17 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { lines.emplace_back(" location_name: " + this->location_name.decode(language)); lines.emplace_back(" quest_name: " + this->quest_name.decode(language)); lines.emplace_back(" description: " + this->description.decode(language)); - lines.emplace_back(string_printf(" map_xy: %hu %hu", this->map_x.load(), this->map_y.load())); + lines.emplace_back(phosg::string_printf(" map_xy: %hu %hu", this->map_x.load(), this->map_y.load())); for (size_t z = 0; z < 3; z++) { - lines.emplace_back(string_printf(" npc_chars[%zu]:", z)); + lines.emplace_back(phosg::string_printf(" npc_chars[%zu]:", z)); lines.emplace_back(" name: " + this->npc_ai_params[z].ai_name.decode(language)); - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " ai_params: (a1: %04hX %04hX, is_arkz: %02hhX, a2: %02hX %02hX %02hX)", this->npc_ai_params[z].unknown_a1[0].load(), this->npc_ai_params[z].unknown_a1[1].load(), this->npc_ai_params[z].is_arkz, this->npc_ai_params[z].unknown_a2[0], this->npc_ai_params[z].unknown_a2[1], this->npc_ai_params[z].unknown_a2[2])); for (size_t w = 0; w < 0x78; w += 0x08) { - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " ai_params.a3[0x%02zX:0x%02zX]: %04hX %04hX %04hX %04hX %04hX %04hX %04hX %04hX", w, w + 0x08, this->npc_ai_params[z].params[w + 0x00].load(), this->npc_ai_params[z].params[w + 0x01].load(), @@ -1850,12 +1850,12 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { this->npc_ai_params[z].params[w + 0x04].load(), this->npc_ai_params[z].params[w + 0x05].load(), this->npc_ai_params[z].params[w + 0x06].load(), this->npc_ai_params[z].params[w + 0x07].load())); } - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " ai_params.a3[0x78:0x7E]: %04hX %04hX %04hX %04hX %04hX %04hX", this->npc_ai_params[z].params[0x78].load(), this->npc_ai_params[z].params[0x79].load(), this->npc_ai_params[z].params[0x7A].load(), this->npc_ai_params[z].params[0x7B].load(), this->npc_ai_params[z].params[0x7C].load(), this->npc_ai_params[z].params[0x7D].load())); - lines.emplace_back(string_printf(" npc_decks[%zu]:", z)); + lines.emplace_back(phosg::string_printf(" npc_decks[%zu]:", z)); lines.emplace_back(" name: " + this->npc_decks[z].deck_name.decode(language)); for (size_t w = 0; w < 0x20; w++) { uint16_t card_id = this->npc_decks[z].card_ids[w]; @@ -1868,9 +1868,9 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { } if (entry) { string name = entry->def.en_name.decode(language); - lines.emplace_back(string_printf(" cards[%02zu]: %04hX (%s)", w, card_id, name.c_str())); + lines.emplace_back(phosg::string_printf(" cards[%02zu]: %04hX (%s)", w, card_id, name.c_str())); } else { - lines.emplace_back(string_printf(" cards[%02zu]: %04hX", w, card_id)); + lines.emplace_back(phosg::string_printf(" cards[%02zu]: %04hX", w, card_id)); } } for (size_t x = 0; x < 0x10; x++) { @@ -1878,18 +1878,18 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { if (set.when == -1 && set.percent_chance == 0xFFFF) { continue; } - lines.emplace_back(string_printf(" npc_dialogue[%zu][%zu] (when: %04hX, chance: %hu%%):", + lines.emplace_back(phosg::string_printf(" npc_dialogue[%zu][%zu] (when: %04hX, chance: %hu%%):", z, x, set.when.load(), set.percent_chance.load())); for (size_t w = 0; w < 4; w++) { if (!set.strings[w].empty() && set.strings[w].at(0) != 0xFF) { string s = set.strings[w].decode(language); - lines.emplace_back(string_printf(" strings[%zu]: %s", w, s.c_str())); + lines.emplace_back(phosg::string_printf(" strings[%zu]: %s", w, s.c_str())); } } } } - lines.emplace_back(" a7: " + format_data_string(this->unknown_a7.data(), this->unknown_a7.bytes())); - lines.emplace_back(string_printf(" npc_ai_params_entry_index: [%08" PRIX32 ", %08" PRIX32 ", %08" PRIX32 "]", + lines.emplace_back(" a7: " + phosg::format_data_string(this->unknown_a7.data(), this->unknown_a7.bytes())); + lines.emplace_back(phosg::string_printf(" npc_ai_params_entry_index: [%08" PRIX32 ", %08" PRIX32 ", %08" PRIX32 "]", this->npc_ai_params_entry_index[0].load(), this->npc_ai_params_entry_index[1].load(), this->npc_ai_params_entry_index[2].load())); if (!this->before_message.empty()) { lines.emplace_back(" before_message: " + this->before_message.decode(language)); @@ -1911,17 +1911,17 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { } if (entry) { string name = entry->def.en_name.decode(language); - lines.emplace_back(string_printf(" reward_cards[%02zu]: %04hX (%s)", z, card_id, name.c_str())); + lines.emplace_back(phosg::string_printf(" reward_cards[%02zu]: %04hX (%s)", z, card_id, name.c_str())); } else { - lines.emplace_back(string_printf(" reward_cards[%02zu]: %04hX", z, card_id)); + lines.emplace_back(phosg::string_printf(" reward_cards[%02zu]: %04hX", z, card_id)); } } - lines.emplace_back(string_printf(" level_overrides: [win: %" PRId32 ", loss: %" PRId32 "]", + lines.emplace_back(phosg::string_printf(" level_overrides: [win: %" PRId32 ", loss: %" PRId32 "]", this->win_level_override.load(), this->loss_level_override.load())); - lines.emplace_back(string_printf(" field_offset: (x: %hd units, y:%hd units) (x: %lg tiles, y: %lg tiles)", this->field_offset_x.load(), this->field_offset_y.load(), static_cast(this->field_offset_x) / 25.0, static_cast(this->field_offset_y) / 25.0)); - lines.emplace_back(string_printf(" map_category: %02hhX", this->map_category)); - lines.emplace_back(string_printf(" cyber_block_type: %02hhX", this->cyber_block_type)); - lines.emplace_back(string_printf(" a11: %02hhX%02hhX", this->unknown_a11[0], this->unknown_a11[1])); + lines.emplace_back(phosg::string_printf(" field_offset: (x: %hd units, y:%hd units) (x: %lg tiles, y: %lg tiles)", this->field_offset_x.load(), this->field_offset_y.load(), static_cast(this->field_offset_x) / 25.0, static_cast(this->field_offset_y) / 25.0)); + lines.emplace_back(phosg::string_printf(" map_category: %02hhX", this->map_category)); + lines.emplace_back(phosg::string_printf(" cyber_block_type: %02hhX", this->cyber_block_type)); + lines.emplace_back(phosg::string_printf(" a11: %02hhX%02hhX", this->unknown_a11[0], this->unknown_a11[1])); static const array sc_card_entry_names = { "00 (Guykild; 0005)", "01 (Kylria; 0006)", @@ -1957,7 +1957,7 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { unavailable_sc_cards += ", "; } if (this->unavailable_sc_cards[z] >= sc_card_entry_names.size()) { - unavailable_sc_cards += string_printf("%04hX (invalid)", this->unavailable_sc_cards[z].load()); + unavailable_sc_cards += phosg::string_printf("%04hX (invalid)", this->unavailable_sc_cards[z].load()); } else { unavailable_sc_cards += sc_card_entry_names[this->unavailable_sc_cards[z]]; } @@ -1986,7 +1986,7 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { player_type = "FREE"; break; default: - player_type = string_printf("(%02hhX)", this->entry_states[z].player_type); + player_type = phosg::string_printf("(%02hhX)", this->entry_states[z].player_type); break; } string deck_type; @@ -2001,13 +2001,13 @@ string MapDefinition::str(const CardIndex* card_index, uint8_t language) const { deck_type = "any deck allowed"; break; default: - deck_type = string_printf("(%02hhX)", this->entry_states[z].deck_type); + deck_type = phosg::string_printf("(%02hhX)", this->entry_states[z].deck_type); break; } - lines.emplace_back(string_printf( + lines.emplace_back(phosg::string_printf( " entry_states[%zu]: %s / %s", z, player_type.c_str(), deck_type.c_str())); } - return join(lines, "\n"); + return phosg::join(lines, "\n"); } MapDefinitionTrial::MapDefinitionTrial(const MapDefinition& map) @@ -2267,20 +2267,20 @@ CardIndex::CardIndex( unordered_map card_text; try { string text_bin_data; - if (!decompressed_text_filename.empty() && isfile(decompressed_text_filename)) { - text_bin_data = load_file(decompressed_text_filename); - } else if (!text_filename.empty() && isfile(text_filename)) { - text_bin_data = prs_decompress(load_file(text_filename)); + if (!decompressed_text_filename.empty() && phosg::isfile(decompressed_text_filename)) { + text_bin_data = phosg::load_file(decompressed_text_filename); + } else if (!text_filename.empty() && phosg::isfile(text_filename)) { + text_bin_data = prs_decompress(phosg::load_file(text_filename)); } if (!text_bin_data.empty()) { - StringReader r(text_bin_data); + phosg::StringReader r(text_bin_data); while (!r.eof()) { string card_id_str = r.get_cstr(); if (card_id_str.empty() || (static_cast(card_id_str[0]) == 0xFF)) { break; } - strip_leading_whitespace(card_id_str); + phosg::strip_leading_whitespace(card_id_str); uint32_t card_id = stoul(card_id_str); // Read all pages for this card @@ -2329,7 +2329,7 @@ CardIndex::CardIndex( // Split first page into tags, and collapse whitespace in the tag names vector tags; - auto lines = split(first_page, '\n'); + auto lines = phosg::split(first_page, '\n'); for (const auto& line : lines) { string tag; if (line[0] == '\t' && line[1] == 'D') { @@ -2344,7 +2344,7 @@ CardIndex::CardIndex( tags.emplace_back(std::move(tag)); } } - strip_leading_whitespace(orig_text); + phosg::strip_leading_whitespace(orig_text); if (!card_text.emplace(card_id, std::move(orig_text)).second) { throw runtime_error("duplicate card text id"); @@ -2363,20 +2363,20 @@ CardIndex::CardIndex( unordered_map> card_dice_text; try { string text_bin_data; - if (!decompressed_dice_text_filename.empty() && isfile(decompressed_dice_text_filename)) { - text_bin_data = load_file(decompressed_dice_text_filename); - } else if (!dice_text_filename.empty() && isfile(dice_text_filename)) { - text_bin_data = prs_decompress(load_file(dice_text_filename)); + if (!decompressed_dice_text_filename.empty() && phosg::isfile(decompressed_dice_text_filename)) { + text_bin_data = phosg::load_file(decompressed_dice_text_filename); + } else if (!dice_text_filename.empty() && phosg::isfile(dice_text_filename)) { + text_bin_data = prs_decompress(phosg::load_file(dice_text_filename)); } if (!text_bin_data.empty()) { - StringReader r(text_bin_data); + phosg::StringReader r(text_bin_data); while (!r.eof()) { uint32_t card_id = r.get_u32l(); string dice_caption = r.read(0xFE); string dice_text = r.read(0xFE); - strip_trailing_zeroes(dice_caption); - strip_trailing_zeroes(dice_text); + phosg::strip_trailing_zeroes(dice_caption); + phosg::strip_trailing_zeroes(dice_text); card_dice_text.emplace(card_id, make_pair(std::move(dice_caption), std::move(dice_text))); } } @@ -2386,12 +2386,12 @@ CardIndex::CardIndex( try { string decompressed_data; - this->mtime_for_card_definitions = stat(filename).st_mtime; + this->mtime_for_card_definitions = phosg::stat(filename).st_mtime; try { - decompressed_data = load_file(decompressed_filename); + decompressed_data = phosg::load_file(decompressed_filename); this->compressed_card_definitions.clear(); - } catch (const cannot_open_file&) { - this->compressed_card_definitions = load_file(filename); + } catch (const phosg::cannot_open_file&) { + this->compressed_card_definitions = phosg::load_file(filename); decompressed_data = prs_decompress(this->compressed_card_definitions); } if (decompressed_data.size() > 0x36EC0) { @@ -2401,7 +2401,7 @@ CardIndex::CardIndex( // There's a footer after the card definitions (it's a standard-format REL // file), but we ignore it if (decompressed_data.size() % sizeof(CardDefinition) != sizeof(CardDefinitionsFooter)) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "decompressed card update file size %zX is not aligned with card definition size %zX (%zX extra bytes)", decompressed_data.size(), sizeof(CardDefinition), decompressed_data.size() % sizeof(CardDefinition))); } @@ -2417,7 +2417,7 @@ CardIndex::CardIndex( auto entry = make_shared(CardEntry{defs[x], "", "", "", {}}); if (!this->card_definitions.emplace(entry->def.card_id, entry).second) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "duplicate card id: %08" PRIX32, entry->def.card_id.load())); } @@ -2454,9 +2454,9 @@ CardIndex::CardIndex( } if (this->compressed_card_definitions.empty()) { - uint64_t start = now(); + uint64_t start = phosg::now(); this->compressed_card_definitions = prs_compress(decompressed_data); - uint64_t diff = now() - start; + uint64_t diff = phosg::now() - start; static_game_data_log.info( "Compressed card definitions (%zu bytes -> %zu bytes) in %" PRIu64 "us", decompressed_data.size(), this->compressed_card_definitions.size(), diff); @@ -2472,9 +2472,9 @@ CardIndex::CardIndex( defs[x].jp_name.clear(); defs[x].jp_short_name.clear(); } - uint64_t start = now(); + uint64_t start = phosg::now(); this->compressed_card_definitions = prs_compress_optimal(decompressed_data.data(), decompressed_data.size()); - uint64_t diff = now() - start; + uint64_t diff = phosg::now() - start; static_game_data_log.info( "Compressed card definitions (0x%zX bytes -> 0x%zX bytes) in %" PRIu64 "us", decompressed_data.size(), this->compressed_card_definitions.size(), diff); @@ -2521,8 +2521,8 @@ uint64_t CardIndex::definitions_mtime() const { return this->mtime_for_card_definitions; } -JSON CardIndex::definitions_json() const { - JSON ret = JSON::dict(); +phosg::JSON CardIndex::definitions_json() const { + phosg::JSON ret = phosg::JSON::dict(); for (const auto& it : this->card_definitions_by_name) { ret.emplace(it.first, it.second->def.json()); } @@ -2549,7 +2549,7 @@ MapIndex::VersionedMap::VersionedMap(std::string&& compressed_data, uint8_t lang compressed_data(std::move(compressed_data)) { string decompressed = prs_decompress(this->compressed_data); if (decompressed.size() != sizeof(MapDefinition)) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "decompressed data size is incorrect (expected %zu bytes, read %zu bytes)", sizeof(MapDefinition), decompressed.size())); } @@ -2621,34 +2621,34 @@ shared_ptr MapIndex::Map::version(uint8_t language } MapIndex::MapIndex(const string& directory) { - for (const auto& filename : list_directory_sorted(directory)) { + for (const auto& filename : phosg::list_directory_sorted(directory)) { try { string base_filename; string compressed_data; shared_ptr decompressed_data; - if (ends_with(filename, ".mnmd") || ends_with(filename, ".bind")) { - decompressed_data = make_shared(load_object_file(directory + "/" + filename)); + if (phosg::ends_with(filename, ".mnmd") || phosg::ends_with(filename, ".bind")) { + decompressed_data = make_shared(phosg::load_object_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 5); - } else if (ends_with(filename, ".mnm") || ends_with(filename, ".bin")) { - compressed_data = load_file(directory + "/" + filename); + } else if (phosg::ends_with(filename, ".mnm") || phosg::ends_with(filename, ".bin")) { + compressed_data = phosg::load_file(directory + "/" + filename); base_filename = filename.substr(0, filename.size() - 4); - } else if (ends_with(filename, ".bin.gci") || ends_with(filename, ".mnm.gci")) { - compressed_data = decode_gci_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".bin.gci") || phosg::ends_with(filename, ".mnm.gci")) { + compressed_data = decode_gci_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 8); - } else if (ends_with(filename, ".gci")) { - compressed_data = decode_gci_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".gci")) { + compressed_data = decode_gci_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 4); - } else if (ends_with(filename, ".bin.vms") || ends_with(filename, ".mnm.vms")) { - compressed_data = decode_vms_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".bin.vms") || phosg::ends_with(filename, ".mnm.vms")) { + compressed_data = decode_vms_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 8); - } else if (ends_with(filename, ".vms")) { - compressed_data = decode_vms_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".vms")) { + compressed_data = decode_vms_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 4); - } else if (ends_with(filename, ".bin.dlq") || ends_with(filename, ".mnm.dlq")) { - compressed_data = decode_dlq_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".bin.dlq") || phosg::ends_with(filename, ".mnm.dlq")) { + compressed_data = decode_dlq_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 8); - } else if (ends_with(filename, ".dlq")) { - compressed_data = decode_dlq_data(load_file(directory + "/" + filename)); + } else if (phosg::ends_with(filename, ".dlq")) { + compressed_data = decode_dlq_data(phosg::load_file(directory + "/" + filename)); base_filename = filename.substr(0, filename.size() - 4); } else { continue; // Silently skip file @@ -2712,8 +2712,8 @@ const string& MapIndex::get_compressed_list(size_t num_players, uint8_t language } string& compressed_map_list = this->compressed_map_lists[language].at(num_players - 1); if (compressed_map_list.empty()) { - StringWriter entries_w; - StringWriter strings_w; + phosg::StringWriter entries_w; + phosg::StringWriter strings_w; size_t num_maps = 0; for (const auto& map_it : this->maps) { @@ -2768,12 +2768,12 @@ const string& MapIndex::get_compressed_list(size_t num_players, uint8_t language prs.add(entries_w.str()); prs.add(strings_w.str()); - StringWriter compressed_w; + phosg::StringWriter compressed_w; compressed_w.put_u32b(prs.input_size()); compressed_w.write(prs.close()); compressed_map_list = std::move(compressed_w.str()); if (compressed_map_list.size() > 0x7BEC) { - throw runtime_error(string_printf("compressed map list for %zu players is too large (0x%zX bytes)", num_players, compressed_map_list.size())); + throw runtime_error(phosg::string_printf("compressed map list for %zu players is too large (0x%zX bytes)", num_players, compressed_map_list.size())); } size_t decompressed_size = sizeof(header) + entries_w.size() + strings_w.size(); static_game_data_log.info("Generated Episode 3 compressed map list for %zu player(s) (%zu maps; 0x%zX -> 0x%zX bytes)", @@ -2800,7 +2800,7 @@ set MapIndex::all_numbers() const { COMDeckIndex::COMDeckIndex(const string& filename) { try { - auto json = JSON::parse(load_file(filename)); + auto json = phosg::JSON::parse(phosg::load_file(filename)); for (const auto& def_json : json.as_list()) { auto& def = this->decks.emplace_back(make_shared()); def->index = this->decks.size() - 1; @@ -2832,13 +2832,13 @@ shared_ptr COMDeckIndex::deck_for_name(const string& wh } shared_ptr COMDeckIndex::random_deck() const { - return this->decks[random_object() % this->decks.size()]; + return this->decks[phosg::random_object() % this->decks.size()]; } } // namespace Episode3 template <> -Episode3::HPType enum_for_name(const char* name) { +Episode3::HPType phosg::enum_for_name(const char* name) { if (!strcmp(name, "DEFEAT_PLAYER")) { return Episode3::HPType::DEFEAT_PLAYER; } else if (!strcmp(name, "DEFEAT_TEAM")) { @@ -2851,7 +2851,7 @@ Episode3::HPType enum_for_name(const char* name) { } template <> -const char* name_for_enum(Episode3::HPType hp_type) { +const char* phosg::name_for_enum(Episode3::HPType hp_type) { switch (hp_type) { case Episode3::HPType::DEFEAT_PLAYER: return "DEFEAT_PLAYER"; @@ -2865,7 +2865,7 @@ const char* name_for_enum(Episode3::HPType hp_type) { } template <> -Episode3::DiceExchangeMode enum_for_name(const char* name) { +Episode3::DiceExchangeMode phosg::enum_for_name(const char* name) { if (!strcmp(name, "HIGH_ATK")) { return Episode3::DiceExchangeMode::HIGH_ATK; } else if (!strcmp(name, "HIGH_DEF")) { @@ -2878,7 +2878,7 @@ Episode3::DiceExchangeMode enum_for_name(const char* } template <> -const char* name_for_enum(Episode3::DiceExchangeMode dice_exchange_mode) { +const char* phosg::name_for_enum(Episode3::DiceExchangeMode dice_exchange_mode) { switch (dice_exchange_mode) { case Episode3::DiceExchangeMode::HIGH_ATK: return "HIGH_ATK"; @@ -2892,7 +2892,7 @@ const char* name_for_enum(Episode3::DiceExchangeMode } template <> -Episode3::AllowedCards enum_for_name(const char* name) { +Episode3::AllowedCards phosg::enum_for_name(const char* name) { if (!strcmp(name, "ALL")) { return Episode3::AllowedCards::ALL; } else if (!strcmp(name, "N_ONLY")) { @@ -2907,7 +2907,7 @@ Episode3::AllowedCards enum_for_name(const char* name) { } template <> -const char* name_for_enum(Episode3::AllowedCards allowed_cards) { +const char* phosg::name_for_enum(Episode3::AllowedCards allowed_cards) { switch (allowed_cards) { case Episode3::AllowedCards::ALL: return "ALL"; @@ -2923,7 +2923,7 @@ const char* name_for_enum(Episode3::AllowedCards allowed } template <> -const char* name_for_enum(Episode3::BattlePhase phase) { +const char* phosg::name_for_enum(Episode3::BattlePhase phase) { switch (phase) { case Episode3::BattlePhase::INVALID_00: return "INVALID_00"; @@ -2945,7 +2945,7 @@ const char* name_for_enum(Episode3::BattlePhase phase) { } template <> -const char* name_for_enum(Episode3::SetupPhase phase) { +const char* phosg::name_for_enum(Episode3::SetupPhase phase) { switch (phase) { case Episode3::SetupPhase::REGISTRATION: return "REGISTRATION"; @@ -2965,7 +2965,7 @@ const char* name_for_enum(Episode3::SetupPhase phase) { } template <> -const char* name_for_enum(Episode3::RegistrationPhase phase) { +const char* phosg::name_for_enum(Episode3::RegistrationPhase phase) { switch (phase) { case Episode3::RegistrationPhase::AWAITING_NUM_PLAYERS: return "AWAITING_NUM_PLAYERS"; @@ -2985,7 +2985,7 @@ const char* name_for_enum(Episode3::RegistrationPha } template <> -const char* name_for_enum(Episode3::ActionSubphase phase) { +const char* phosg::name_for_enum(Episode3::ActionSubphase phase) { switch (phase) { case Episode3::ActionSubphase::ATTACK: return "ATTACK"; @@ -2999,7 +2999,7 @@ const char* name_for_enum(Episode3::ActionSubphase pha } template <> -const char* name_for_enum(Episode3::AttackMedium medium) { +const char* phosg::name_for_enum(Episode3::AttackMedium medium) { switch (medium) { case Episode3::AttackMedium::UNKNOWN: return "UNKNOWN"; @@ -3017,7 +3017,7 @@ const char* name_for_enum(Episode3::AttackMedium medium) } template <> -const char* name_for_enum(Episode3::CriterionCode code) { +const char* phosg::name_for_enum(Episode3::CriterionCode code) { switch (code) { case Episode3::CriterionCode::NONE: return "NONE"; @@ -3095,7 +3095,7 @@ const char* name_for_enum(Episode3::CriterionCode code) } template <> -const char* name_for_enum(Episode3::CardType type) { +const char* phosg::name_for_enum(Episode3::CardType type) { switch (type) { case Episode3::CardType::HUNTERS_SC: return "HUNTERS_SC"; @@ -3117,7 +3117,7 @@ const char* name_for_enum(Episode3::CardType type) { } template <> -const char* name_for_enum(Episode3::CardClass cc) { +const char* phosg::name_for_enum(Episode3::CardClass cc) { switch (cc) { case Episode3::CardClass::HU_SC: return "HU_SC"; @@ -3165,7 +3165,7 @@ const char* name_for_enum(Episode3::CardClass cc) { } template <> -const char* name_for_enum(Episode3::ConditionType cond_type) { +const char* phosg::name_for_enum(Episode3::ConditionType cond_type) { try { return Episode3::description_for_condition_type.at(static_cast(cond_type)).name; } catch (const out_of_range&) { @@ -3174,7 +3174,7 @@ const char* name_for_enum(Episode3::ConditionType cond_ } template <> -const char* name_for_enum(Episode3::EffectWhen when) { +const char* phosg::name_for_enum(Episode3::EffectWhen when) { switch (when) { case Episode3::EffectWhen::NONE: return "NONE"; @@ -3246,7 +3246,7 @@ const char* name_for_enum(Episode3::EffectWhen when) { } template <> -const char* name_for_enum(Episode3::Direction d) { +const char* phosg::name_for_enum(Episode3::Direction d) { switch (d) { case Episode3::Direction::RIGHT: return "LEFT"; diff --git a/src/Episode3/DataIndexes.hh b/src/Episode3/DataIndexes.hh index 161cb424..fa4be54c 100644 --- a/src/Episode3/DataIndexes.hh +++ b/src/Episode3/DataIndexes.hh @@ -16,6 +16,7 @@ #include "../PlayerSubordinates.hh" #include "../Text.hh" #include "../TextIndex.hh" +#include "../Types.hh" namespace Episode3 { @@ -506,7 +507,7 @@ struct CardDefinition { void decode_code(); std::string str() const; - JSON json() const; + phosg::JSON json() const; } __packed_ws__(Stat, 4); struct Effect { @@ -543,7 +544,7 @@ struct CardDefinition { bool is_empty() const; static std::string str_for_arg(const std::string& arg); std::string str(const char* separator = ", ", const TextSet* text_archive = nullptr) const; - JSON json() const; + phosg::JSON json() const; } __packed_ws__(Effect, 0x20); /* 0000 */ be_uint32_t card_id; @@ -810,7 +811,7 @@ struct CardDefinition { void decode_range(); std::string str(bool single_line = true, const TextSet* text_archive = nullptr) const; - JSON json() const; + phosg::JSON json() const; } __packed_ws__(CardDefinition, 0x128); struct CardDefinitionsFooter { @@ -1029,8 +1030,8 @@ struct Rules { // likely be more work than it's worth. Rules() = default; - explicit Rules(const JSON& json); - JSON json() const; + explicit Rules(const phosg::JSON& json); + phosg::JSON json() const; bool operator==(const Rules& other) const = default; bool operator!=(const Rules& other) const = default; void clear(); @@ -1225,7 +1226,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests /* 48 */ std::string str() const; - JSON json() const; + phosg::JSON json() const; } __packed_ws__(CameraSpec, 0x48); // This array specifies the camera zone maps. A camera zone map is a subset of @@ -1283,7 +1284,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests /* 00 */ pstring deck_name; /* 18 */ parray card_ids; // Last one appears to always be FFFF /* 58 */ - JSON json(uint8_t language) const; + phosg::JSON json(uint8_t language) const; } __packed_ws__(NPCDeck, 0x58); /* 1FE8 */ parray npc_decks; // Unused if name[0] == 0 @@ -1299,7 +1300,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests // TODO: Figure out exactly how these are used and document here. /* 0018 */ parray params; /* 0114 */ - JSON json(uint8_t language) const; + phosg::JSON json(uint8_t language) const; } __packed_ws__(AIParams, 0x114); /* 20F0 */ parray npc_ai_params; // Unused if name[0] == 0 @@ -1352,7 +1353,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests // strings, excluding any that are empty or begin with the character '^'. /* 0004 */ parray, 4> strings; /* 0104 */ - JSON json(uint8_t language) const; + phosg::JSON json(uint8_t language) const; } __packed_ws__(DialogueSet, 0x104); // There are up to 0x10 of these per valid NPC, but only the first 13 of them @@ -1435,7 +1436,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests bool operator==(const EntryState& other) const = default; bool operator!=(const EntryState& other) const = default; - JSON json() const; + phosg::JSON json() const; } __packed_ws__(EntryState, 2); /* 5A10 */ parray entry_states; /* 5A18 */ @@ -1451,7 +1452,7 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests void assert_semantically_equivalent(const MapDefinition& other) const; std::string str(const CardIndex* card_index, uint8_t language) const; - JSON json(uint8_t language) const; + phosg::JSON json(uint8_t language) const; } __packed_ws__(MapDefinition, 0x5A18); struct MapDefinitionTrial { @@ -1534,7 +1535,7 @@ public: std::shared_ptr definition_for_name_normalized(const std::string& name) const; std::set all_ids() const; uint64_t definitions_mtime() const; - JSON definitions_json() const; + phosg::JSON definitions_json() const; private: static std::string normalize_card_name(const std::string& name); @@ -1615,37 +1616,37 @@ private: // TODO: Figure out how to declare these inside the Episode3 namespace. template <> -Episode3::HPType enum_for_name(const char* name); +Episode3::HPType phosg::enum_for_name(const char* name); template <> -const char* name_for_enum(Episode3::HPType hp_type); +const char* phosg::name_for_enum(Episode3::HPType hp_type); template <> -Episode3::DiceExchangeMode enum_for_name(const char* name); +Episode3::DiceExchangeMode phosg::enum_for_name(const char* name); template <> -const char* name_for_enum(Episode3::DiceExchangeMode dice_exchange_mode); +const char* phosg::name_for_enum(Episode3::DiceExchangeMode dice_exchange_mode); template <> -Episode3::AllowedCards enum_for_name(const char* name); +Episode3::AllowedCards phosg::enum_for_name(const char* name); template <> -const char* name_for_enum(Episode3::AllowedCards allowed_cards); +const char* phosg::name_for_enum(Episode3::AllowedCards allowed_cards); template <> -const char* name_for_enum(Episode3::BattlePhase phase); +const char* phosg::name_for_enum(Episode3::BattlePhase phase); template <> -const char* name_for_enum(Episode3::SetupPhase phase); +const char* phosg::name_for_enum(Episode3::SetupPhase phase); template <> -const char* name_for_enum(Episode3::RegistrationPhase phase); +const char* phosg::name_for_enum(Episode3::RegistrationPhase phase); template <> -const char* name_for_enum(Episode3::ActionSubphase phase); +const char* phosg::name_for_enum(Episode3::ActionSubphase phase); template <> -const char* name_for_enum(Episode3::AttackMedium medium); +const char* phosg::name_for_enum(Episode3::AttackMedium medium); template <> -const char* name_for_enum(Episode3::CriterionCode code); +const char* phosg::name_for_enum(Episode3::CriterionCode code); template <> -const char* name_for_enum(Episode3::CardType type); +const char* phosg::name_for_enum(Episode3::CardType type); template <> -const char* name_for_enum(Episode3::CardClass cc); +const char* phosg::name_for_enum(Episode3::CardClass cc); template <> -const char* name_for_enum(Episode3::ConditionType cond_type); +const char* phosg::name_for_enum(Episode3::ConditionType cond_type); template <> -const char* name_for_enum(Episode3::EffectWhen when); +const char* phosg::name_for_enum(Episode3::EffectWhen when); template <> -const char* name_for_enum(Episode3::Direction d); +const char* phosg::name_for_enum(Episode3::Direction d); diff --git a/src/Episode3/PlayerState.cc b/src/Episode3/PlayerState.cc index 1801c296..590db8d0 100644 --- a/src/Episode3/PlayerState.cc +++ b/src/Episode3/PlayerState.cc @@ -1780,7 +1780,7 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) { auto card = s->card_for_set_card_ref(pa.attacker_card_ref); if (card) { card->loc.direction = pa.facing_direction; - log.debug("set facing direction to %s", name_for_enum(card->loc.direction)); + log.debug("set facing direction to %s", phosg::name_for_enum(card->loc.direction)); G_AddToSetCardlog_Ep3_6xB4x4A cmd; cmd.card_refs.clear(0xFFFF); @@ -1789,7 +1789,7 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) { cmd.entry_count = 0; size_t z = 0; do { - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string ref_str = s->debug_str_for_card_ref(pa.action_card_refs[z]); log.debug("on action card ref %s", ref_str.c_str()); } @@ -1826,7 +1826,7 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) { for (size_t z = 0; (z < 4 * 9) && (pa.target_card_refs[z] != 0xFFFF); z++) { auto target_card = s->card_for_set_card_ref(pa.target_card_refs[z]); if (target_card) { - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string ref_str = s->debug_str_for_card_ref(pa.target_card_refs[z]); log.debug("on target card ref %s", ref_str.c_str()); } @@ -1856,7 +1856,7 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) { this->subtract_or_check_atk_or_def_points_for_action(pa, 1); } for (size_t z = 0; (z < pa.action_card_refs.size()) && (pa.action_card_refs[z] != 0xFFFF); z++) { - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string ref_str = s->debug_str_for_card_ref(pa.action_card_refs[z]); log.debug("discarding %s from hand", ref_str.c_str()); } diff --git a/src/Episode3/PlayerStateSubordinates.cc b/src/Episode3/PlayerStateSubordinates.cc index 3c8c0f9c..2a54eea6 100644 --- a/src/Episode3/PlayerStateSubordinates.cc +++ b/src/Episode3/PlayerStateSubordinates.cc @@ -64,11 +64,11 @@ void Condition::clear_FF() { std::string Condition::str(shared_ptr s) const { auto card_ref_str = s->debug_str_for_card_ref(this->card_ref); auto giver_ref_str = s->debug_str_for_card_ref(this->condition_giver_card_ref); - return string_printf( + return phosg::string_printf( "Condition[type=%s, turns=%hhu, a_arg=%hhd, dice=%hhu, flags=%02hhX, " "def_eff_index=%hhu, ref=%s, value=%hd, giver_ref=%s " "percent=%hhu value8=%hd order=%hu a8=%hu]", - name_for_enum(this->type), + phosg::name_for_enum(this->type), this->remaining_turns, this->a_arg_value, this->dice_roll_value, @@ -103,7 +103,7 @@ void EffectResult::clear() { std::string EffectResult::str(shared_ptr s) const { string attacker_ref_str = s->debug_str_for_card_ref(this->attacker_card_ref); string target_ref_str = s->debug_str_for_card_ref(this->target_card_ref); - return string_printf( + return phosg::string_printf( "EffectResult[att_ref=%s, target_ref=%s, value=%hhd, " "cur_hp=%hhd, ap=%hhd, tp=%hhd, flags=%02hhX, op=%hhd, " "cond_index=%hhu, dice=%hhu]", @@ -139,7 +139,7 @@ bool CardShortStatus::operator!=(const CardShortStatus& other) const { std::string CardShortStatus::str(shared_ptr s) const { string loc_s = this->loc.str(); string ref_str = s->debug_str_for_card_ref(this->card_ref); - return string_printf( + return phosg::string_printf( "CardShortStatus[ref=%s, cur_hp=%hd, flags=%08" PRIX32 ", loc=%s, " "u1=%04hX, max_hp=%hhd, u2=%hhu]", ref_str.c_str(), @@ -193,13 +193,13 @@ std::string ActionState::str(shared_ptr s) const { string original_attacker_ref_s = s->debug_str_for_card_ref(this->original_attacker_card_ref); string target_refs_s = s->debug_str_for_card_refs(this->target_card_refs); string action_refs_s = s->debug_str_for_card_refs(this->action_card_refs); - return string_printf( + return phosg::string_printf( "ActionState[client=%hu, u=%hhu, facing=%s, attacker_ref=%s, " "def_ref=%s, target_refs=%s, action_refs=%s, " "orig_attacker_ref=%s]", this->client_id.load(), this->unused, - name_for_enum(this->facing_direction), + phosg::name_for_enum(this->facing_direction), attacker_ref_s.c_str(), defense_ref_s.c_str(), target_refs_s.c_str(), @@ -243,7 +243,7 @@ std::string ActionChain::str(shared_ptr s) const { string unknown_card_ref_a3_s = s->debug_str_for_card_ref(this->unknown_card_ref_a3); string attack_action_card_refs_s = s->debug_str_for_card_refs(this->attack_action_card_refs); string target_card_refs_s = s->debug_str_for_card_refs(this->target_card_refs); - return string_printf( + return phosg::string_printf( "ActionChain[eff_ap=%hhd, eff_tp=%hhd, ap_bonus=%hhd, damage=%hhd, " "acting_ref=%s, unknown_ref_a3=%s, attack_action_refs=%s, " "attack_action_ref_count=%hhu, medium=%s, target_ref_count=%hhu, " @@ -258,9 +258,9 @@ std::string ActionChain::str(shared_ptr s) const { unknown_card_ref_a3_s.c_str(), attack_action_card_refs_s.c_str(), this->attack_action_card_ref_count, - name_for_enum(this->attack_medium), + phosg::name_for_enum(this->attack_medium), this->target_card_ref_count, - name_for_enum(this->action_subphase), + phosg::name_for_enum(this->action_subphase), this->strike_count, this->damage_multiplier, this->attack_number, @@ -341,7 +341,7 @@ std::string ActionChainWithConds::str(shared_ptr s) const { if (ret.back() != '[') { ret += ", "; } - ret += string_printf("%zu:", z); + ret += phosg::string_printf("%zu:", z); ret += this->conditions[z].str(s); } } @@ -580,7 +580,7 @@ std::string ActionMetadata::str(shared_ptr s) const { string target_card_refs_s = s->debug_str_for_card_refs(this->target_card_refs); string defense_card_refs_s = s->debug_str_for_card_refs(this->defense_card_refs); string original_attacker_card_refs_s = s->debug_str_for_card_refs(this->original_attacker_card_refs); - return string_printf( + return phosg::string_printf( "ActionMetadata[ref=%s, target_ref_count=%hhu, def_ref_count=%hhu, " "subphase=%s, def_power=%hhd, def_bonus=%hhd, " "att_bonus=%hhd, flags=%08" PRIX32 ", target_refs=%s, " @@ -588,7 +588,7 @@ std::string ActionMetadata::str(shared_ptr s) const { card_ref_s.c_str(), this->target_card_ref_count, this->defense_card_ref_count, - name_for_enum(this->action_subphase), + phosg::name_for_enum(this->action_subphase), this->defense_power, this->defense_bonus, this->attack_bonus, @@ -683,7 +683,7 @@ std::string HandAndEquipState::str(shared_ptr s) const { string set_card_refs_s = s->debug_str_for_card_refs(this->set_card_refs); string hand_card_refs2_s = s->debug_str_for_card_refs(this->hand_card_refs2); string set_card_refs2_s = s->debug_str_for_card_refs(this->set_card_refs2); - return string_printf( + return phosg::string_printf( "HandAndEquipState[dice=[%hhu, %hhu], atk=%hhu, def=%hhu, atk2=%hhu, " "a1=%hhu, total_set_cost=%hhu, is_cpu=%hhu, assist_flags=%08" PRIX32 ", " "hand_refs=%s, assist_ref=%s, set_refs=%s, sc_ref=%s, hand_refs2=%s, " @@ -858,7 +858,7 @@ static bool is_card_within_range( const parray& range, const Location& anchor_loc, const CardShortStatus& ss, - PrefixedLogger* log) { + phosg::PrefixedLogger* log) { if (ss.card_ref == 0xFFFF) { if (log) { log->debug("is_card_within_range: (false) ss.card_ref missing"); @@ -899,7 +899,7 @@ vector get_card_refs_within_range( const parray& range, const Location& loc, const parray& short_statuses, - PrefixedLogger* log) { + phosg::PrefixedLogger* log) { vector ret; if (is_card_within_range(range, loc, short_statuses[0], log)) { if (log) { diff --git a/src/Episode3/PlayerStateSubordinates.hh b/src/Episode3/PlayerStateSubordinates.hh index 9be7556d..e680b74d 100644 --- a/src/Episode3/PlayerStateSubordinates.hh +++ b/src/Episode3/PlayerStateSubordinates.hh @@ -329,6 +329,6 @@ std::vector get_card_refs_within_range( const parray& range, const Location& loc, const parray& short_statuses, - PrefixedLogger* log = nullptr); + phosg::PrefixedLogger* log = nullptr); } // namespace Episode3 diff --git a/src/Episode3/RulerServer.cc b/src/Episode3/RulerServer.cc index 96e5cd73..f9591daa 100644 --- a/src/Episode3/RulerServer.cc +++ b/src/Episode3/RulerServer.cc @@ -15,8 +15,8 @@ void compute_effective_range( uint16_t card_id, const Location& loc, shared_ptr map_and_rules, - PrefixedLogger* log) { - if (log && log->should_log(LogLevel::DEBUG)) { + phosg::PrefixedLogger* log) { + if (log && log->should_log(phosg::LogLevel::DEBUG)) { string loc_str = loc.str(); log->debug("compute_effective_range: card_id=#%04hX, loc=%s", card_id, loc_str.c_str()); log->debug("compute_effective_range: map_and_rules->map:"); @@ -941,7 +941,7 @@ bool RulerServer::check_usability_or_condition_apply( AttackMedium attack_medium) const { auto s = this->server(); bool is_nte = s->options.is_nte(); - auto log = s->log_stack(string_printf("check_usability_or_condition_apply(%02hhX, #%04hX, %02hhX, #%04hX, #%04hX, %02hhX, %s, %s): ", client_id1, card_id1, client_id2, card_id2, card_id3, def_effect_index, is_item_usability_check ? "true" : "false", name_for_enum(attack_medium))); + auto log = s->log_stack(phosg::string_printf("check_usability_or_condition_apply(%02hhX, #%04hX, %02hhX, #%04hX, #%04hX, %02hhX, %s, %s): ", client_id1, card_id1, client_id2, card_id2, card_id3, def_effect_index, is_item_usability_check ? "true" : "false", phosg::name_for_enum(attack_medium))); if (static_cast(attack_medium) & 0x80) { attack_medium = AttackMedium::UNKNOWN; @@ -969,7 +969,7 @@ bool RulerServer::check_usability_or_condition_apply( } criterion_code = ce1->def.effects[def_effect_index].apply_criterion; } - log.debug("criterion_code=%s", name_for_enum(criterion_code)); + log.debug("criterion_code=%s", phosg::name_for_enum(criterion_code)); // For item usability checks, prevent criteria that depend on player // positioning/team setup @@ -2059,7 +2059,7 @@ shared_ptr RulerServer::definition_for_card_id(uint3 uint32_t RulerServer::get_card_id_with_effective_range( uint16_t card_ref, uint16_t card_id_override, TargetMode* out_target_mode) const { - auto log = this->server()->log_stack(string_printf("get_card_id_with_effective_range(@%04hX, #%04hX): ", card_ref, card_id_override)); + auto log = this->server()->log_stack(phosg::string_printf("get_card_id_with_effective_range(@%04hX, #%04hX): ", card_ref, card_id_override)); uint16_t card_id = (card_id_override == 0xFFFF) ? this->card_id_for_card_ref(card_ref) diff --git a/src/Episode3/RulerServer.hh b/src/Episode3/RulerServer.hh index d6b34a09..ce347760 100644 --- a/src/Episode3/RulerServer.hh +++ b/src/Episode3/RulerServer.hh @@ -19,7 +19,7 @@ void compute_effective_range( uint16_t card_id, const Location& loc, std::shared_ptr map_and_rules, - PrefixedLogger* log = nullptr); + phosg::PrefixedLogger* log = nullptr); bool card_linkage_is_valid( std::shared_ptr right_def, diff --git a/src/Episode3/Server.cc b/src/Episode3/Server.cc index 639d60c3..5a054860 100644 --- a/src/Episode3/Server.cc +++ b/src/Episode3/Server.cc @@ -82,7 +82,7 @@ Server::Server(shared_ptr lobby, Options&& options) Server::~Server() noexcept(false) { if (this->logger_stack.size() != 1) { - throw logic_error(string_printf("incorrect logger stack size: expected 1, received %zu", this->logger_stack.size())); + throw logic_error(phosg::string_printf("incorrect logger stack size: expected 1, received %zu", this->logger_stack.size())); } delete this->logger_stack.back(); } @@ -125,7 +125,7 @@ Server::StackLogger::StackLogger(const Server* s, const std::string& prefix) s->logger_stack.push_back(this); } -Server::StackLogger::StackLogger(const Server* s, const std::string& prefix, LogLevel min_level) +Server::StackLogger::StackLogger(const Server* s, const std::string& prefix, phosg::LogLevel min_level) : PrefixedLogger(prefix, min_level), server(s) { s->logger_stack.push_back(this); @@ -172,9 +172,9 @@ std::string Server::debug_str_for_card_ref(uint16_t card_ref) const { auto ce = this->definition_for_card_ref(card_ref); if (ce) { string name = ce->def.en_name.decode(); - return string_printf("@%04hX (#%04" PRIX32 " %s)", card_ref, ce->def.card_id.load(), name.c_str()); + return phosg::string_printf("@%04hX (#%04" PRIX32 " %s)", card_ref, ce->def.card_id.load(), name.c_str()); } else { - return string_printf("@%04hX (missing)", card_ref); + return phosg::string_printf("@%04hX (missing)", card_ref); } } @@ -185,9 +185,9 @@ std::string Server::debug_str_for_card_id(uint16_t card_id) const { auto ce = this->definition_for_card_id(card_id); if (ce) { string name = ce->def.en_name.decode(); - return string_printf("#%04hX (%s)", card_id, name.c_str()); + return phosg::string_printf("#%04hX (%s)", card_id, name.c_str()); } else { - return string_printf("#%04hX (missing)", card_id); + return phosg::string_printf("#%04hX (missing)", card_id); } } @@ -240,7 +240,7 @@ void Server::send(const void* data, size_t size, uint8_t command, bool enable_ma !(this->options.behavior_flags & BehaviorFlag::DISABLE_MASKING) && (size >= 8)) { masked_data.assign(reinterpret_cast(data), size); - uint8_t mask_key = (random_object() % 0xFF) + 1; + uint8_t mask_key = (phosg::random_object() % 0xFF) + 1; set_mask_for_ep3_game_command(masked_data.data(), masked_data.size(), mask_key); data = masked_data.data(); size = masked_data.size(); @@ -260,7 +260,7 @@ void Server::send(const void* data, size_t size, uint8_t command, bool enable_ma } else if ((this->options.behavior_flags & BehaviorFlag::LOG_COMMANDS_IF_LOBBY_MISSING) && this->log().info("Generated command")) { - print_data(stderr, data, size, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::print_data(stderr, data, size, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); } } @@ -272,9 +272,9 @@ void Server::send_6xB4x46() const { // debugging easier. G_ServerVersionStrings_Ep3_6xB4x46 cmd; cmd.version_signature.encode(this->options.is_nte() ? VERSION_SIGNATURE_NTE : VERSION_SIGNATURE, 1); - cmd.date_str1.encode(format_time(this->options.card_index->definitions_mtime() * 1000000), 1); - string build_date = format_time(BUILD_TIMESTAMP); - cmd.date_str2.encode(string_printf("newserv %s compiled at %s", GIT_REVISION_HASH, build_date.c_str()), 1); + cmd.date_str1.encode(phosg::format_time(this->options.card_index->definitions_mtime() * 1000000), 1); + string build_date = phosg::format_time(BUILD_TIMESTAMP); + cmd.date_str2.encode(phosg::string_printf("newserv %s compiled at %s", GIT_REVISION_HASH, build_date.c_str()), 1); this->send(cmd); } @@ -283,7 +283,7 @@ string Server::prepare_6xB6x41_map_definition(shared_ptr ma const auto& compressed = vm->compressed(is_nte); - StringWriter w; + phosg::StringWriter w; uint32_t subcommand_size = (compressed.size() + sizeof(G_MapData_Ep3_6xB6x41) + 3) & (~3); w.put({{{{0xB6, 0, 0}, subcommand_size}, 0x41, {}}, vm->map->map_number.load(), compressed.size(), 0}); w.write(compressed); @@ -347,7 +347,7 @@ __attribute__((format(printf, 2, 3))) void Server::send_debug_message_printf(con if (l && (this->options.behavior_flags & Episode3::BehaviorFlag::ENABLE_STATUS_MESSAGES)) { va_list va; va_start(va, fmt); - std::string buf = string_vprintf(fmt, va); + std::string buf = phosg::string_vprintf(fmt, va); va_end(va); send_text_message(l, buf); } @@ -358,7 +358,7 @@ __attribute__((format(printf, 2, 3))) void Server::send_info_message_printf(cons if (l) { va_list va; va_start(va, fmt); - std::string buf = string_vprintf(fmt, va); + std::string buf = phosg::string_vprintf(fmt, va); va_end(va); send_text_message(l, buf); } @@ -862,7 +862,7 @@ void Server::draw_phase_after() { // facilities used are different. uint64_t limit_5mins = this->map_and_rules->rules.overall_time_limit; uint64_t end_usecs = this->battle_start_usecs + (limit_5mins * 300 * 1000 * 1000); - if (now() >= end_usecs) { + if (phosg::now() >= end_usecs) { this->overall_time_expired = true; } } @@ -972,7 +972,7 @@ void Server::end_action_phase() { bool Server::enqueue_attack_or_defense(uint8_t client_id, ActionState* pa) { auto log = this->log_stack("enqueue_attack_or_defense: "); - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string s = pa->str(this->shared_from_this()); log.debug("input: %s", s.c_str()); } @@ -1022,7 +1022,7 @@ bool Server::enqueue_attack_or_defense(uint8_t client_id, ActionState* pa) { size_t attack_index = this->num_pending_attacks++; this->pending_attacks[attack_index] = *pa; - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string pa_str = this->pending_attacks[attack_index].str(this->shared_from_this()); log.debug("set pending attack %zu: %s", attack_index, pa_str.c_str()); } @@ -1711,7 +1711,7 @@ void Server::setup_and_start_battle() { cmd.start_battle = 1; this->send(cmd); } - this->battle_start_usecs = now(); + this->battle_start_usecs = phosg::now(); this->send_6xB4x46(); @@ -1831,8 +1831,8 @@ void Server::on_server_data_input(shared_ptr sender_c, const string& dat auto header = check_size_t(data, 0xFFFF); size_t expected_size = header.size * 4; if (expected_size < data.size()) { - print_data(stderr, data); - throw runtime_error(string_printf("command is incomplete: expected %zX bytes, received %zX bytes", expected_size, data.size())); + phosg::print_data(stderr, data); + throw runtime_error(phosg::string_printf("command is incomplete: expected %zX bytes, received %zX bytes", expected_size, data.size())); } if (header.subcommand != 0xB3) { throw runtime_error("server data command is not 6xB3"); @@ -2259,7 +2259,7 @@ void Server::handle_CAx14_update_deck_during_setup(shared_ptr, const str } } if (verify_error) { - throw runtime_error(string_printf("invalid deck: -0x%" PRIX32, verify_error)); + throw runtime_error(phosg::string_printf("invalid deck: -0x%" PRIX32, verify_error)); } if (!this->options.is_nte() && !(this->options.behavior_flags & BehaviorFlag::SKIP_D1_D2_REPLACE)) { this->ruler_server->replace_D1_D2_rank_cards_with_Attack(entry.card_ids); @@ -2579,7 +2579,7 @@ void Server::handle_CAx40_map_list_request(shared_ptr sender_c, const st uint8_t language = sender_c ? sender_c->language() : 1; const auto& list_data = this->options.map_index->get_compressed_list(num_players, language); - StringWriter w; + phosg::StringWriter w; uint32_t subcommand_size = (list_data.size() + sizeof(G_MapList_Ep3_6xB6x40) + 3) & (~3); w.put(G_MapList_Ep3_6xB6x40{{{{0xB6, 0, 0}, subcommand_size}, 0x40, {}}, list_data.size(), 0}); w.write(list_data); @@ -2828,7 +2828,7 @@ void Server::unknown_8023EEF4() { auto card = this->attack_cards[this->unknown_a14]; if (this->get_current_team_turn() == card->get_team_id()) { ActionState as = this->pending_attacks_with_cards[this->unknown_a14]; - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { log.debug("card @%04hX #%04hX can attack", card->get_card_ref(), card->get_card_id()); string as_str = as.str(this->shared_from_this()); log.debug("as: %s", as_str.c_str()); @@ -2838,7 +2838,7 @@ void Server::unknown_8023EEF4() { } else { this->replace_targets_due_to_destruction_or_conditions(&as); } - if (log.should_log(LogLevel::DEBUG)) { + if (log.should_log(phosg::LogLevel::DEBUG)) { string as_str = as.str(this->shared_from_this()); log.debug("as after target replacement: %s", as_str.c_str()); } diff --git a/src/Episode3/Server.hh b/src/Episode3/Server.hh index ebb81e56..17622be4 100644 --- a/src/Episode3/Server.hh +++ b/src/Episode3/Server.hh @@ -72,7 +72,7 @@ public: std::shared_ptr card_index; std::shared_ptr map_index; uint32_t behavior_flags; - std::shared_ptr opt_rand_stream; + std::shared_ptr opt_rand_stream; std::shared_ptr opt_rand_crypt; std::shared_ptr tournament; std::array, 5> trap_card_ids; @@ -85,10 +85,10 @@ public: ~Server() noexcept(false); void init(); - class StackLogger : public PrefixedLogger { + class StackLogger : public phosg::PrefixedLogger { public: StackLogger(const Server* s, const std::string& prefix); - StackLogger(const Server* s, const std::string& prefix, LogLevel min_level); + StackLogger(const Server* s, const std::string& prefix, phosg::LogLevel min_level); StackLogger(const StackLogger&) = delete; StackLogger(StackLogger&&); StackLogger& operator=(const StackLogger&) = delete; @@ -109,7 +109,7 @@ public: for (size_t z = 0; z < count; z++) { if (refs[z] != 0xFFFF) { std::string ref_str = this->debug_str_for_card_ref(refs[z]); - ret += string_printf("%zu:%s ", z, ref_str.c_str()); + ret += phosg::string_printf("%zu:%s ", z, ref_str.c_str()); } } if (ret.size() > 1) { diff --git a/src/Episode3/Tournament.cc b/src/Episode3/Tournament.cc index 3489b820..0cefe159 100644 --- a/src/Episode3/Tournament.cc +++ b/src/Episode3/Tournament.cc @@ -49,16 +49,16 @@ string Tournament::Team::str() const { num_com_players += player.is_com(); } - string ret = string_printf("[Team/%zu %s %zuH/%zuC/%zuP name=%s pass=%s rounds=%zu", + string ret = phosg::string_printf("[Team/%zu %s %zuH/%zuC/%zuP name=%s pass=%s rounds=%zu", this->index, this->is_active ? "active" : "inactive", num_human_players, num_com_players, this->max_players, this->name.c_str(), this->password.c_str(), this->num_rounds_cleared); for (const auto& player : this->players) { if (player.is_human()) { if (player.player_name.empty()) { - ret += string_printf(" %08" PRIX32, player.account_id); + ret += phosg::string_printf(" %08" PRIX32, player.account_id); } else { - ret += string_printf(" %08" PRIX32 " (%s)", player.account_id, player.player_name.c_str()); + ret += phosg::string_printf(" %08" PRIX32 " (%s)", player.account_id, player.player_name.c_str()); } } } @@ -206,7 +206,7 @@ Tournament::Match::Match( string Tournament::Match::str() const { string winner_str = this->winner_team ? this->winner_team->str() : "(none)"; - return string_printf("[Match round=%zu winner=%s]", this->round_num, winner_str.c_str()); + return phosg::string_printf("[Match round=%zu winner=%s]", this->round_num, winner_str.c_str()); } bool Tournament::Match::resolve_if_skippable() { @@ -230,7 +230,7 @@ bool Tournament::Match::resolve_if_skippable() { // entirely and just make one team advance arbitrarily (note that this also // handles the case where both preceding winner teams are empty) if (!winner_a->has_any_human_players() && !winner_b->has_any_human_players()) { - this->set_winner_team((random_object() & 1) ? winner_b : winner_a); + this->set_winner_team((phosg::random_object() & 1) ? winner_b : winner_a); return true; } @@ -318,7 +318,7 @@ Tournament::Tournament( const Rules& rules, size_t num_teams, uint8_t flags) - : log(string_printf("[Tournament:%s] ", name.c_str())), + : log(phosg::string_printf("[Tournament:%s] ", name.c_str())), map_index(map_index), com_deck_index(com_deck_index), name(name), @@ -342,8 +342,8 @@ Tournament::Tournament( Tournament::Tournament( shared_ptr map_index, shared_ptr com_deck_index, - const JSON& json) - : log(string_printf("[Tournament:%s] ", json.get_string("name").c_str())), + const phosg::JSON& json) + : log(phosg::string_printf("[Tournament:%s] ", json.get_string("name").c_str())), map_index(map_index), com_deck_index(com_deck_index), source_json(json), @@ -504,14 +504,14 @@ void Tournament::create_bracket_matches() { this->final_match = current_round_matches.at(0); } -JSON Tournament::json() const { - auto teams_list = JSON::list(); +phosg::JSON Tournament::json() const { + auto teams_list = phosg::JSON::list(); for (auto team : this->teams) { - auto players_list = JSON::list(); + auto players_list = phosg::JSON::list(); for (const auto& player : team->players) { if (player.is_human()) { if (!player.player_name.empty()) { - players_list.emplace_back(JSON::list({player.account_id, player.player_name})); + players_list.emplace_back(phosg::JSON::list({player.account_id, player.player_name})); } else { players_list.emplace_back(player.account_id); } @@ -519,7 +519,7 @@ JSON Tournament::json() const { players_list.emplace_back(player.com_deck->deck_name); } } - teams_list.emplace_back(JSON::dict({ + teams_list.emplace_back(phosg::JSON::dict({ {"max_players", team->max_players}, {"player_specs", std::move(players_list)}, {"name", team->name}, @@ -527,7 +527,7 @@ JSON Tournament::json() const { {"num_rounds_cleared", team->num_rounds_cleared}, })); } - return JSON::dict({ + return phosg::JSON::dict({ {"name", this->name}, {"map_number", this->map->map_number}, {"rules", this->rules.json()}, @@ -649,7 +649,7 @@ void Tournament::start() { if (this->flags & Flag::SHUFFLE_ENTRIES) { // Shuffle all the tournament entries for (size_t z = this->teams.size(); z > 0; z--) { - size_t index = random_object() % z; + size_t index = phosg::random_object() % z; if (index != z - 1) { this->teams[z - 1].swap(this->teams[index]); } @@ -665,7 +665,7 @@ void Tournament::start() { auto m = this->zero_round_matches[z]; auto t = m->winner_team; if (t->name.empty()) { - t->name = has_com_teams ? string_printf("COM:%zu", z) : "(no entrant)"; + t->name = has_com_teams ? phosg::string_printf("COM:%zu", z) : "(no entrant)"; } for (const auto& player : t->players) { if (player.is_com()) { @@ -791,16 +791,16 @@ TournamentIndex::TournamentIndex( return; } - JSON json; + phosg::JSON json; try { - json = JSON::parse(load_file(this->state_filename)); - } catch (const cannot_open_file&) { - json = JSON::list(); + json = phosg::JSON::parse(phosg::load_file(this->state_filename)); + } catch (const phosg::cannot_open_file&) { + json = phosg::JSON::list(); } if (json.is_list()) { if (json.size() > 0x20) { - throw runtime_error("tournament JSON list length is incorrect"); + throw runtime_error("tournament phosg::JSON list length is incorrect"); } for (size_t z = 0; z < min(json.size(), 0x20); z++) { if (!json.at(z).is_null()) { @@ -815,13 +815,13 @@ TournamentIndex::TournamentIndex( } } else if (json.is_dict()) { if (json.size() > 0x20) { - throw runtime_error("tournament JSON dict length is incorrect"); + throw runtime_error("tournament phosg::JSON dict length is incorrect"); } for (const auto& it : json.as_dict()) { auto tourn = make_shared(this->map_index, this->com_deck_index, *it.second); tourn->init(); if (!this->name_to_tournament.emplace(tourn->get_name(), tourn).second) { - // This is logic_error instead of runtime_error because JSON dicts are + // This is logic_error instead of runtime_error because phosg::JSON dicts are // supposed to already have unique keys throw logic_error("multiple tournaments have the same name: " + tourn->get_name()); } @@ -829,7 +829,7 @@ TournamentIndex::TournamentIndex( this->menu_item_id_to_tournament.emplace_back(tourn); } } else { - throw runtime_error("tournament state root JSON is not a list or dict"); + throw runtime_error("tournament state root phosg::JSON is not a list or dict"); } } @@ -838,11 +838,11 @@ void TournamentIndex::save() const { return; } - auto json = JSON::dict(); + auto json = phosg::JSON::dict(); for (const auto& it : this->name_to_tournament) { json.emplace(it.second->get_name(), it.second->json()); } - save_file(this->state_filename, json.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::HEX_INTEGERS | JSON::SerializeOption::ESCAPE_CONTROLS_ONLY)); + phosg::save_file(this->state_filename, json.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS | phosg::JSON::SerializeOption::ESCAPE_CONTROLS_ONLY)); } shared_ptr TournamentIndex::create_tournament( diff --git a/src/Episode3/Tournament.hh b/src/Episode3/Tournament.hh index 8fb62423..adefe6d0 100644 --- a/src/Episode3/Tournament.hh +++ b/src/Episode3/Tournament.hh @@ -49,7 +49,7 @@ public: bool is_com() const; bool is_human() const; - JSON json() const; + phosg::JSON json() const; }; struct Team : public std::enable_shared_from_this { @@ -115,11 +115,11 @@ public: Tournament( std::shared_ptr map_index, std::shared_ptr com_deck_index, - const JSON& json); + const phosg::JSON& json); ~Tournament() = default; void init(); - JSON json() const; + phosg::JSON json() const; inline const std::string& get_name() const { return this->name; @@ -165,11 +165,11 @@ public: private: void create_bracket_matches(); - PrefixedLogger log; + phosg::PrefixedLogger log; std::shared_ptr map_index; std::shared_ptr com_deck_index; - JSON source_json; + phosg::JSON source_json; std::string name; std::shared_ptr map; Rules rules; diff --git a/src/FileContentsCache.cc b/src/FileContentsCache.cc index 91fb7679..85b78807 100644 --- a/src/FileContentsCache.cc +++ b/src/FileContentsCache.cc @@ -20,7 +20,7 @@ FileContentsCache::File::File( shared_ptr FileContentsCache::replace( const string& name, string&& data, uint64_t t) { if (t == 0) { - t = now(); + t = phosg::now(); } auto new_file = make_shared(name, std::move(data), t); auto emplace_ret = this->name_to_file.emplace(name, new_file); @@ -37,7 +37,7 @@ shared_ptr FileContentsCache::replace( } FileContentsCache::GetResult FileContentsCache::get_or_load(const std::string& name) { - return this->get(name, load_file); + return this->get(name, phosg::load_file); } FileContentsCache::GetResult FileContentsCache::get_or_load(const char* name) { @@ -59,7 +59,7 @@ shared_ptr FileContentsCache::get_or_throw( FileContentsCache::GetResult FileContentsCache::get(const std::string& name, std::function generate) { - uint64_t t = now(); + uint64_t t = phosg::now(); try { auto& entry = this->name_to_file.at(name); if (this->ttl_usecs && (t - entry->load_time < this->ttl_usecs)) { diff --git a/src/FileContentsCache.hh b/src/FileContentsCache.hh index 6f02af69..6d49dfd2 100644 --- a/src/FileContentsCache.hh +++ b/src/FileContentsCache.hh @@ -78,7 +78,7 @@ public: } template GetObjResult get_obj(NameT name, std::function generate) { - uint64_t t = now(); + uint64_t t = phosg::now(); try { auto& f = this->name_to_file.at(name); if (f->data->size() != sizeof(T)) { diff --git a/src/FunctionCompiler.cc b/src/FunctionCompiler.cc index 56de9f44..651401d4 100644 --- a/src/FunctionCompiler.cc +++ b/src/FunctionCompiler.cc @@ -59,7 +59,7 @@ string CompiledFunctionCode::generate_client_command_t( footer.entrypoint_addr_offset = this->entrypoint_offset_offset; footer.unused2.clear(0); - StringWriter w; + phosg::StringWriter w; if (!label_writes.empty()) { string modified_code = this->code; for (const auto& it : label_writes) { @@ -91,7 +91,7 @@ string CompiledFunctionCode::generate_client_command_t( footer.relocations_offset = override_relocations_offset; } else { for (uint16_t delta : this->relocation_deltas) { - w.put(delta); + w.put>(delta); } if (this->relocation_deltas.size() & 1) { w.put_u16(0); @@ -161,24 +161,24 @@ shared_ptr compile_function_code( } // Look in the function directory first, then the system directory - string asm_filename = string_printf("%s/%s.%s.inc.s", function_directory.c_str(), name.c_str(), arch_name_token); - if (!isfile(asm_filename)) { - asm_filename = string_printf("%s/%s.%s.inc.s", system_directory.c_str(), name.c_str(), arch_name_token); + string asm_filename = phosg::string_printf("%s/%s.%s.inc.s", function_directory.c_str(), name.c_str(), arch_name_token); + if (!phosg::isfile(asm_filename)) { + asm_filename = phosg::string_printf("%s/%s.%s.inc.s", system_directory.c_str(), name.c_str(), arch_name_token); } - if (isfile(asm_filename)) { + if (phosg::isfile(asm_filename)) { if (!get_include_stack.emplace(name).second) { throw runtime_error("mutual recursion between includes: " + name); } ResourceDASM::EmulatorBase::AssembleResult ret; switch (arch) { case CompiledFunctionCode::Architecture::POWERPC: - ret = ResourceDASM::PPC32Emulator::assemble(load_file(asm_filename), get_include); + ret = ResourceDASM::PPC32Emulator::assemble(phosg::load_file(asm_filename), get_include); break; case CompiledFunctionCode::Architecture::X86: - ret = ResourceDASM::X86Emulator::assemble(load_file(asm_filename), get_include); + ret = ResourceDASM::X86Emulator::assemble(phosg::load_file(asm_filename), get_include); break; case CompiledFunctionCode::Architecture::SH4: - ret = ResourceDASM::SH4Emulator::assemble(load_file(asm_filename), get_include); + ret = ResourceDASM::SH4Emulator::assemble(phosg::load_file(asm_filename), get_include); break; default: throw runtime_error("unknown architecture"); @@ -188,12 +188,12 @@ shared_ptr compile_function_code( } string bin_filename = function_directory + "/" + name + ".inc.bin"; - if (isfile(bin_filename)) { - return load_file(bin_filename); + if (phosg::isfile(bin_filename)) { + return phosg::load_file(bin_filename); } bin_filename = system_directory + "/" + name + ".inc.bin"; - if (isfile(bin_filename)) { - return load_file(bin_filename); + if (phosg::isfile(bin_filename)) { + return phosg::load_file(bin_filename); } throw runtime_error("data not found for include: " + name + " (from " + asm_filename + " or " + bin_filename + ")"); }; @@ -229,7 +229,7 @@ shared_ptr compile_function_code( set reloc_indexes; for (const auto& it : ret->label_offsets) { - if (starts_with(it.first, "reloc")) { + if (phosg::starts_with(it.first, "reloc")) { reloc_indexes.emplace(it.second / 4); } } @@ -260,28 +260,28 @@ FunctionCodeIndex::FunctionCodeIndex(const string& directory) { return; } - string system_dir_path = ends_with(directory, "/") ? (directory + "System") : (directory + "/System"); + string system_dir_path = phosg::ends_with(directory, "/") ? (directory + "System") : (directory + "/System"); uint32_t next_menu_item_id = 1; - for (const auto& subdir_name : list_directory_sorted(directory)) { - string subdir_path = ends_with(directory, "/") ? (directory + subdir_name) : (directory + "/" + subdir_name); - if (!isdir(subdir_path)) { + for (const auto& subdir_name : phosg::list_directory_sorted(directory)) { + string subdir_path = phosg::ends_with(directory, "/") ? (directory + subdir_name) : (directory + "/" + subdir_name); + if (!phosg::isdir(subdir_path)) { function_compiler_log.warning("Skipping %s (not a directory)", subdir_name.c_str()); continue; } - for (const auto& filename : list_directory_sorted(subdir_path)) { + for (const auto& filename : phosg::list_directory_sorted(subdir_path)) { try { - if (!ends_with(filename, ".s")) { + if (!phosg::ends_with(filename, ".s")) { continue; } string name = filename.substr(0, filename.size() - 2); - if (ends_with(name, ".inc")) { + if (phosg::ends_with(name, ".inc")) { continue; } - bool is_patch = ends_with(name, ".patch"); + bool is_patch = phosg::ends_with(name, ".patch"); if (is_patch) { name.resize(name.size() - 6); } @@ -290,15 +290,15 @@ FunctionCodeIndex::FunctionCodeIndex(const string& directory) { CompiledFunctionCode::Architecture arch = CompiledFunctionCode::Architecture::UNKNOWN; uint32_t specific_version = 0; string short_name = name; - if (ends_with(name, ".ppc")) { + if (phosg::ends_with(name, ".ppc")) { arch = CompiledFunctionCode::Architecture::POWERPC; name.resize(name.size() - 4); short_name = name; - } else if (ends_with(name, ".x86")) { + } else if (phosg::ends_with(name, ".x86")) { arch = CompiledFunctionCode::Architecture::X86; name.resize(name.size() - 4); short_name = name; - } else if (ends_with(name, ".sh4")) { + } else if (phosg::ends_with(name, ".sh4")) { arch = CompiledFunctionCode::Architecture::SH4; name.resize(name.size() - 4); short_name = name; @@ -321,11 +321,11 @@ FunctionCodeIndex::FunctionCodeIndex(const string& directory) { } string path = subdir_path + "/" + filename; - string text = load_file(path); + string text = phosg::load_file(path); auto code = compile_function_code(arch, subdir_path, system_dir_path, name, text); if (code->index != 0) { if (!this->index_to_function.emplace(code->index, code).second) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "duplicate function index: %08" PRIX32, code->index)); } } @@ -338,11 +338,11 @@ FunctionCodeIndex::FunctionCodeIndex(const string& directory) { this->menu_item_id_and_specific_version_to_patch_function.emplace( static_cast(code->menu_item_id) << 32 | specific_version, code); this->name_and_specific_version_to_patch_function.emplace( - string_printf("%s-%08" PRIX32, short_name.c_str(), specific_version), code); + phosg::string_printf("%s-%08" PRIX32, short_name.c_str(), specific_version), code); } - string index_prefix = code->index ? string_printf("%02X => ", code->index) : ""; - string patch_prefix = is_patch ? string_printf("[%08" PRIX32 "/%08" PRIX32 "] ", code->menu_item_id, code->specific_version) : ""; + string index_prefix = code->index ? phosg::string_printf("%02X => ", code->index) : ""; + string patch_prefix = is_patch ? phosg::string_printf("[%08" PRIX32 "/%08" PRIX32 "] ", code->menu_item_id, code->specific_version) : ""; function_compiler_log.info("Compiled function %s%s%s (%s)", index_prefix.c_str(), patch_prefix.c_str(), name.c_str(), name_for_architecture(code->arch)); @@ -354,13 +354,13 @@ FunctionCodeIndex::FunctionCodeIndex(const string& directory) { } shared_ptr FunctionCodeIndex::patch_menu(uint32_t specific_version) const { - auto suffix = string_printf("-%08" PRIX32, specific_version); + auto suffix = phosg::string_printf("-%08" PRIX32, specific_version); auto ret = make_shared(MenuID::PATCHES, "Patches"); ret->items.emplace_back(PatchesMenuItemID::GO_BACK, "Go back", "Return to the\nmain menu", 0); for (const auto& it : this->name_and_specific_version_to_patch_function) { const auto& fn = it.second; - if (fn->hide_from_patches_menu || !ends_with(it.first, suffix)) { + if (fn->hide_from_patches_menu || !phosg::ends_with(it.first, suffix)) { continue; } ret->items.emplace_back( @@ -374,13 +374,13 @@ shared_ptr FunctionCodeIndex::patch_menu(uint32_t specific_version) shared_ptr FunctionCodeIndex::patch_switches_menu( uint32_t specific_version, const std::unordered_set& auto_patches_enabled) const { - auto suffix = string_printf("-%08" PRIX32, specific_version); + auto suffix = phosg::string_printf("-%08" PRIX32, specific_version); auto ret = make_shared(MenuID::PATCH_SWITCHES, "Patch switches"); ret->items.emplace_back(PatchesMenuItemID::GO_BACK, "Go back", "Return to the\nmain menu", 0); for (const auto& it : this->name_and_specific_version_to_patch_function) { const auto& fn = it.second; - if (fn->hide_from_patches_menu || !ends_with(it.first, suffix)) { + if (fn->hide_from_patches_menu || !phosg::ends_with(it.first, suffix)) { continue; } string name; @@ -404,7 +404,7 @@ bool FunctionCodeIndex::patch_menu_empty(uint32_t specific_version) const { std::shared_ptr FunctionCodeIndex::get_patch( const std::string& name, uint32_t specific_version) const { return this->name_and_specific_version_to_patch_function.at( - string_printf("%s-%08" PRIX32, name.c_str(), specific_version)); + phosg::string_printf("%s-%08" PRIX32, name.c_str(), specific_version)); } DOLFileIndex::DOLFileIndex(const string& directory) { @@ -412,7 +412,7 @@ DOLFileIndex::DOLFileIndex(const string& directory) { function_compiler_log.info("Function compiler is not available"); return; } - if (!isdir(directory)) { + if (!phosg::isdir(directory)) { function_compiler_log.info("DOL file directory is missing"); return; } @@ -422,9 +422,9 @@ DOLFileIndex::DOLFileIndex(const string& directory) { menu->items.emplace_back(ProgramsMenuItemID::GO_BACK, "Go back", "Return to the\nmain menu", 0); uint32_t next_menu_item_id = 0; - for (const auto& filename : list_directory_sorted(directory)) { - bool is_dol = ends_with(filename, ".dol"); - bool is_compressed_dol = ends_with(filename, ".dol.prs"); + for (const auto& filename : phosg::list_directory_sorted(directory)) { + bool is_dol = phosg::ends_with(filename, ".dol"); + bool is_compressed_dol = phosg::ends_with(filename, ".dol.prs"); if (!is_dol && !is_compressed_dol) { continue; } @@ -436,13 +436,13 @@ DOLFileIndex::DOLFileIndex(const string& directory) { dol->name = name; string path = directory + "/" + filename; - string file_data = load_file(path); + string file_data = phosg::load_file(path); string description; if (is_compressed_dol) { size_t decompressed_size = prs_decompress_size(file_data); - StringWriter w; + phosg::StringWriter w; w.put_u32b(file_data.size()); w.put_u32b(decompressed_size); w.write(file_data); @@ -451,15 +451,15 @@ DOLFileIndex::DOLFileIndex(const string& directory) { } dol->data = std::move(w.str()); - string compressed_size_str = format_size(file_data.size()); - string decompressed_size_str = format_size(decompressed_size); + string compressed_size_str = phosg::format_size(file_data.size()); + string decompressed_size_str = phosg::format_size(decompressed_size); function_compiler_log.info("Loaded compressed DOL file %s (%s -> %s)", dol->name.c_str(), compressed_size_str.c_str(), decompressed_size_str.c_str()); - description = string_printf("$C6%s$C7\n%s\n%s (orig)", + description = phosg::string_printf("$C6%s$C7\n%s\n%s (orig)", dol->name.c_str(), compressed_size_str.c_str(), decompressed_size_str.c_str()); } else { - StringWriter w; + phosg::StringWriter w; w.put_u32b(0); w.put_u32b(file_data.size()); w.write(file_data); @@ -468,9 +468,9 @@ DOLFileIndex::DOLFileIndex(const string& directory) { } dol->data = std::move(w.str()); - string size_str = format_size(dol->data.size()); + string size_str = phosg::format_size(dol->data.size()); function_compiler_log.info("Loaded DOL file %s (%s)", filename.c_str(), size_str.c_str()); - description = string_printf("$C6%s$C7\n%s", dol->name.c_str(), size_str.c_str()); + description = phosg::string_printf("$C6%s$C7\n%s", dol->name.c_str(), size_str.c_str()); } this->name_to_file.emplace(dol->name, dol); @@ -503,7 +503,7 @@ uint32_t specific_version_for_gc_header_checksum(uint32_t header_checksum) { data.region_code = *region_code; for (uint8_t version_code = 0; version_code < 8; version_code++) { data.version_code = version_code; - uint32_t checksum = crc32(&data, sizeof(data)); + uint32_t checksum = phosg::crc32(&data, sizeof(data)); uint32_t specific_version = 0x33000030 | (*game_code2 << 16) | (*region_code << 8) | version_code; if (!checksum_to_specific_version.emplace(checksum, specific_version).second) { throw logic_error("multiple specific_versions have same header checksum"); @@ -515,7 +515,7 @@ uint32_t specific_version_for_gc_header_checksum(uint32_t header_checksum) { data.region_code = 'J'; data.system_code = 'D'; data.version_code = 0; - uint32_t checksum = crc32(&data, sizeof(data)); + uint32_t checksum = phosg::crc32(&data, sizeof(data)); uint32_t specific_version = 0x33004A54 | (*game_code2 << 16); if (!checksum_to_specific_version.emplace(checksum, specific_version).second) { throw logic_error("multiple specific_versions have same header checksum"); diff --git a/src/GSLArchive.cc b/src/GSLArchive.cc index 61260678..3863cb81 100644 --- a/src/GSLArchive.cc +++ b/src/GSLArchive.cc @@ -5,16 +5,15 @@ #include #include "Text.hh" +#include "Types.hh" using namespace std; -template +template struct GSLHeaderEntryT { - using U32T = typename std::conditional::type; - pstring filename; - U32T offset; // In pages, so actual offset is this * 0x800 - U32T size; + U32T offset; // In pages, so actual offset is this * 0x800 + U32T size; uint64_t unused; } __packed__; @@ -23,12 +22,12 @@ using GSLHeaderEntryBE = GSLHeaderEntryT; check_struct_size(GSLHeaderEntry, 0x30); check_struct_size(GSLHeaderEntryBE, 0x30); -template +template void GSLArchive::load_t() { - StringReader r(*this->data); + phosg::StringReader r(*this->data); uint64_t min_data_offset = 0xFFFFFFFFFFFFFFFF; while (r.where() < min_data_offset) { - const auto& entry = r.get>(); + const auto& entry = r.get>(); if (entry.filename.empty()) { break; } @@ -71,10 +70,10 @@ string GSLArchive::get_copy(const string& name) const { } } -StringReader GSLArchive::get_reader(const string& name) const { +phosg::StringReader GSLArchive::get_reader(const string& name) const { try { const auto& entry = this->entries.at(name); - return StringReader(this->data->data() + entry.offset, entry.size); + return phosg::StringReader(this->data->data() + entry.offset, entry.size); } catch (const out_of_range&) { throw out_of_range("GSL does not contain file: " + name); } @@ -84,16 +83,16 @@ string GSLArchive::generate(const unordered_map& files, bool big return big_endian ? GSLArchive::generate_t(files) : GSLArchive::generate_t(files); } -template +template string GSLArchive::generate_t(const unordered_map& files) { - StringWriter w; + phosg::StringWriter w; // Make sure there's enough space for a blank header entry before any file's // data pages begin - uint32_t data_start_offset = ((sizeof(GSLHeaderEntryT) * (files.size() + 1)) + 0x7FF) & (~0x7FF); + uint32_t data_start_offset = ((sizeof(GSLHeaderEntryT) * (files.size() + 1)) + 0x7FF) & (~0x7FF); uint32_t data_offset = data_start_offset; for (const auto& file : files) { - GSLHeaderEntryT entry; + GSLHeaderEntryT entry; entry.filename.encode(file.first); entry.offset = data_offset >> 11; entry.size = file.second.size(); diff --git a/src/GSLArchive.hh b/src/GSLArchive.hh index 827ade33..22c7da52 100644 --- a/src/GSLArchive.hh +++ b/src/GSLArchive.hh @@ -21,14 +21,14 @@ public: std::pair get(const std::string& name) const; std::string get_copy(const std::string& name) const; - StringReader get_reader(const std::string& name) const; + phosg::StringReader get_reader(const std::string& name) const; static std::string generate(const std::unordered_map& files, bool big_endian); private: - template + template void load_t(); - template + template static std::string generate_t(const std::unordered_map& files); std::shared_ptr data; diff --git a/src/GVMEncoder.cc b/src/GVMEncoder.cc index 7cd4339c..47202b5b 100644 --- a/src/GVMEncoder.cc +++ b/src/GVMEncoder.cc @@ -34,7 +34,7 @@ struct GVRHeader { be_uint16_t height; } __packed_ws__(GVRHeader, 0x10); -string encode_gvm(const Image& img, GVRDataFormat data_format, const std::string& internal_name, uint32_t global_index) { +string encode_gvm(const phosg::Image& img, GVRDataFormat data_format, const std::string& internal_name, uint32_t global_index) { int8_t dimensions_field = -2; { size_t h = img.get_height(); @@ -66,7 +66,7 @@ string encode_gvm(const Image& img, GVRDataFormat data_format, const std::string throw invalid_argument("cannot encode pixel format"); } - StringWriter w; + phosg::StringWriter w; w.put({.signature = 0x47564D48, .header_size = 0x48, .flags = 0x000F, .num_files = 1}); GVMFileEntry file_entry; file_entry.file_num = 0; diff --git a/src/GVMEncoder.hh b/src/GVMEncoder.hh index 8137c106..5a0c533f 100644 --- a/src/GVMEncoder.hh +++ b/src/GVMEncoder.hh @@ -19,7 +19,7 @@ enum class GVRDataFormat : uint8_t { DXT1 = 0x0E, }; -std::string encode_gvm(const Image& img, GVRDataFormat data_format, const std::string& internal_name, uint32_t global_index); +std::string encode_gvm(const phosg::Image& img, GVRDataFormat data_format, const std::string& internal_name, uint32_t global_index); constexpr uint16_t encode_rgb565(uint8_t r, uint8_t g, uint8_t b) { return ((r << 8) & 0xF800) | ((g << 3) & 0x07E0) | ((b >> 3) & 0x001F); diff --git a/src/HTTPServer.cc b/src/HTTPServer.cc index dfe9ad1a..59b9f87e 100644 --- a/src/HTTPServer.cc +++ b/src/HTTPServer.cc @@ -110,7 +110,7 @@ unordered_multimap HTTPServer::parse_url_params(const string& qu if (query.empty()) { return params; } - for (auto it : split(query, '&')) { + for (auto it : phosg::split(query, '&')) { size_t first_equals = it.find('='); if (first_equals != string::npos) { string value(it, first_equals + 1); @@ -119,8 +119,8 @@ unordered_multimap HTTPServer::parse_url_params(const string& qu for (; read_offset < value.size(); write_offset++) { if ((value[read_offset] == '%') && (read_offset < value.size() - 2)) { value[write_offset] = - static_cast(value_for_hex_char(value[read_offset + 1]) << 4) | - static_cast(value_for_hex_char(value[read_offset + 2])); + static_cast(phosg::value_for_hex_char(value[read_offset + 1]) << 4) | + static_cast(phosg::value_for_hex_char(value[read_offset + 2])); read_offset += 3; } else if (value[write_offset] == '+') { value[write_offset] = ' '; @@ -171,7 +171,7 @@ HTTPServer::HTTPServer(shared_ptr state) } void HTTPServer::listen(const string& socket_path) { - int fd = ::listen(socket_path, 0, SOMAXCONN); + int fd = phosg::listen(socket_path, 0, SOMAXCONN); server_log.info("Listening on Unix socket %s on fd %d (HTTP)", socket_path.c_str(), fd); this->add_socket(fd); } @@ -180,8 +180,8 @@ void HTTPServer::listen(const string& addr, int port) { if (port == 0) { this->listen(addr); } else { - int fd = ::listen(addr, port, SOMAXCONN); - string netloc_str = render_netloc(addr, port); + int fd = phosg::listen(addr, port, SOMAXCONN); + string netloc_str = phosg::render_netloc(addr, port); server_log.info("Listening on TCP interface %s on fd %d (HTTP)", netloc_str.c_str(), fd); this->add_socket(fd); } @@ -207,7 +207,7 @@ HTTPServer::WebsocketClient::WebsocketClient(struct evhttp_connection* conn) : conn(conn), bev(evhttp_connection_get_bufferevent(this->conn)), pending_opcode(0xFF), - last_communication_time(now()) {} + last_communication_time(phosg::now()) {} HTTPServer::WebsocketClient::~WebsocketClient() { evhttp_connection_free(this->conn); @@ -241,7 +241,7 @@ shared_ptr HTTPServer::enable_websockets(struct evh // we're about to free the original string sec_websocket_key = sec_websocket_key_header; string sec_websocket_accept_data = sec_websocket_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - string sec_websocket_accept = base64_encode(sha1(sec_websocket_accept_data)); + string sec_websocket_accept = phosg::base64_encode(phosg::sha1(sec_websocket_accept_data)); // Hijack the bufferevent since it's no longer handling HTTP at all struct evhttp_connection* conn = evhttp_request_get_connection(req); @@ -290,13 +290,13 @@ void HTTPServer::on_websocket_read(struct bufferevent* bev) { if (bytes_read < 10) { break; // Full 64-bit header not yet available } - payload_size = bswap64(*reinterpret_cast(&header_data[2])); + payload_size = phosg::bswap64(*reinterpret_cast(&header_data[2])); header_size = 10; } else if (payload_size == 0x7E) { if (bytes_read < 4) { break; // Full 16-bit size header not yet available } - payload_size = bswap16(*reinterpret_cast(&header_data[2])); + payload_size = phosg::bswap16(*reinterpret_cast(&header_data[2])); header_size = 4; } if (evbuffer_get_length(in_buf) < header_size + payload_size) { @@ -312,7 +312,7 @@ void HTTPServer::on_websocket_read(struct bufferevent* bev) { } shared_ptr c = this->bev_to_websocket_client.at(bev); - c->last_communication_time = now(); + c->last_communication_time = phosg::now(); // Read and unmask message data string payload(payload_size, '\0'); @@ -392,11 +392,11 @@ void HTTPServer::send_websocket_message(struct bufferevent* bev, if (message.size() > 65535) { header.push_back(0x7F); header.resize(10); - *reinterpret_cast(const_cast(header.data() + 2)) = bswap64(message.size()); + *reinterpret_cast(const_cast(header.data() + 2)) = phosg::bswap64(message.size()); } else if (message.size() > 0x7D) { header.push_back(0x7E); header.resize(4); - *reinterpret_cast(const_cast(header.data() + 2)) = bswap16(message.size()); + *reinterpret_cast(const_cast(header.data() + 2)) = phosg::bswap16(message.size()); } else { header.push_back(message.size()); } @@ -418,7 +418,7 @@ void HTTPServer::handle_websocket_disconnect(shared_ptr c) { this->rare_drop_subscribers.erase(c); } -void HTTPServer::send_rare_drop_notification(shared_ptr message) { +void HTTPServer::send_rare_drop_notification(shared_ptr message) { forward_to_event_thread(this->base, [this, message]() -> void { if (this->rare_drop_subscribers.empty()) { return; @@ -434,26 +434,26 @@ void HTTPServer::dispatch_handle_request(struct evhttp_request* req, void* ctx) reinterpret_cast(ctx)->handle_request(req); } -JSON HTTPServer::generate_quest_json_st(shared_ptr q) { +phosg::JSON HTTPServer::generate_quest_json_st(shared_ptr q) { if (!q) { return nullptr; } auto battle_rules_json = q->battle_rules ? q->battle_rules->json() : nullptr; auto challenge_template_index_json = (q->challenge_template_index >= 0) ? q->challenge_template_index - : JSON(nullptr); - return JSON::dict({ + : phosg::JSON(nullptr); + return phosg::JSON::dict({ {"Number", q->quest_number}, {"Episode", name_for_episode(q->episode)}, {"Joinable", q->joinable}, - {"LockStatusRegister", (q->lock_status_register >= 0) ? q->lock_status_register : JSON(nullptr)}, + {"LockStatusRegister", (q->lock_status_register >= 0) ? q->lock_status_register : phosg::JSON(nullptr)}, {"Name", q->name}, {"BattleRules", std::move(battle_rules_json)}, {"ChallengeTemplateIndex", std::move(challenge_template_index_json)}, }); } -JSON HTTPServer::generate_client_config_json_st(const Client::Config& config) { +phosg::JSON HTTPServer::generate_client_config_json_st(const Client::Config& config) { const char* drop_notifications_mode = "unknown"; switch (config.get_drop_notification_mode()) { case Client::ItemDropNotificationMode::NOTHING: @@ -470,7 +470,7 @@ JSON HTTPServer::generate_client_config_json_st(const Client::Config& config) { break; } - auto ret = JSON::dict({ + auto ret = phosg::JSON::dict({ {"SpecificVersion", config.specific_version}, {"SwitchAssistEnabled", (config.check_flag(Client::Flag::SWITCH_ASSIST_ENABLED) ? true : false)}, {"InfiniteHPEnabled", (config.check_flag(Client::Flag::INFINITE_HP_ENABLED) ? true : false)}, @@ -486,46 +486,46 @@ JSON HTTPServer::generate_client_config_json_st(const Client::Config& config) { {"ProxyBlockFunctionCalls", (config.check_flag(Client::Flag::PROXY_BLOCK_FUNCTION_CALLS) ? true : false)}, {"ProxyEp3UnmaskWhispers", (config.check_flag(Client::Flag::PROXY_EP3_UNMASK_WHISPERS) ? true : false)}, }); - ret.emplace("OverrideRandomSeed", config.check_flag(Client::Flag::USE_OVERRIDE_RANDOM_SEED) ? config.override_random_seed : JSON(nullptr)); - ret.emplace("OverrideSectionID", (config.override_section_id != 0xFF) ? config.override_section_id : JSON(nullptr)); - ret.emplace("OverrideLobbyEvent", (config.override_lobby_event != 0xFF) ? config.override_lobby_event : JSON(nullptr)); - ret.emplace("OverrideLobbyNumber", (config.override_lobby_number != 0x80) ? config.override_lobby_number : JSON(nullptr)); + ret.emplace("OverrideRandomSeed", config.check_flag(Client::Flag::USE_OVERRIDE_RANDOM_SEED) ? config.override_random_seed : phosg::JSON(nullptr)); + ret.emplace("OverrideSectionID", (config.override_section_id != 0xFF) ? config.override_section_id : phosg::JSON(nullptr)); + ret.emplace("OverrideLobbyEvent", (config.override_lobby_event != 0xFF) ? config.override_lobby_event : phosg::JSON(nullptr)); + ret.emplace("OverrideLobbyNumber", (config.override_lobby_number != 0x80) ? config.override_lobby_number : phosg::JSON(nullptr)); return ret; } -JSON HTTPServer::generate_account_json_st(shared_ptr a) { - auto dc_nte_licenses_json = JSON::list(); +phosg::JSON HTTPServer::generate_account_json_st(shared_ptr a) { + auto dc_nte_licenses_json = phosg::JSON::list(); for (const auto& it : a->dc_nte_licenses) { dc_nte_licenses_json.emplace_back(it.first); } - auto dc_licenses_json = JSON::list(); + auto dc_licenses_json = phosg::JSON::list(); for (const auto& it : a->dc_licenses) { dc_licenses_json.emplace_back(it.first); } - auto pc_licenses_json = JSON::list(); + auto pc_licenses_json = phosg::JSON::list(); for (const auto& it : a->pc_licenses) { pc_licenses_json.emplace_back(it.first); } - auto gc_licenses_json = JSON::list(); + auto gc_licenses_json = phosg::JSON::list(); for (const auto& it : a->gc_licenses) { gc_licenses_json.emplace_back(it.first); } - auto xb_licenses_json = JSON::list(); + auto xb_licenses_json = phosg::JSON::list(); for (const auto& it : a->xb_licenses) { xb_licenses_json.emplace_back(it.first); } - auto bb_licenses_json = JSON::list(); + auto bb_licenses_json = phosg::JSON::list(); for (const auto& it : a->bb_licenses) { bb_licenses_json.emplace_back(it.first); } - auto auto_patches_json = JSON::list(); + auto auto_patches_json = phosg::JSON::list(); for (const auto& it : a->auto_patches_enabled) { auto_patches_json.emplace_back(it); } - return JSON::dict({ + return phosg::JSON::dict({ {"AccountID", a->account_id}, {"Flags", a->flags}, - {"BanEndTime", a->ban_end_time ? a->ban_end_time : JSON(nullptr)}, + {"BanEndTime", a->ban_end_time ? a->ban_end_time : phosg::JSON(nullptr)}, {"Ep3CurrentMeseta", a->ep3_current_meseta}, {"Ep3TotalMesetaEarned", a->ep3_total_meseta_earned}, {"BBTeamID", a->bb_team_id}, @@ -542,11 +542,11 @@ JSON HTTPServer::generate_account_json_st(shared_ptr a) { }); }; -JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared_ptr item_name_index) { - auto ret = JSON::dict({ +phosg::JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared_ptr item_name_index) { + auto ret = phosg::JSON::dict({ {"ID", c->id}, - {"RemoteAddress", render_sockaddr_storage(c->channel.remote_addr)}, - {"Version", name_for_enum(c->version())}, + {"RemoteAddress", phosg::render_sockaddr_storage(c->channel.remote_addr)}, + {"Version", phosg::name_for_enum(c->version())}, {"SubVersion", c->sub_version}, {"Config", HTTPServer::generate_client_config_json_st(c->config)}, {"Language", name_for_language_code(c->language())}, @@ -555,7 +555,7 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared {"LocationFloor", c->floor}, {"CanChat", c->can_chat}, }); - ret.emplace("Account", c->login ? HTTPServer::generate_account_json_st(c->login->account) : JSON(nullptr)); + ret.emplace("Account", c->login ? HTTPServer::generate_account_json_st(c->login->account) : phosg::JSON(nullptr)); auto l = c->lobby.lock(); if (l) { ret.emplace("LobbyID", l->lobby_id); @@ -580,10 +580,10 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared ret.emplace("NumLuckMaterialsUsed", p->get_material_usage(PSOBBCharacterFile::MaterialType::LUCK)); } } - JSON items_json = JSON::list(); + phosg::JSON items_json = phosg::JSON::list(); for (size_t z = 0; z < p->inventory.num_items; z++) { const auto& item = p->inventory.items[z]; - auto item_dict = JSON::dict({ + auto item_dict = phosg::JSON::dict({ {"Flags", item.flags.load()}, {"Data", item.data.hex()}, {"ItemID", item.data.id.load()}, @@ -602,17 +602,17 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared ret.emplace("LCK", p->disp.stats.char_stats.lck.load()); ret.emplace("EXP", p->disp.stats.experience.load()); ret.emplace("Meseta", p->disp.stats.meseta.load()); - auto tech_levels_json = JSON::dict(); + auto tech_levels_json = phosg::JSON::dict(); for (size_t z = 0; z < 0x13; z++) { auto level = p->get_technique_level(z); - tech_levels_json.emplace(name_for_technique(z), (level != 0xFF) ? level : JSON(nullptr)); + tech_levels_json.emplace(name_for_technique(z), (level != 0xFF) ? level : phosg::JSON(nullptr)); } ret.emplace("TechniqueLevels", std::move(tech_levels_json)); } ret.emplace("Height", p->disp.stats.height.load()); ret.emplace("Level", p->disp.stats.level.load()); ret.emplace("NameColor", p->disp.visual.name_color.load()); - ret.emplace("ExtraModel", (p->disp.visual.validation_flags & 2) ? p->disp.visual.extra_model : JSON(nullptr)); + ret.emplace("ExtraModel", (p->disp.visual.validation_flags & 2) ? p->disp.visual.extra_model : phosg::JSON(nullptr)); ret.emplace("SectionID", name_for_section_id(p->disp.visual.section_id)); ret.emplace("CharClass", name_for_char_class(p->disp.visual.section_id)); ret.emplace("Costume", p->disp.visual.costume.load()); @@ -631,7 +631,7 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared ret.emplace("AutoReply", p->auto_reply.decode(c->language())); ret.emplace("InfoBoard", p->info_board.decode(c->language())); - auto battle_place_counts = JSON::list({ + auto battle_place_counts = phosg::JSON::list({ p->battle_records.place_counts[0].load(), p->battle_records.place_counts[1].load(), p->battle_records.place_counts[2].load(), @@ -641,8 +641,8 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared ret.emplace("BattleDisconnectCount", p->battle_records.disconnect_count.load()); if (!is_ep3(c->version())) { - auto json_for_challenge_times = [](const parray& times) -> JSON { - auto times_json = JSON::list(); + auto json_for_challenge_times = [](const parray& times) -> phosg::JSON { + auto times_json = phosg::JSON::list(); for (size_t z = 0; z < times.size(); z++) { times_json.emplace_back(times[z].decode()); } @@ -662,7 +662,7 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared uint8_t day = (p->challenge_records.grave_time >> 16) & 0xFF; uint8_t hour = (p->challenge_records.grave_time >> 8) & 0xFF; uint8_t minute = p->challenge_records.grave_time & 0xFF; - ret.emplace("ChallengeGraveTime", string_printf("%04hu-%02hhu-%02hhu %02hhu:%02hhu:00", year, month, day, hour, minute)); + ret.emplace("ChallengeGraveTime", phosg::string_printf("%04hu-%02hhu-%02hhu %02hhu:%02hhu:00", year, month, day, hour, minute)); } string grave_enemy_types; if (p->challenge_records.grave_defeated_by_enemy_rt_index) { @@ -670,7 +670,7 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared if (!grave_enemy_types.empty()) { grave_enemy_types += "/"; } - grave_enemy_types += name_for_enum(type); + grave_enemy_types += phosg::name_for_enum(type); } } ret.emplace("ChallengeGraveDefeatedByEnemy", std::move(grave_enemy_types)); @@ -691,7 +691,7 @@ JSON HTTPServer::generate_game_client_json_st(shared_ptr c, shared return ret; } -JSON HTTPServer::generate_proxy_client_json_st(shared_ptr ses) { +phosg::JSON HTTPServer::generate_proxy_client_json_st(shared_ptr ses) { struct LobbyPlayer { uint32_t guild_card_number = 0; uint64_t xb_user_id = 0; @@ -702,35 +702,35 @@ JSON HTTPServer::generate_proxy_client_json_st(shared_ptr lobby_players; - auto lobby_players_json = JSON::list(); + auto lobby_players_json = phosg::JSON::list(); for (size_t z = 0; z < ses->lobby_players.size(); z++) { const auto& p = ses->lobby_players[z]; if (p.guild_card_number) { - lobby_players_json.emplace_back(JSON::dict({ + lobby_players_json.emplace_back(phosg::JSON::dict({ {"GuildCardNumber", p.guild_card_number}, {"Name", p.name}, {"Language", name_for_language_code(p.language)}, {"SectionID", name_for_section_id(p.section_id)}, {"CharClass", name_for_char_class(p.char_class)}, })); - lobby_players_json.back().emplace("XBUserID", p.xb_user_id ? p.xb_user_id : JSON(nullptr)); + lobby_players_json.back().emplace("XBUserID", p.xb_user_id ? p.xb_user_id : phosg::JSON(nullptr)); } else { lobby_players_json.emplace_back(nullptr); } } - auto ret = JSON::dict({ + auto ret = phosg::JSON::dict({ {"ID", ses->id}, - {"RemoteClientAddress", render_sockaddr_storage(ses->client_channel.remote_addr)}, - {"RemoteServerAddress", render_sockaddr_storage(ses->server_channel.remote_addr)}, + {"RemoteClientAddress", phosg::render_sockaddr_storage(ses->client_channel.remote_addr)}, + {"RemoteServerAddress", phosg::render_sockaddr_storage(ses->server_channel.remote_addr)}, {"LocalPort", ses->local_port}, - {"NextDestination", render_sockaddr_storage(ses->next_destination)}, - {"Version", name_for_enum(ses->version())}, + {"NextDestination", phosg::render_sockaddr_storage(ses->next_destination)}, + {"Version", phosg::name_for_enum(ses->version())}, {"SubVersion", ses->sub_version}, {"Name", ses->character_name}, {"DCHardwareID", ses->hardware_id}, {"RemoteGuildCardNumber", ses->remote_guild_card_number}, - {"RemoteClientConfigData", format_data_string(&ses->remote_client_config_data[0], ses->remote_client_config_data.size())}, + {"RemoteClientConfigData", phosg::format_data_string(&ses->remote_client_config_data[0], ses->remote_client_config_data.size())}, {"Config", HTTPServer::generate_client_config_json_st(ses->config)}, {"Language", name_for_language_code(ses->language())}, {"LobbyClientID", ses->lobby_client_id}, @@ -759,19 +759,19 @@ JSON HTTPServer::generate_proxy_client_json_st(shared_ptrlogin ? HTTPServer::generate_account_json_st(ses->login->account) : JSON(nullptr)); + ret.emplace("Account", ses->login ? HTTPServer::generate_account_json_st(ses->login->account) : phosg::JSON(nullptr)); return ret; } -JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptr item_name_index) { +phosg::JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptr item_name_index) { std::array, 12> clients; - auto client_ids_json = JSON::list(); + auto client_ids_json = phosg::JSON::list(); for (size_t z = 0; z < l->max_clients; z++) { - client_ids_json.emplace_back(l->clients[z] ? l->clients[z]->id : JSON(nullptr)); + client_ids_json.emplace_back(l->clients[z] ? l->clients[z]->id : phosg::JSON(nullptr)); } - auto ret = JSON::dict({ + auto ret = phosg::JSON::dict({ {"ID", l->lobby_id}, {"AllowedVersions", l->allowed_versions}, {"Event", l->event}, @@ -796,7 +796,7 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrcheck_flag(Lobby::Flag::QUEST_SELECTION_IN_PROGRESS)); ret.emplace("QuestInProgress", l->check_flag(Lobby::Flag::QUEST_IN_PROGRESS)); ret.emplace("JoinableQuestInProgress", l->check_flag(Lobby::Flag::JOINABLE_QUEST_IN_PROGRESS)); - auto variations_json = JSON::list(); + auto variations_json = phosg::JSON::list(); for (size_t z = 0; z < l->variations.size(); z++) { variations_json.emplace_back(l->variations[z].load()); } @@ -839,11 +839,11 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrfloor_item_managers.size(); floor++) { for (const auto& it : l->floor_item_managers[floor].items) { const auto& item = it.second; - auto item_dict = JSON::dict({ + auto item_dict = phosg::JSON::dict({ {"LocationFloor", floor}, {"LocationX", item->x}, {"LocationZ", item->z}, @@ -868,7 +868,7 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrep3_server; if (ep3s) { - auto players_json = JSON::list(); + auto players_json = phosg::JSON::list(); for (size_t z = 0; z < 4; z++) { if (!ep3s->name_entries[z].present) { players_json.emplace_back(nullptr); @@ -876,9 +876,9 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrclients[z]; auto deck_entry = ep3s->deck_entries[z]; - JSON deck_json = nullptr; + phosg::JSON deck_json = nullptr; if (deck_entry) { - auto cards_json = JSON::list(); + auto cards_json = phosg::JSON::list(); for (size_t w = 0; w < deck_entry->card_ids.size(); w++) { try { const auto& ce = ep3s->options.card_index->definition_for_id(deck_entry->card_ids[w]); @@ -897,7 +897,7 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrcard_ids[w].load()); } } - deck_json = JSON::dict({ + deck_json = phosg::JSON::dict({ {"Name", deck_entry->name.decode(lc ? lc->language() : 1)}, {"TeamID", deck_entry->team_id.load()}, {"Cards", std::move(cards_json)}, @@ -906,7 +906,7 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrname_entries[z].name.decode(lc ? lc->language() : 1)}, {"ClientID", ep3s->name_entries[z].client_id}, {"IsCOM", !!ep3s->name_entries[z].is_cpu_player}, @@ -915,13 +915,13 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptroptions.behavior_flags}, - {"RandomSeed", ep3s->options.opt_rand_crypt ? ep3s->options.opt_rand_crypt->seed() : JSON(nullptr)}, - {"RandomOffset", ep3s->options.opt_rand_crypt ? ep3s->options.opt_rand_crypt->absolute_offset() : JSON(nullptr)}, + {"RandomSeed", ep3s->options.opt_rand_crypt ? ep3s->options.opt_rand_crypt->seed() : phosg::JSON(nullptr)}, + {"RandomOffset", ep3s->options.opt_rand_crypt ? ep3s->options.opt_rand_crypt->absolute_offset() : phosg::JSON(nullptr)}, {"Tournament", ep3s->options.tournament ? ep3s->options.tournament->json() : nullptr}, - {"MapNumber", ep3s->last_chosen_map ? ep3s->last_chosen_map->map_number : JSON(nullptr)}, - {"EnvironmentNumber", ep3s->map_and_rules ? ep3s->map_and_rules->environment_number : JSON(nullptr)}, + {"MapNumber", ep3s->last_chosen_map ? ep3s->last_chosen_map->map_number : phosg::JSON(nullptr)}, + {"EnvironmentNumber", ep3s->map_and_rules ? ep3s->map_and_rules->environment_number : phosg::JSON(nullptr)}, {"Rules", ep3s->map_and_rules ? ep3s->map_and_rules->rules.json() : nullptr}, {"Players", std::move(players_json)}, {"IsBattleFinished", ep3s->battle_finished}, @@ -929,13 +929,13 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrround_num}, {"FirstTeamTurn", ep3s->first_team_turn}, {"CurrentTeamTurn", ep3s->current_team_turn1}, - {"BattlePhase", name_for_enum(ep3s->battle_phase)}, + {"BattlePhase", phosg::name_for_enum(ep3s->battle_phase)}, {"SetupPhase", ep3s->setup_phase}, {"RegistrationPhase", ep3s->registration_phase}, {"ActionSubphase", ep3s->action_subphase}, {"BattleStartTimeUsecs", ep3s->battle_start_usecs}, - {"TeamEXP", JSON::list({ep3s->team_exp[0], ep3s->team_exp[1]})}, - {"TeamDiceBonus", JSON::list({ep3s->team_dice_bonus[0], ep3s->team_dice_bonus[1]})}, + {"TeamEXP", phosg::JSON::list({ep3s->team_exp[0], ep3s->team_exp[1]})}, + {"TeamDiceBonus", phosg::JSON::list({ep3s->team_dice_bonus[0], ep3s->team_dice_bonus[1]})}, }); // std::shared_ptr state_flags; // std::array, 4> player_states; @@ -947,7 +947,7 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptrlobby_id); } - auto watcher_lobby_ids_json = JSON::list(); + auto watcher_lobby_ids_json = phosg::JSON::list(); for (const auto& watcher_lobby : l->watcher_lobbies) { watcher_lobby_ids_json.emplace_back(watcher_lobby->lobby_id); } @@ -964,9 +964,9 @@ JSON HTTPServer::generate_lobby_json_st(shared_ptr l, shared_ptr(this->state->base, [&]() { - auto res = JSON::list(); +phosg::JSON HTTPServer::generate_game_server_clients_json() const { + return call_on_event_thread(this->state->base, [&]() { + auto res = phosg::JSON::list(); for (const auto& it : this->state->channel_to_client) { res.emplace_back(this->generate_game_client_json_st(it.second, this->state->item_name_index_opt(it.second->version()))); } @@ -974,9 +974,9 @@ JSON HTTPServer::generate_game_server_clients_json() const { }); } -JSON HTTPServer::generate_proxy_server_clients_json() const { - return call_on_event_thread(this->state->base, [&]() { - JSON res = JSON::list(); +phosg::JSON HTTPServer::generate_proxy_server_clients_json() const { + return call_on_event_thread(this->state->base, [&]() { + phosg::JSON res = phosg::JSON::list(); if (this->state->proxy_server) { for (const auto& it : this->state->proxy_server->all_sessions()) { res.emplace_back(this->generate_proxy_client_json_st(it.second)); @@ -986,8 +986,8 @@ JSON HTTPServer::generate_proxy_server_clients_json() const { }); } -JSON HTTPServer::generate_server_info_json() const { - return call_on_event_thread(this->state->base, [&]() { +phosg::JSON HTTPServer::generate_server_info_json() const { + return call_on_event_thread(this->state->base, [&]() { size_t game_count = 0; size_t lobby_count = 0; for (const auto& it : this->state->id_to_lobby) { @@ -997,12 +997,12 @@ JSON HTTPServer::generate_server_info_json() const { lobby_count++; } } - uint64_t uptime_usecs = now() - this->state->creation_time; - return JSON::dict({ + uint64_t uptime_usecs = phosg::now() - this->state->creation_time; + return phosg::JSON::dict({ {"StartTimeUsecs", this->state->creation_time}, - {"StartTime", format_time(this->state->creation_time)}, + {"StartTime", phosg::format_time(this->state->creation_time)}, {"UptimeUsecs", uptime_usecs}, - {"Uptime", format_duration(uptime_usecs)}, + {"Uptime", phosg::format_duration(uptime_usecs)}, {"LobbyCount", lobby_count}, {"GameCount", game_count}, {"ClientCount", this->state->channel_to_client.size()}, @@ -1012,9 +1012,9 @@ JSON HTTPServer::generate_server_info_json() const { }); } -JSON HTTPServer::generate_lobbies_json() const { - return call_on_event_thread(this->state->base, [&]() { - JSON res = JSON::list(); +phosg::JSON HTTPServer::generate_lobbies_json() const { + return call_on_event_thread(this->state->base, [&]() { + phosg::JSON res = phosg::JSON::list(); for (const auto& it : this->state->id_to_lobby) { res.emplace_back(this->generate_lobby_json_st(it.second, this->state->item_name_index_opt(it.second->base_version))); } @@ -1022,46 +1022,46 @@ JSON HTTPServer::generate_lobbies_json() const { }); } -JSON HTTPServer::generate_summary_json() const { - auto ret = call_on_event_thread(this->state->base, [&]() { - auto clients_json = JSON::list(); +phosg::JSON HTTPServer::generate_summary_json() const { + auto ret = call_on_event_thread(this->state->base, [&]() { + auto clients_json = phosg::JSON::list(); for (const auto& it : this->state->channel_to_client) { auto c = it.second; auto p = c->character(false, false); auto l = c->lobby.lock(); - clients_json.emplace_back(JSON::dict({ + clients_json.emplace_back(phosg::JSON::dict({ {"ID", c->id}, - {"AccountID", c->login ? c->login->account->account_id : JSON(nullptr)}, - {"Name", p ? p->disp.name.decode(it.second->language()) : JSON(nullptr)}, - {"Version", name_for_enum(it.second->version())}, + {"AccountID", c->login ? c->login->account->account_id : phosg::JSON(nullptr)}, + {"Name", p ? p->disp.name.decode(it.second->language()) : phosg::JSON(nullptr)}, + {"Version", phosg::name_for_enum(it.second->version())}, {"Language", name_for_language_code(it.second->language())}, - {"Level", p ? p->disp.stats.level + 1 : JSON(nullptr)}, - {"Class", p ? name_for_char_class(p->disp.visual.char_class) : JSON(nullptr)}, - {"SectionID", p ? name_for_section_id(p->disp.visual.section_id) : JSON(nullptr)}, - {"LobbyID", l ? l->lobby_id : JSON(nullptr)}, + {"Level", p ? p->disp.stats.level + 1 : phosg::JSON(nullptr)}, + {"Class", p ? name_for_char_class(p->disp.visual.char_class) : phosg::JSON(nullptr)}, + {"SectionID", p ? name_for_section_id(p->disp.visual.section_id) : phosg::JSON(nullptr)}, + {"LobbyID", l ? l->lobby_id : phosg::JSON(nullptr)}, })); } - auto proxy_clients_json = JSON::list(); + auto proxy_clients_json = phosg::JSON::list(); if (this->state->proxy_server) { for (const auto& it : this->state->proxy_server->all_sessions()) { - proxy_clients_json.emplace_back(JSON::dict({ - {"AccountID", it.second->login ? it.second->login->account->account_id : JSON(nullptr)}, + proxy_clients_json.emplace_back(phosg::JSON::dict({ + {"AccountID", it.second->login ? it.second->login->account->account_id : phosg::JSON(nullptr)}, {"Name", it.second->character_name}, - {"Version", name_for_enum(it.second->version())}, + {"Version", phosg::name_for_enum(it.second->version())}, {"Language", name_for_language_code(it.second->language())}, })); } } - auto games_json = JSON::list(); + auto games_json = phosg::JSON::list(); for (const auto& it : this->state->id_to_lobby) { auto l = it.second; if (l->is_game()) { - auto game_json = JSON::dict({ + auto game_json = phosg::JSON::dict({ {"ID", l->lobby_id}, {"Name", l->name}, - {"BaseVersion", name_for_enum(l->base_version)}, + {"BaseVersion", phosg::name_for_enum(l->base_version)}, {"Players", l->count_clients()}, {"CheatsEnabled", l->check_flag(Lobby::Flag::CHEATS_ENABLED)}, {"Episode", name_for_episode(l->episode)}, @@ -1071,7 +1071,7 @@ JSON HTTPServer::generate_summary_json() const { auto ep3s = l->ep3_server; game_json.emplace("BattleInProgress", l->check_flag(Lobby::Flag::BATTLE_IN_PROGRESS)); game_json.emplace("IsSpectatorTeam", l->check_flag(Lobby::Flag::IS_SPECTATOR_TEAM)); - game_json.emplace("MapNumber", (ep3s && ep3s->last_chosen_map) ? ep3s->last_chosen_map->map_number : JSON(nullptr)); + game_json.emplace("MapNumber", (ep3s && ep3s->last_chosen_map) ? ep3s->last_chosen_map->map_number : phosg::JSON(nullptr)); game_json.emplace("Rules", (ep3s && ep3s->map_and_rules) ? ep3s->map_and_rules->rules.json() : nullptr); } else { game_json.emplace("QuestSelectionInProgress", l->check_flag(Lobby::Flag::QUEST_SELECTION_IN_PROGRESS)); @@ -1086,7 +1086,7 @@ JSON HTTPServer::generate_summary_json() const { } } - return JSON::dict({ + return phosg::JSON::dict({ {"Clients", std::move(clients_json)}, {"ProxyClients", std::move(proxy_clients_json)}, {"Games", std::move(games_json)}, @@ -1096,8 +1096,8 @@ JSON HTTPServer::generate_summary_json() const { return ret; } -JSON HTTPServer::generate_all_json() const { - return JSON::dict({ +phosg::JSON HTTPServer::generate_all_json() const { + return phosg::JSON::dict({ {"Clients", this->generate_game_server_clients_json()}, {"ProxyClients", this->generate_proxy_server_clients_json()}, {"Lobbies", this->generate_lobbies_json()}, @@ -1105,43 +1105,43 @@ JSON HTTPServer::generate_all_json() const { }); } -JSON HTTPServer::generate_ep3_cards_json(bool trial) const { +phosg::JSON HTTPServer::generate_ep3_cards_json(bool trial) const { auto index = call_on_event_thread>(this->state->base, [&]() { return trial ? this->state->ep3_card_index_trial : this->state->ep3_card_index; }); return index->definitions_json(); } -JSON HTTPServer::generate_common_tables_json() const { +phosg::JSON HTTPServer::generate_common_tables_json() const { auto [set_v2, set_v3_v4] = call_on_event_thread, shared_ptr>>(this->state->base, [&]() { return make_pair(this->state->common_item_set_v2, this->state->common_item_set_v3_v4); }); - return JSON::dict({{"v1_v2", set_v2->json()}, {"v3_v4", set_v3_v4->json()}}); + return phosg::JSON::dict({{"v1_v2", set_v2->json()}, {"v3_v4", set_v3_v4->json()}}); } -JSON HTTPServer::generate_rare_tables_json() const { +phosg::JSON HTTPServer::generate_rare_tables_json() const { auto sets = call_on_event_thread>>(this->state->base, [&]() { return this->state->rare_item_sets; }); - JSON ret = JSON::list(); + phosg::JSON ret = phosg::JSON::list(); for (const auto& it : sets) { ret.emplace_back(it.first); } return ret; } -JSON HTTPServer::generate_rare_table_json(const std::string& table_name) const { +phosg::JSON HTTPServer::generate_rare_table_json(const std::string& table_name) const { try { auto colls = call_on_event_thread, shared_ptr>>(this->state->base, [&]() { const auto& table = this->state->rare_item_sets.at(table_name); shared_ptr name_index; - if (ends_with(table_name, "-v1")) { + if (phosg::ends_with(table_name, "-v1")) { name_index = this->state->item_name_index_opt(Version::DC_V1); - } else if (ends_with(table_name, "-v2")) { + } else if (phosg::ends_with(table_name, "-v2")) { name_index = this->state->item_name_index_opt(Version::PC_V2); - } else if (ends_with(table_name, "-v3")) { + } else if (phosg::ends_with(table_name, "-v3")) { name_index = this->state->item_name_index_opt(Version::GC_V3); - } else if (ends_with(table_name, "-v4")) { + } else if (phosg::ends_with(table_name, "-v4")) { name_index = this->state->item_name_index_opt(Version::BB_V4); } return make_pair(table, name_index); @@ -1153,9 +1153,9 @@ JSON HTTPServer::generate_rare_table_json(const std::string& table_name) const { } void HTTPServer::handle_request(struct evhttp_request* req) { - shared_ptr ret; + shared_ptr ret; uint32_t serialize_options = 0; - uint64_t start_time = now(); + uint64_t start_time = phosg::now(); string uri = evhttp_request_get_uri(req); try { @@ -1168,14 +1168,14 @@ void HTTPServer::handle_request(struct evhttp_request* req) { static const string default_format_option = "false"; if (this->get_url_param(query, "format", &default_format_option) == "true") { - serialize_options |= JSON::SerializeOption::FORMAT | JSON::SerializeOption::SORT_DICT_KEYS; + serialize_options |= phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::SORT_DICT_KEYS; } if (this->get_url_param(query, "hex", &default_format_option) == "true") { - serialize_options |= JSON::SerializeOption::HEX_INTEGERS; + serialize_options |= phosg::JSON::SerializeOption::HEX_INTEGERS; } if (uri == "/") { - auto endpoints_json = JSON::list({ + auto endpoints_json = phosg::JSON::list({ "/y/data/ep3-cards", "/y/data/ep3-cards-trial", "/y/data/common-tables", @@ -1190,7 +1190,7 @@ void HTTPServer::handle_request(struct evhttp_request* req) { "/y/summary", "/y/all", }); - ret = make_shared(JSON::dict({{"endpoints", std::move(endpoints_json)}})); + ret = make_shared(phosg::JSON::dict({{"endpoints", std::move(endpoints_json)}})); } else if (uri == "/y/rare-drops/stream") { auto c = this->enable_websockets(req); @@ -1198,35 +1198,35 @@ void HTTPServer::handle_request(struct evhttp_request* req) { throw http_error(400, "this path requires a websocket connection"); } else { this->rare_drop_subscribers.emplace(c); - auto version_message = JSON::dict({{"ServerType", "newserv"}}); + auto version_message = phosg::JSON::dict({{"ServerType", "newserv"}}); this->send_websocket_message(c, version_message.serialize()); return; } } else if (uri == "/y/data/ep3-cards") { - ret = make_shared(this->generate_ep3_cards_json(false)); + ret = make_shared(this->generate_ep3_cards_json(false)); } else if (uri == "/y/data/ep3-cards-trial") { - ret = make_shared(this->generate_ep3_cards_json(true)); + ret = make_shared(this->generate_ep3_cards_json(true)); } else if (uri == "/y/data/common-tables") { - ret = make_shared(this->generate_common_tables_json()); + ret = make_shared(this->generate_common_tables_json()); } else if (uri == "/y/data/rare-tables") { - ret = make_shared(this->generate_rare_tables_json()); + ret = make_shared(this->generate_rare_tables_json()); } else if (!strncmp(uri.c_str(), "/y/data/rare-tables/", 20)) { - ret = make_shared(this->generate_rare_table_json(uri.substr(20))); + ret = make_shared(this->generate_rare_table_json(uri.substr(20))); } else if (uri == "/y/data/config") { - ret = call_on_event_thread>(this->state->base, [this]() { return this->state->config_json; }); + ret = call_on_event_thread>(this->state->base, [this]() { return this->state->config_json; }); } else if (uri == "/y/clients") { - ret = make_shared(this->generate_game_server_clients_json()); + ret = make_shared(this->generate_game_server_clients_json()); } else if (uri == "/y/proxy-clients") { - ret = make_shared(this->generate_proxy_server_clients_json()); + ret = make_shared(this->generate_proxy_server_clients_json()); } else if (uri == "/y/lobbies") { - ret = make_shared(this->generate_lobbies_json()); + ret = make_shared(this->generate_lobbies_json()); } else if (uri == "/y/server") { - ret = make_shared(this->generate_server_info_json()); + ret = make_shared(this->generate_server_info_json()); } else if (uri == "/y/summary") { - ret = make_shared(this->generate_summary_json()); + ret = make_shared(this->generate_summary_json()); } else if (uri == "/y/all") { - ret = make_shared(this->generate_all_json()); + ret = make_shared(this->generate_all_json()); } else { throw http_error(404, "unknown action"); @@ -1246,20 +1246,20 @@ void HTTPServer::handle_request(struct evhttp_request* req) { return; } - uint64_t handler_end = now(); + uint64_t handler_end = phosg::now(); unique_ptr out_buffer(evbuffer_new(), evbuffer_free); - string* serialized = new string(ret->serialize(JSON::SerializeOption::ESCAPE_CONTROLS_ONLY | serialize_options)); + string* serialized = new string(ret->serialize(phosg::JSON::SerializeOption::ESCAPE_CONTROLS_ONLY | serialize_options)); size_t size = serialized->size(); - uint64_t serialize_end = now(); + uint64_t serialize_end = phosg::now(); auto cleanup = +[](const void*, size_t, void* s) -> void { delete reinterpret_cast(s); }; evbuffer_add_reference(out_buffer.get(), serialized->data(), serialized->size(), cleanup, serialized); this->send_response(req, 200, "application/json", out_buffer.get()); - string handler_time = format_duration(handler_end - start_time); - string serialize_time = format_duration(serialize_end - handler_end); - string size_str = format_size(size); + string handler_time = phosg::format_duration(handler_end - start_time); + string serialize_time = phosg::format_duration(serialize_end - handler_end); + string size_str = phosg::format_size(size); server_log.info("[HTTPServer] %s in [handler: %s, serialize: %s, size: %s]", uri.c_str(), handler_time.c_str(), serialize_time.c_str(), size_str.c_str()); } diff --git a/src/HTTPServer.hh b/src/HTTPServer.hh index 5e2fa4f3..813554b4 100644 --- a/src/HTTPServer.hh +++ b/src/HTTPServer.hh @@ -28,7 +28,7 @@ public: void schedule_stop(); void wait_for_stop(); - void send_rare_drop_notification(std::shared_ptr message); + void send_rare_drop_notification(std::shared_ptr message); protected: class http_error : public std::runtime_error { @@ -94,21 +94,21 @@ protected: const std::string& key, const std::string* _default = nullptr); - static JSON generate_quest_json_st(std::shared_ptr q); - static JSON generate_client_config_json_st(const Client::Config& config); - static JSON generate_account_json_st(std::shared_ptr a); - static JSON generate_game_client_json_st(std::shared_ptr c, std::shared_ptr item_name_index); - static JSON generate_proxy_client_json_st(std::shared_ptr ses); - static JSON generate_lobby_json_st(std::shared_ptr l, std::shared_ptr item_name_index); - JSON generate_game_server_clients_json() const; - JSON generate_proxy_server_clients_json() const; - JSON generate_server_info_json() const; - JSON generate_lobbies_json() const; - JSON generate_summary_json() const; - JSON generate_all_json() const; + static phosg::JSON generate_quest_json_st(std::shared_ptr q); + static phosg::JSON generate_client_config_json_st(const Client::Config& config); + static phosg::JSON generate_account_json_st(std::shared_ptr a); + static phosg::JSON generate_game_client_json_st(std::shared_ptr c, std::shared_ptr item_name_index); + static phosg::JSON generate_proxy_client_json_st(std::shared_ptr ses); + static phosg::JSON generate_lobby_json_st(std::shared_ptr l, std::shared_ptr item_name_index); + phosg::JSON generate_game_server_clients_json() const; + phosg::JSON generate_proxy_server_clients_json() const; + phosg::JSON generate_server_info_json() const; + phosg::JSON generate_lobbies_json() const; + phosg::JSON generate_summary_json() const; + phosg::JSON generate_all_json() const; - JSON generate_ep3_cards_json(bool trial) const; - JSON generate_common_tables_json() const; - JSON generate_rare_tables_json() const; - JSON generate_rare_table_json(const std::string& table_name) const; + phosg::JSON generate_ep3_cards_json(bool trial) const; + phosg::JSON generate_common_tables_json() const; + phosg::JSON generate_rare_tables_json() const; + phosg::JSON generate_rare_table_json(const std::string& table_name) const; }; diff --git a/src/IPFrameInfo.cc b/src/IPFrameInfo.cc index ca5156ca..11c54354 100644 --- a/src/IPFrameInfo.cc +++ b/src/IPFrameInfo.cc @@ -23,7 +23,7 @@ FrameInfo::FrameInfo(LinkType link_type, const void* header_start, size_t size) this->total_size = size; this->payload_size = size; - StringReader r(header_start, size); + phosg::StringReader r(header_start, size); // Parse link-layer header Protocol proto = Protocol::NONE; @@ -126,35 +126,35 @@ string FrameInfo::header_str() const { string ret; if (this->ether) { - ret = string_printf( + ret = phosg::string_printf( "ETHER:%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX->%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX", this->ether->src_mac[0], this->ether->src_mac[1], this->ether->src_mac[2], this->ether->src_mac[3], this->ether->src_mac[4], this->ether->src_mac[5], this->ether->dest_mac[0], this->ether->dest_mac[1], this->ether->dest_mac[2], this->ether->dest_mac[3], this->ether->dest_mac[4], this->ether->dest_mac[5]); } else if (this->hdlc) { - ret = string_printf("HDLC:%02hhX/%02hhX", this->hdlc->address, this->hdlc->control); + ret = phosg::string_printf("HDLC:%02hhX/%02hhX", this->hdlc->address, this->hdlc->control); } else { return ""; } if (this->arp) { - ret += string_printf( + ret += phosg::string_printf( ",ARP,hw_type=%04hX,proto_type=%04hX,hw_addr_len=%02hhX,proto_addr_len=%02hhX,op=%04hX", this->arp->hardware_type.load(), this->arp->protocol_type.load(), this->arp->hwaddr_len, this->arp->paddr_len, this->arp->operation.load()); } else if (this->ipv4) { - ret += string_printf( + ret += phosg::string_printf( ",IPv4,size=%04hX,src=%08" PRIX32 ",dest=%08" PRIX32, this->ipv4->size.load(), this->ipv4->src_addr.load(), this->ipv4->dest_addr.load()); if (this->udp) { - ret += string_printf( + ret += phosg::string_printf( ",UDP,src_port=%04hX,dest_port=%04hX,size=%04hX", this->udp->src_port.load(), this->udp->dest_port.load(), this->udp->size.load()); } else if (this->tcp) { - ret += string_printf( + ret += phosg::string_printf( ",TCP,src_port=%04hX,dest_port=%04hX,seq=%08" PRIX32 ",ack=%08" PRIX32 ",flags=%04hX(", this->tcp->src_port.load(), this->tcp->dest_port.load(), this->tcp->seq_num.load(), this->tcp->ack_num.load(), this->tcp->flags.load()); if (this->tcp->flags & TCPHeader::Flag::FIN) { @@ -175,14 +175,14 @@ string FrameInfo::header_str() const { ret += ')'; } else { - ret += string_printf(",proto=%02hhX", this->ipv4->protocol); + ret += phosg::string_printf(",proto=%02hhX", this->ipv4->protocol); } } else { if (this->ether) { - ret += string_printf(",proto=%04hX", this->ether->protocol.load()); + ret += phosg::string_printf(",proto=%04hX", this->ether->protocol.load()); } else if (this->hdlc) { - ret += string_printf(",proto=%04hX", this->hdlc->protocol.load()); + ret += phosg::string_printf(",proto=%04hX", this->hdlc->protocol.load()); } } diff --git a/src/IPFrameInfo.hh b/src/IPFrameInfo.hh index 29cd55a1..2fc7a91e 100644 --- a/src/IPFrameInfo.hh +++ b/src/IPFrameInfo.hh @@ -161,8 +161,8 @@ struct FrameInfo { std::string header_str() const; - inline StringReader read_payload() const { - return StringReader(this->payload, this->payload_size); + inline phosg::StringReader read_payload() const { + return phosg::StringReader(this->payload, this->payload_size); } void truncate(size_t new_total_size); diff --git a/src/IPStackSimulator.cc b/src/IPStackSimulator.cc index e07f1d7d..ac6cd47d 100644 --- a/src/IPStackSimulator.cc +++ b/src/IPStackSimulator.cc @@ -22,7 +22,7 @@ using namespace std; static const size_t DEFAULT_RESEND_PUSH_USECS = 200000; // 200ms static string unescape_hdlc_frame(const void* data, size_t size) { - StringReader r(data, size); + phosg::StringReader r(data, size); if (r.get_u8(data) != 0x7E) { throw runtime_error("HDLC frame does not begin with 7E"); } @@ -53,7 +53,7 @@ static string escape_hdlc_frame(const void* data, size_t size, uint32_t escape_c throw runtime_error("HDLC frame too small for start and end sentinels"); } - StringReader r(data, size); + phosg::StringReader r(data, size); if (r.pget_u8(size - 1) != 0x7E) { throw runtime_error("HDLC frame does not end with 7E"); } @@ -104,9 +104,9 @@ string IPStackSimulator::str_for_ipv4_netloc(uint32_t addr, uint16_t port) { be_uint32_t be_addr = addr; char addr_str[INET_ADDRSTRLEN]; if (!inet_ntop(AF_INET, &be_addr, addr_str, INET_ADDRSTRLEN)) { - return string_printf(":%hu", port); + return phosg::string_printf(":%hu", port); } else { - return string_printf("%s:%hu", addr_str, port); + return phosg::string_printf("%s:%hu", addr_str, port); } } @@ -115,7 +115,7 @@ string IPStackSimulator::str_for_tcp_connection(shared_ptr c, co string server_netloc_str = str_for_ipv4_netloc(conn.server_addr, conn.server_port); string client_netloc_str = str_for_ipv4_netloc(c->ipv4_addr, conn.client_port); int fd = bufferevent_getfd(c->bev.get()); - return string_printf("%d+%016" PRIX64 " (%s -> %s)", + return phosg::string_printf("%d+%016" PRIX64 " (%s -> %s)", fd, key, client_netloc_str.c_str(), server_netloc_str.c_str()); } @@ -137,7 +137,7 @@ IPStackSimulator::~IPStackSimulator() { } void IPStackSimulator::listen(const string& name, const string& socket_path, Protocol proto) { - int fd = ::listen(socket_path, 0, SOMAXCONN); + int fd = phosg::listen(socket_path, 0, SOMAXCONN); ip_stack_simulator_log.info("Listening on Unix socket %s on fd %d as %s", socket_path.c_str(), fd, name.c_str()); this->add_socket(name, fd, proto); } @@ -146,8 +146,8 @@ void IPStackSimulator::listen(const string& name, const string& addr, int port, if (port == 0) { this->listen(name, addr, proto); } else { - int fd = ::listen(addr, port, SOMAXCONN); - string netloc_str = render_netloc(addr, port); + int fd = phosg::listen(addr, port, SOMAXCONN); + string netloc_str = phosg::render_netloc(addr, port); ip_stack_simulator_log.info("Listening on TCP interface %s on fd %d as %s", netloc_str.c_str(), fd, name.c_str()); this->add_socket(name, fd, proto); } @@ -195,7 +195,7 @@ IPStackSimulator::IPClient::IPClient( ipv4_addr(0), idle_timeout_event(event_new(sim->base.get(), -1, EV_TIMEOUT, &IPStackSimulator::IPClient::dispatch_on_idle_timeout, this), event_free) { uint64_t idle_timeout_usecs = sim->state->client_idle_timeout_usecs; - struct timeval tv = usecs_to_timeval(idle_timeout_usecs); + struct timeval tv = phosg::usecs_to_timeval(idle_timeout_usecs); event_add(this->idle_timeout_event.get(), &tv); } @@ -247,7 +247,7 @@ void IPStackSimulator::dispatch_on_listen_accept( void IPStackSimulator::on_listen_accept(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr*, int) { struct sockaddr_storage remote_addr; - get_socket_addresses(fd, nullptr, &remote_addr); + phosg::get_socket_addresses(fd, nullptr, &remote_addr); if (this->state->banned_ipv4_ranges->check(remote_addr)) { close(fd); return; @@ -304,7 +304,7 @@ void IPStackSimulator::IPClient::on_client_input(struct bufferevent* bev) { } uint64_t idle_timeout_usecs = sim ? sim->state->client_idle_timeout_usecs : 60000000; - struct timeval tv = usecs_to_timeval(idle_timeout_usecs); + struct timeval tv = phosg::usecs_to_timeval(idle_timeout_usecs); event_add(this->idle_timeout_event.get(), &tv); switch (this->protocol) { @@ -325,7 +325,7 @@ void IPStackSimulator::IPClient::on_client_input(struct bufferevent* bev) { sim->on_client_frame(this->shared_from_this(), frame); } catch (const exception& e) { if (ip_stack_simulator_log.warning("Failed to process frame: %s", e.what())) { - print_data(stderr, frame); + phosg::print_data(stderr, frame); } } } @@ -360,7 +360,7 @@ void IPStackSimulator::IPClient::on_client_input(struct bufferevent* bev) { sim->on_client_frame(this->shared_from_this(), frame); } catch (const exception& e) { if (ip_stack_simulator_log.warning("Failed to process frame: %s", e.what())) { - print_data(stderr, frame); + phosg::print_data(stderr, frame); } } } @@ -416,7 +416,7 @@ void IPStackSimulator::send_layer3_frame(shared_ptr c, FrameInfo::Prot evbuffer_add(out_buf, ðer, sizeof(ether)); evbuffer_add(out_buf, data, size); if (this->pcap_text_log_file) { - StringWriter w; + phosg::StringWriter w; w.write(ðer, sizeof(ether)); w.write(data, size); this->log_frame(w.str()); @@ -451,7 +451,7 @@ void IPStackSimulator::send_layer3_frame(shared_ptr c, FrameInfo::Prot throw logic_error("unknown layer 3 protocol"); } - StringWriter w; + phosg::StringWriter w; w.put(hdlc); w.write(data, size); w.put_u16l(FrameInfo::computed_hdlc_checksum(w.str().data() + 1, w.size() - 1)); @@ -459,7 +459,7 @@ void IPStackSimulator::send_layer3_frame(shared_ptr c, FrameInfo::Prot string escaped = escape_hdlc_frame(w.str(), c->hdlc_escape_control_character_flags); if (ip_stack_simulator_log.debug("Sending HDLC frame to virtual network (escaped to %zX bytes)", escaped.size())) { - print_data(stderr, w.str()); + phosg::print_data(stderr, w.str()); } if (c->protocol == Protocol::HDLC_TAPSERVER) { @@ -490,12 +490,12 @@ void IPStackSimulator::on_client_frame(shared_ptr c, const string& fra effective_data = &hdlc_unescaped_data; } if (ip_stack_simulator_log.debug("Virtual network sent frame")) { - print_data(stderr, *effective_data); + phosg::print_data(stderr, *effective_data); } this->log_frame(*effective_data); FrameInfo fi(link_type, *effective_data); - if (ip_stack_simulator_log.should_log(LogLevel::DEBUG)) { + if (ip_stack_simulator_log.should_log(phosg::LogLevel::DEBUG)) { string fi_header = fi.header_str(); ip_stack_simulator_log.debug("Frame header: %s", fi_header.c_str()); } @@ -510,7 +510,7 @@ void IPStackSimulator::on_client_frame(shared_ptr c, const string& fra uint16_t expected_checksum = fi.computed_hdlc_checksum(); uint16_t stored_checksum = fi.stored_hdlc_checksum(); if (expected_checksum != stored_checksum) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "HDLC checksum is incorrect (%04hX expected, %04hX received)", expected_checksum, stored_checksum)); } @@ -533,7 +533,7 @@ void IPStackSimulator::on_client_frame(shared_ptr c, const string& fra } else if (fi.ipv4) { uint16_t expected_ipv4_checksum = fi.computed_ipv4_header_checksum(); if (fi.ipv4->checksum != expected_ipv4_checksum) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "IPv4 header checksum is incorrect (%04hX expected, %04hX received)", expected_ipv4_checksum, fi.ipv4->checksum.load())); } @@ -545,7 +545,7 @@ void IPStackSimulator::on_client_frame(shared_ptr c, const string& fra if (fi.udp) { uint16_t expected_udp_checksum = fi.computed_udp4_checksum(); if (fi.udp->checksum != expected_udp_checksum) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "UDP checksum is incorrect (%04hX expected, %04hX received)", expected_udp_checksum, fi.udp->checksum.load())); } @@ -554,7 +554,7 @@ void IPStackSimulator::on_client_frame(shared_ptr c, const string& fra } else if (fi.tcp) { uint16_t expected_tcp_checksum = fi.computed_tcp4_checksum(); if (fi.tcp->checksum != expected_tcp_checksum) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "TCP checksum is incorrect (%04hX expected, %04hX received)", expected_tcp_checksum, fi.tcp->checksum.load())); } @@ -576,7 +576,7 @@ void IPStackSimulator::on_client_lcp_frame(shared_ptr c, const FrameIn while (!opts_r.eof()) { uint8_t opt = opts_r.get_u8(); string opt_data = opts_r.read(opts_r.get_u8() - 2); - StringReader opt_data_r(opt_data); + phosg::StringReader opt_data_r(opt_data); switch (opt) { case 0x01: // Maximum receive unit // TODO: Currently we ignore this, but we probably should use it. @@ -593,7 +593,7 @@ void IPStackSimulator::on_client_lcp_frame(shared_ptr c, const FrameIn case 0x04: // Quality protocol case 0x07: // Protocol field compression case 0x08: // Address and control field compression - throw runtime_error(string_printf("unimplemented LCP option %02hhX (%zu bytes)", opt, opt_data.size())); + throw runtime_error(phosg::string_printf("unimplemented LCP option %02hhX (%zu bytes)", opt, opt_data.size())); default: throw runtime_error("unknown LCP option"); } @@ -602,7 +602,7 @@ void IPStackSimulator::on_client_lcp_frame(shared_ptr c, const FrameIn // lazy to do this right now. In our situation, it should suffice to // simply always send a Configure-Request to the client with a magic // number not equal to the one we received. - StringWriter opts_w; + phosg::StringWriter opts_w; opts_w.put_u8(0x01); // Maximum receive unit opts_w.put_u8(0x04); opts_w.put_u16b(1500); @@ -615,7 +615,7 @@ void IPStackSimulator::on_client_lcp_frame(shared_ptr c, const FrameIn opts_w.put_u8(0x05); // Magic number (bitwise inverse of the remote end's) opts_w.put_u8(0x06); opts_w.put_u32b(~c->hdlc_remote_magic_number); - StringWriter request_w; + phosg::StringWriter request_w; request_w.put(LCPHeader{ .command = 0x01, // Configure-Request .request_id = fi.lcp->request_id, @@ -624,7 +624,7 @@ void IPStackSimulator::on_client_lcp_frame(shared_ptr c, const FrameIn request_w.write(opts_w.str()); this->send_layer3_frame(c, FrameInfo::Protocol::LCP, request_w.str()); - StringWriter ack_w; + phosg::StringWriter ack_w; ack_w.put(LCPHeader{ .command = 0x02, // Configure-Ack .request_id = fi.lcp->request_id, @@ -679,7 +679,7 @@ void IPStackSimulator::on_client_pap_frame(shared_ptr c, const FrameIn ip_stack_simulator_log.info("Client logged in with username \"%s\" and password", username.c_str()); static const string login_message = "newserv PPP simulator"; - StringWriter w; + phosg::StringWriter w; w.put(PAPHeader{ .command = 0x02, // Authenticate-Ack .request_id = fi.pap->request_id, @@ -698,11 +698,11 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI uint32_t remote_ip = 0; uint32_t remote_primary_dns = 0; uint32_t remote_secondary_dns = 0; - StringWriter rejected_opts_w; + phosg::StringWriter rejected_opts_w; while (!opts_r.eof()) { uint8_t opt = opts_r.get_u8(); string opt_data = opts_r.read(opts_r.get_u8() - 2); - StringReader opt_data_r(opt_data); + phosg::StringReader opt_data_r(opt_data); switch (opt) { case 0x01: // IP addresses (deprecated as of 1992; we don't support it at all) throw runtime_error("IPCP client sent IP-Addresses option"); @@ -723,7 +723,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI case 0x82: // Primary NBNS server address case 0x84: // Secondary NBNS server address case 0x04: // Mobile IP address - throw runtime_error(string_printf("unimplemented IPCP option %02hhX (%zu bytes)", opt, opt_data.size())); + throw runtime_error(phosg::string_printf("unimplemented IPCP option %02hhX (%zu bytes)", opt, opt_data.size())); default: throw runtime_error("unknown IPCP option"); } @@ -731,7 +731,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI if (!rejected_opts_w.str().empty()) { // Send a Configure-Reject if the client specified IP header compression - StringWriter reject_w; + phosg::StringWriter reject_w; reject_w.put(IPCPHeader{ .command = 0x04, // Configure-Reject .request_id = fi.ipcp->request_id, @@ -745,7 +745,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI (remote_secondary_dns != 0x24242424)) { // Send a Configure-Nak if the client's request doesn't exactly match // what we want them to use. - StringWriter opts_w; + phosg::StringWriter opts_w; opts_w.put_u8(0x03); // IP address opts_w.put_u8(0x06); opts_w.put_u32b(0x1E1E1E1E); @@ -756,7 +756,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI opts_w.put_u8(0x06); opts_w.put_u32b(0x24242424); - StringWriter nak_w; + phosg::StringWriter nak_w; nak_w.put(IPCPHeader{ .command = 0x03, // Configure-Nak .request_id = fi.ipcp->request_id, @@ -770,7 +770,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI // As with LCP, we technically should implement the state machine, but I // continue to be lazy. - StringWriter opts_w; + phosg::StringWriter opts_w; opts_w.put_u8(0x03); // IP address opts_w.put_u8(0x06); opts_w.put_u32b(0x39393939); @@ -781,7 +781,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI opts_w.put_u8(0x06); opts_w.put_u32b(0x24242424); - StringWriter request_w; + phosg::StringWriter request_w; request_w.put(IPCPHeader{ .command = 0x01, // Configure-Request .request_id = fi.ipcp->request_id, @@ -790,7 +790,7 @@ void IPStackSimulator::on_client_ipcp_frame(shared_ptr c, const FrameI request_w.write(opts_w.str()); this->send_layer3_frame(c, FrameInfo::Protocol::IPCP, request_w.str()); - StringWriter ack_w; + phosg::StringWriter ack_w; ack_w.put(IPCPHeader{ .command = 0x02, // Configure-Ack .request_id = fi.ipcp->request_id, @@ -841,7 +841,7 @@ void IPStackSimulator::on_client_arp_frame( reinterpret_cast(fi.payload) + 6); } - StringWriter w; + phosg::StringWriter w; w.put(ARPHeader{ .hardware_type = fi.arp->hardware_type, .protocol_type = fi.arp->protocol_type, @@ -942,7 +942,7 @@ void IPStackSimulator::on_client_udp_frame(shared_ptr c, const FrameIn throw runtime_error("client sent unknown DHCP command option"); } - StringWriter w; + phosg::StringWriter w; DHCPHeader r_dhcp; r_dhcp.opcode = 2; // Response r_dhcp.hardware_type = 1; // Ethernet @@ -1027,13 +1027,13 @@ void IPStackSimulator::on_client_udp_frame(shared_ptr c, const FrameIn r_udp.checksum = FrameInfo::computed_udp4_checksum( r_ipv4, r_udp, r_data.data(), r_data.size()); - if (ip_stack_simulator_log.should_log(LogLevel::DEBUG)) { + if (ip_stack_simulator_log.should_log(phosg::LogLevel::DEBUG)) { string remote_str = this->str_for_ipv4_netloc(fi.ipv4->src_addr, fi.udp->src_port); ip_stack_simulator_log.debug("Sending UDP response to %s", remote_str.c_str()); - print_data(stderr, r_data); + phosg::print_data(stderr, r_data); } - StringWriter w; + phosg::StringWriter w; w.put(r_ipv4); w.put(r_udp); w.write(r_data); @@ -1079,7 +1079,7 @@ void IPStackSimulator::on_client_tcp_frame( throw runtime_error("TCP SYN contains extra flags"); } - StringReader options_r(fi.tcp + 1, fi.tcp_options_size); + phosg::StringReader options_r(fi.tcp + 1, fi.tcp_options_size); size_t max_frame_size = 1400; while (!options_r.eof()) { uint8_t option = options_r.get_u8(); @@ -1135,7 +1135,7 @@ void IPStackSimulator::on_client_tcp_frame( conn.server_port = fi.tcp->dest_port; conn.client_port = fi.tcp->src_port; conn.next_client_seq = fi.tcp->seq_num + 1; - conn.acked_server_seq = random_object(); + conn.acked_server_seq = phosg::random_object(); conn.resend_push_usecs = DEFAULT_RESEND_PUSH_USECS; conn.next_push_max_frame_size = max_frame_size; conn.awaiting_first_ack = true; @@ -1240,7 +1240,7 @@ void IPStackSimulator::on_client_tcp_frame( // server immediately. } else if (fi.payload_size != 0) { - string conn_str = ip_stack_simulator_log.should_log(LogLevel::WARNING) + string conn_str = ip_stack_simulator_log.should_log(phosg::LogLevel::WARNING) ? this->str_for_tcp_connection(c, *conn) : ""; @@ -1285,7 +1285,7 @@ void IPStackSimulator::on_client_tcp_frame( conn_str.c_str()); } if (was_logged) { - print_data(stderr, payload, payload_size); + phosg::print_data(stderr, payload, payload_size); } // Send the new data to the server @@ -1388,7 +1388,7 @@ void IPStackSimulator::send_pending_push_frame( conn.acked_server_seq, bytes_to_send, pending_bytes); this->send_tcp_frame(c, conn, TCPHeader::Flag::PSH, conn.pending_data.get(), bytes_to_send); - struct timeval resend_push_timeout = usecs_to_timeval(conn.resend_push_usecs); + struct timeval resend_push_timeout = phosg::usecs_to_timeval(conn.resend_push_usecs); event_add(conn.resend_push_event.get(), &resend_push_timeout); // If the client isn't responding to our PSHes, back off exponentially up to @@ -1441,7 +1441,7 @@ void IPStackSimulator::send_tcp_frame( const void* linear_data = src_bytes ? evbuffer_pullup(src_buf, src_bytes) : nullptr; tcp.checksum = FrameInfo::computed_tcp4_checksum(ipv4, tcp, linear_data, src_bytes); - StringWriter w; + phosg::StringWriter w; w.put(ipv4); w.put(tcp); if (src_bytes) { @@ -1488,7 +1488,7 @@ void IPStackSimulator::on_server_input(shared_ptr c, IPClient::TCPConn auto sim = c->sim.lock(); uint64_t idle_timeout_usecs = sim ? sim->state->client_idle_timeout_usecs : 60000000; - struct timeval tv = usecs_to_timeval(idle_timeout_usecs); + struct timeval tv = phosg::usecs_to_timeval(idle_timeout_usecs); event_add(c->idle_timeout_event.get(), &tv); evbuffer_add_buffer(conn.pending_data.get(), buf); @@ -1534,8 +1534,7 @@ void IPStackSimulator::on_server_error( void IPStackSimulator::log_frame(const string& data) const { if (this->pcap_text_log_file) { - print_data(this->pcap_text_log_file, data, 0, nullptr, - PrintDataFlags::SKIP_SEPARATOR); + phosg::print_data(this->pcap_text_log_file, data, 0, nullptr, phosg::PrintDataFlags::SKIP_SEPARATOR); fputc('\n', this->pcap_text_log_file); fflush(this->pcap_text_log_file); } diff --git a/src/IPV4RangeSet.cc b/src/IPV4RangeSet.cc index 289bbcd5..ec727cb8 100644 --- a/src/IPV4RangeSet.cc +++ b/src/IPV4RangeSet.cc @@ -4,10 +4,10 @@ using namespace std; -IPV4RangeSet::IPV4RangeSet(const JSON& json) { +IPV4RangeSet::IPV4RangeSet(const phosg::JSON& json) { for (const auto& it : json.as_list()) { // String should be of the form a.b.c.d or a.b.c.d/e - auto tokens = split(it->as_string(), '/'); + auto tokens = phosg::split(it->as_string(), '/'); size_t mask_bits; if (tokens.size() == 1) { @@ -21,7 +21,7 @@ IPV4RangeSet::IPV4RangeSet(const JSON& json) { throw runtime_error("invalid IPv4 address range"); } - auto addr_tokens = split(tokens[0], '.'); + auto addr_tokens = phosg::split(tokens[0], '.'); if (addr_tokens.size() != 4) { throw runtime_error("invalid IPv4 address"); } @@ -40,12 +40,12 @@ IPV4RangeSet::IPV4RangeSet(const JSON& json) { } } -JSON IPV4RangeSet::json() const { - auto ret = JSON::list(); +phosg::JSON IPV4RangeSet::json() const { + auto ret = phosg::JSON::list(); for (const auto& it : this->ranges) { uint32_t addr = it.first; uint8_t mask_bits = it.second; - ret.emplace_back(string_printf("%hhu.%hhu.%hhu.%hhu/%hhu", + ret.emplace_back(phosg::string_printf("%hhu.%hhu.%hhu.%hhu/%hhu", static_cast((addr >> 24) & 0xFF), static_cast((addr >> 16) & 0xFF), static_cast((addr >> 8) & 0xFF), diff --git a/src/IPV4RangeSet.hh b/src/IPV4RangeSet.hh index b8fce939..1849f2ae 100644 --- a/src/IPV4RangeSet.hh +++ b/src/IPV4RangeSet.hh @@ -6,9 +6,9 @@ class IPV4RangeSet { public: IPV4RangeSet() = default; - explicit IPV4RangeSet(const JSON& json); + explicit IPV4RangeSet(const phosg::JSON& json); - JSON json() const; + phosg::JSON json() const; bool check(uint32_t addr) const; bool check(const struct sockaddr_storage& ss) const; diff --git a/src/IntegralExpression.cc b/src/IntegralExpression.cc index 03ac448e..b4d3f237 100644 --- a/src/IntegralExpression.cc +++ b/src/IntegralExpression.cc @@ -184,7 +184,7 @@ int64_t IntegralExpression::FlagLookupNode::evaluate(const Env& env) const { } string IntegralExpression::FlagLookupNode::str() const { - return string_printf("F_%04hX", this->flag_index); + return phosg::string_printf("F_%04hX", this->flag_index); } IntegralExpression::ChallengeCompletionLookupNode::ChallengeCompletionLookupNode( @@ -214,7 +214,7 @@ int64_t IntegralExpression::ChallengeCompletionLookupNode::evaluate(const Env& e } string IntegralExpression::ChallengeCompletionLookupNode::str() const { - return string_printf("CC_%s_%hhu", abbreviation_for_episode(this->episode), static_cast(this->stage_index + 1)); + return phosg::string_printf("CC_%s_%hhu", abbreviation_for_episode(this->episode), static_cast(this->stage_index + 1)); } IntegralExpression::TeamRewardLookupNode::TeamRewardLookupNode(const string& reward_name) @@ -296,7 +296,7 @@ int64_t IntegralExpression::ConstantNode::evaluate(const Env&) const { } string IntegralExpression::ConstantNode::str() const { - return string_printf("%" PRId64, this->value); + return phosg::string_printf("%" PRId64, this->value); } unique_ptr IntegralExpression::parse_expr(string_view text) { diff --git a/src/ItemCreator.cc b/src/ItemCreator.cc index 9e0b570e..c42fc894 100644 --- a/src/ItemCreator.cc +++ b/src/ItemCreator.cc @@ -36,7 +36,7 @@ ItemCreator::ItemCreator( uint8_t section_id, std::shared_ptr opt_rand_crypt, shared_ptr restrictions) - : log(string_printf("[ItemCreator:%s/%s/%s/%c/%hhu] ", name_for_enum(stack_limits->version), abbreviation_for_episode(episode), abbreviation_for_mode(mode), abbreviation_for_difficulty(difficulty), section_id), lobby_log.min_level), + : log(phosg::string_printf("[ItemCreator:%s/%s/%s/%c/%hhu] ", phosg::name_for_enum(stack_limits->version), abbreviation_for_episode(episode), abbreviation_for_mode(mode), abbreviation_for_difficulty(difficulty), section_id), lobby_log.min_level), logic_version(stack_limits->version), stack_limits(stack_limits), episode(episode), @@ -63,8 +63,8 @@ void ItemCreator::set_random_crypt(shared_ptr new_random_crypt void ItemCreator::set_section_id(uint8_t new_section_id) { if (this->section_id != new_section_id) { this->section_id = new_section_id; - this->log.prefix = string_printf("[ItemCreator:%s/%s/%s/%c/%hhu] ", - name_for_enum(stack_limits->version), + this->log.prefix = phosg::string_printf("[ItemCreator:%s/%s/%s/%c/%hhu] ", + phosg::name_for_enum(stack_limits->version), abbreviation_for_episode(episode), abbreviation_for_mode(mode), abbreviation_for_difficulty(difficulty), @@ -298,13 +298,13 @@ ItemData ItemCreator::check_rare_specs_and_create_rare_box_item(uint8_t area_nor for (const auto& spec : rare_specs) { item = this->check_rate_and_create_rare_item(spec, area_norm); if (!item.empty()) { - if (this->log.should_log(LogLevel::INFO)) { + if (this->log.should_log(phosg::LogLevel::INFO)) { auto hex = spec.data.hex(); this->log.info("Box spec %08" PRIX32 " produced item %s", spec.probability, hex.c_str()); } break; } - if (this->log.should_log(LogLevel::INFO)) { + if (this->log.should_log(phosg::LogLevel::INFO)) { auto hex = spec.data.hex(); this->log.info("Box spec %08" PRIX32 " did not produce item %s", spec.probability, hex.c_str()); } @@ -359,13 +359,13 @@ ItemData ItemCreator::check_rare_spec_and_create_rare_enemy_item(uint32_t enemy_ for (const auto& spec : rare_specs) { item = this->check_rate_and_create_rare_item(spec, area_norm); if (!item.empty()) { - if (this->log.should_log(LogLevel::INFO)) { + if (this->log.should_log(phosg::LogLevel::INFO)) { auto hex = spec.data.hex(); this->log.info("Enemy spec %08" PRIX32 " produced item %s", spec.probability, hex.c_str()); } break; } - if (this->log.should_log(LogLevel::INFO)) { + if (this->log.should_log(phosg::LogLevel::INFO)) { auto hex = spec.data.hex(); this->log.info("Enemy spec %08" PRIX32 " did not produce item %s", spec.probability, hex.c_str()); } diff --git a/src/ItemCreator.hh b/src/ItemCreator.hh index ee39d07e..49908ba2 100644 --- a/src/ItemCreator.hh +++ b/src/ItemCreator.hh @@ -58,7 +58,7 @@ public: void set_section_id(uint8_t new_section_id); private: - PrefixedLogger log; + phosg::PrefixedLogger log; Version logic_version; std::shared_ptr stack_limits; Episode episode; diff --git a/src/ItemData.cc b/src/ItemData.cc index bd35b5b8..15f563a1 100644 --- a/src/ItemData.cc +++ b/src/ItemData.cc @@ -21,7 +21,7 @@ ItemData::StackLimits::StackLimits( max_tool_stack_sizes_by_data1_1(max_tool_stack_sizes_by_data1_1), max_meseta_stack_size(max_meseta_stack_size) {} -ItemData::StackLimits::StackLimits(Version version, const JSON& json) +ItemData::StackLimits::StackLimits(Version version, const phosg::JSON& json) : version(version) { this->max_tool_stack_sizes_by_data1_1.clear(); for (const auto& limit_json : json.at("ToolLimits").as_list()) { @@ -53,8 +53,8 @@ ItemData::ItemData(const ItemData& other) { ItemData::ItemData(uint64_t first, uint64_t second) { *reinterpret_cast(&this->data1[0]) = first; - this->data1d[2] = bswap32((second >> 32) & 0xFFFFFFFF); - this->data2d = bswap32(second & 0xFFFFFFFF); + this->data1d[2] = phosg::bswap32((second >> 32) & 0xFFFFFFFF); + this->data2d = phosg::bswap32(second & 0xFFFFFFFF); } ItemData& ItemData::operator=(const ItemData& other) { @@ -400,7 +400,7 @@ void ItemData::decode_for_version(Version from_version) { // data2d field, since internally it's actually a uint32_t. We treat it // as individual bytes instead, so we correct for the client's // byteswapping here. - this->data2d = bswap32(this->data2d); + this->data2d = phosg::bswap32(this->data2d); } break; @@ -482,7 +482,7 @@ void ItemData::encode_for_version(Version to_version, shared_ptrdata2w[1] = this->data2[0] | ((this->data2[2] << 15) & 0x8000); this->data2w[0] = this->data2[1]; } else if (is_big_endian(to_version)) { - this->data2d = bswap32(this->data2d); + this->data2d = phosg::bswap32(this->data2d); } break; @@ -743,12 +743,12 @@ ItemData ItemData::from_primary_identifier(const StackLimits& limits, uint32_t p } string ItemData::hex() const { - return string_printf("%08" PRIX32 " %08" PRIX32 " %08" PRIX32 " (%08" PRIX32 ") %08" PRIX32, + return phosg::string_printf("%08" PRIX32 " %08" PRIX32 " %08" PRIX32 " (%08" PRIX32 ") %08" PRIX32, this->data1db[0].load(), this->data1db[1].load(), this->data1db[2].load(), this->id.load(), this->data2db.load()); } string ItemData::short_hex() const { - auto ret = string_printf("%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "%08" PRIX32, + auto ret = phosg::string_printf("%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "%08" PRIX32, this->data1db[0].load(), this->data1db[1].load(), this->data1db[2].load(), this->data2db.load()); size_t offset = ret.find_last_not_of('0'); if (offset != string::npos) { diff --git a/src/ItemData.hh b/src/ItemData.hh index 60a19982..1ecd2d0e 100644 --- a/src/ItemData.hh +++ b/src/ItemData.hh @@ -62,7 +62,7 @@ struct ItemData { uint32_t max_meseta_stack_size; StackLimits(Version version, const std::vector& max_tool_stack_sizes_by_data1_1, uint32_t max_meseta_stack_size); - StackLimits(Version version, const JSON& json); + StackLimits(Version version, const phosg::JSON& json); StackLimits(const StackLimits& other) = default; StackLimits(StackLimits&& other) = default; StackLimits& operator=(const StackLimits& other) = default; diff --git a/src/ItemNameIndex.cc b/src/ItemNameIndex.cc index ed0e0267..d4e45be1 100644 --- a/src/ItemNameIndex.cc +++ b/src/ItemNameIndex.cc @@ -24,7 +24,7 @@ ItemNameIndex::ItemNameIndex( meta->primary_identifier = primary_identifier; meta->name = *name; this->primary_identifier_index.emplace(meta->primary_identifier, meta); - this->name_index.emplace(tolower(meta->name), meta); + this->name_index.emplace(phosg::tolower(meta->name), meta); } } } @@ -99,7 +99,7 @@ const array name_for_s_rank_special = { std::string ItemNameIndex::describe_item(const ItemData& item, bool include_color_escapes) const { if (item.data1[0] == 0x04) { - return string_printf("%s%" PRIu32 " Meseta", include_color_escapes ? "$C7" : "", item.data2d.load()); + return phosg::string_printf("%s%" PRIu32 " Meseta", include_color_escapes ? "$C7" : "", item.data2d.load()); } vector ret_tokens; @@ -120,7 +120,7 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo try { ret_tokens.emplace_back(name_for_weapon_special.at(special_id)); } catch (const out_of_range&) { - ret_tokens.emplace_back(string_printf("!SP:%02hhX", special_id)); + ret_tokens.emplace_back(phosg::string_printf("!SP:%02hhX", special_id)); } } } @@ -128,7 +128,7 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo try { ret_tokens.emplace_back(name_for_s_rank_special.at(item.data1[2])); } catch (const out_of_range&) { - ret_tokens.emplace_back(string_printf("!SSP:%02hhX", item.data1[2])); + ret_tokens.emplace_back(phosg::string_printf("!SSP:%02hhX", item.data1[2])); } } @@ -149,34 +149,34 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo technique_name = tech_id_to_name.at(item.data1[4]); technique_name[0] = toupper(technique_name[0]); } catch (const out_of_range&) { - technique_name = string_printf("!TD:%02hhX", item.data1[4]); + technique_name = phosg::string_printf("!TD:%02hhX", item.data1[4]); } // Hide the level for Reverser and Ryuker, unless the level isn't 1 if ((item.data1[2] == 0) && ((item.data1[4] == 0x0E) || (item.data1[4] == 0x11))) { - ret_tokens.emplace_back(string_printf("Disk:%s", technique_name.c_str())); + ret_tokens.emplace_back(phosg::string_printf("Disk:%s", technique_name.c_str())); } else { - ret_tokens.emplace_back(string_printf("Disk:%s Lv.%d", technique_name.c_str(), item.data1[2] + 1)); + ret_tokens.emplace_back(phosg::string_printf("Disk:%s Lv.%d", technique_name.c_str(), item.data1[2] + 1)); } } else { try { auto meta = this->primary_identifier_index.at(primary_identifier); ret_tokens.emplace_back(meta->name); } catch (const out_of_range&) { - ret_tokens.emplace_back(string_printf("!ID:%08" PRIX32, primary_identifier)); + ret_tokens.emplace_back(phosg::string_printf("!ID:%08" PRIX32, primary_identifier)); } } // For weapons, add the grind and bonuses, or S-rank name if applicable if (item.data1[0] == 0x00) { if (item.data1[3] > 0) { - ret_tokens.emplace_back(string_printf("+%hhu", item.data1[3])); + ret_tokens.emplace_back(phosg::string_printf("+%hhu", item.data1[3])); } if (item.is_s_rank_weapon()) { // S-rank (has name instead of percent bonuses) - uint16_t be_data1w3 = bswap16(item.data1w[3]); - uint16_t be_data1w4 = bswap16(item.data1w[4]); - uint16_t be_data1w5 = bswap16(item.data1w[5]); + uint16_t be_data1w3 = phosg::bswap16(item.data1w[3]); + uint16_t be_data1w4 = phosg::bswap16(item.data1w[4]); + uint16_t be_data1w5 = phosg::bswap16(item.data1w[5]); uint8_t char_indexes[8] = { static_cast((be_data1w3 >> 5) & 0x1F), static_cast(be_data1w3 & 0x1F), @@ -210,9 +210,9 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo } if (which & 0x80) { uint16_t kill_count = ((which << 8) & 0x7F00) | (value & 0xFF); - ret_tokens.emplace_back(string_printf("K:%hu", kill_count)); + ret_tokens.emplace_back(phosg::string_printf("K:%hu", kill_count)); } else if (which > 5) { - ret_tokens.emplace_back(string_printf("!PC:%02hhX%02hhX", which, value)); + ret_tokens.emplace_back(phosg::string_printf("!PC:%02hhX%02hhX", which, value)); } else { bonuses[which - 1] = value; } @@ -222,11 +222,11 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo bool should_highlight_hit = include_color_escapes && (bonuses[4] > 0); const char* color_prefix = include_color_escapes ? "$C7" : ""; if (should_include_hit) { - ret_tokens.emplace_back(string_printf("%s%hhd/%hhd/%hhd/%hhd/%s%hhd", + ret_tokens.emplace_back(phosg::string_printf("%s%hhd/%hhd/%hhd/%hhd/%s%hhd", color_prefix, bonuses[0], bonuses[1], bonuses[2], bonuses[3], (should_highlight_hit ? "$C6" : ""), bonuses[4])); } else { - ret_tokens.emplace_back(string_printf("%s%hhd/%hhd/%hhd/%hhd", + ret_tokens.emplace_back(phosg::string_printf("%s%hhd/%hhd/%hhd/%hhd", color_prefix, bonuses[0], bonuses[1], bonuses[2], bonuses[3])); } } @@ -245,7 +245,7 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo } else if (modifier <= -3) { ret_tokens.back().append("--"); } else if (modifier != 0) { - ret_tokens.emplace_back(string_printf("!MD:%04hX", modifier)); + ret_tokens.emplace_back(phosg::string_printf("!MD:%04hX", modifier)); } } else { // Armor/shields @@ -253,22 +253,22 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo if (item.data1[5] == 1) { ret_tokens.emplace_back("(1 slot)"); } else { - ret_tokens.emplace_back(string_printf("(%hhu slots)", item.data1[5])); + ret_tokens.emplace_back(phosg::string_printf("(%hhu slots)", item.data1[5])); } } if (item.data1w[3] != 0) { - ret_tokens.emplace_back(string_printf("+%hdDEF", + ret_tokens.emplace_back(phosg::string_printf("+%hdDEF", static_cast(item.data1w[3].load()))); } if (item.data1w[4] != 0) { - ret_tokens.emplace_back(string_printf("+%hdEVP", + ret_tokens.emplace_back(phosg::string_printf("+%hdEVP", static_cast(item.data1w[4].load()))); } } // For mags, add tons of info } else if (item.data1[0] == 0x02) { - ret_tokens.emplace_back(string_printf("LV%hhu", item.data1[2])); + ret_tokens.emplace_back(phosg::string_printf("LV%hhu", item.data1[2])); uint16_t def = item.data1w[2]; uint16_t pow = item.data1w[3]; @@ -278,16 +278,16 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo uint16_t level = stat / 100; uint8_t partial = stat % 100; if (partial == 0) { - return string_printf("%hu", level); + return phosg::string_printf("%hu", level); } else if (partial % 10 == 0) { - return string_printf("%hu.%hhu", level, static_cast(partial / 10)); + return phosg::string_printf("%hu.%hhu", level, static_cast(partial / 10)); } else { - return string_printf("%hu.%02hhu", level, partial); + return phosg::string_printf("%hu.%02hhu", level, partial); } }; ret_tokens.emplace_back(format_stat(def) + "/" + format_stat(pow) + "/" + format_stat(dex) + "/" + format_stat(mind)); - ret_tokens.emplace_back(string_printf("%hhu%%", item.data2[0])); - ret_tokens.emplace_back(string_printf("%hhuIQ", item.data2[1])); + ret_tokens.emplace_back(phosg::string_printf("%hhu%%", item.data2[0])); + ret_tokens.emplace_back(phosg::string_printf("%hhuIQ", item.data2[1])); uint8_t flags = item.data2[2]; if (flags & 7) { @@ -322,19 +322,19 @@ std::string ItemNameIndex::describe_item(const ItemData& item, bool include_colo } try { - ret_tokens.emplace_back(string_printf("(%s)", name_for_mag_color.at(item.data2[3]))); + ret_tokens.emplace_back(phosg::string_printf("(%s)", name_for_mag_color.at(item.data2[3]))); } catch (const out_of_range&) { - ret_tokens.emplace_back(string_printf("(!CL:%02hhX)", item.data2[3])); + ret_tokens.emplace_back(phosg::string_printf("(!CL:%02hhX)", item.data2[3])); } // For tools, add the amount (if applicable) } else if (item.data1[0] == 0x03) { if (item.max_stack_size(*this->limits) > 1) { - ret_tokens.emplace_back(string_printf("x%hhu", item.data1[5])); + ret_tokens.emplace_back(phosg::string_printf("x%hhu", item.data1[5])); } } - string ret = join(ret_tokens, " "); + string ret = phosg::join(ret_tokens, " "); if (include_color_escapes) { if (is_unidentified) { return "$C3" + ret; @@ -361,13 +361,13 @@ ItemData ItemNameIndex::parse_item_description(const std::string& desc) const { ret = this->parse_item_description_phase(desc, true); } catch (const exception& e2) { try { - ret = ItemData::from_data(parse_data_string(desc)); + ret = ItemData::from_data(phosg::parse_data_string(desc)); } catch (const exception& ed) { if (strcmp(e1.what(), e2.what())) { - throw runtime_error(string_printf("cannot parse item description \"%s\" (as text 1: %s) (as text 2: %s) (as data: %s)", + throw runtime_error(phosg::string_printf("cannot parse item description \"%s\" (as text 1: %s) (as text 2: %s) (as data: %s)", desc.c_str(), e1.what(), e2.what(), ed.what())); } else { - throw runtime_error(string_printf("cannot parse item description \"%s\" (as text: %s) (as data: %s)", + throw runtime_error(phosg::string_printf("cannot parse item description \"%s\" (as text: %s) (as data: %s)", desc.c_str(), e1.what(), ed.what())); } } @@ -383,15 +383,15 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript ret.id = 0xFFFFFFFF; ret.data2d = 0; - string desc = tolower(description); - if (ends_with(desc, " meseta")) { + string desc = phosg::tolower(description); + if (phosg::ends_with(desc, " meseta")) { ret.data1[0] = 0x04; ret.data2d = stol(desc, nullptr, 10); return ret; } - if (starts_with(desc, "disk:")) { - auto tokens = split(desc, ' '); + if (phosg::starts_with(desc, "disk:")) { + auto tokens = phosg::split(desc, ' '); tokens[0] = tokens[0].substr(5); // Trim off "disk:" if ((tokens[0] == "reverser") || (tokens[0] == "ryuker")) { uint8_t tech = technique_for_name(tokens[0]); @@ -403,7 +403,7 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript if (tokens.size() != 2) { throw runtime_error("invalid tech disk format"); } - if (!starts_with(tokens[1], "lv.")) { + if (!phosg::starts_with(tokens[1], "lv.")) { throw runtime_error("invalid tech disk level"); } uint8_t tech = technique_for_name(tokens[0]); @@ -416,11 +416,11 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript return ret; } - bool is_wrapped = starts_with(desc, "wrapped "); + bool is_wrapped = phosg::starts_with(desc, "wrapped "); if (is_wrapped) { desc = desc.substr(8); } - bool is_unidentified = starts_with(desc, "?"); + bool is_unidentified = phosg::starts_with(desc, "?"); if (is_unidentified) { size_t z; for (z = 1; z < desc.size(); z++) { @@ -438,9 +438,9 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript if (!name_for_weapon_special[z]) { continue; } - string prefix = tolower(name_for_weapon_special[z]); + string prefix = phosg::tolower(name_for_weapon_special[z]); prefix += ' '; - if (starts_with(desc, prefix)) { + if (phosg::starts_with(desc, prefix)) { weapon_special = z; desc = desc.substr(prefix.size()); break; @@ -454,7 +454,7 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript // then we'll see Sange & Yasha first, which we should skip. size_t lookback = 0; while (lookback < 4) { - if (name_it != this->name_index.end() && desc.starts_with(name_it->first)) { + if (name_it != this->name_index.end() && phosg::starts_with(desc, name_it->first)) { break; } else if (name_it == this->name_index.begin()) { throw runtime_error("no such item"); @@ -468,7 +468,7 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript } desc = desc.substr(name_it->first.size()); - if (starts_with(desc, " ")) { + if (phosg::starts_with(desc, " ")) { desc = desc.substr(1); } @@ -483,12 +483,12 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript // Weapons: add special, grind and percentages (or name, if S-rank) ret.data1[4] = weapon_special | (is_wrapped ? 0x40 : 0x00) | (is_unidentified ? 0x80 : 0x00); - auto tokens = split(desc, ' '); + auto tokens = phosg::split(desc, ' '); for (auto& token : tokens) { if (token.empty()) { continue; } - if (starts_with(token, "+")) { + if (phosg::starts_with(token, "+")) { token = token.substr(1); ret.data1[3] = stoul(token, nullptr, 10); @@ -502,17 +502,17 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript char ch = toupper(token[z]); const char* pos = strchr(s_rank_name_characters, ch); if (!pos) { - throw runtime_error(string_printf("s-rank name contains invalid character %02hhX (%c)", ch, ch)); + throw runtime_error(phosg::string_printf("s-rank name contains invalid character %02hhX (%c)", ch, ch)); } char_indexes[z] = (pos - s_rank_name_characters); } - ret.data1w[3] = bswap16(0x8000 | (char_indexes[1] & 0x1F) | ((char_indexes[0] & 0x1F) << 5)); - ret.data1w[4] = bswap16(0x8000 | (char_indexes[4] & 0x1F) | ((char_indexes[3] & 0x1F) << 5) | ((char_indexes[2] & 0x1F) << 10)); - ret.data1w[5] = bswap16(0x8000 | (char_indexes[7] & 0x1F) | ((char_indexes[6] & 0x1F) << 5) | ((char_indexes[5] & 0x1F) << 10)); + ret.data1w[3] = phosg::bswap16(0x8000 | (char_indexes[1] & 0x1F) | ((char_indexes[0] & 0x1F) << 5)); + ret.data1w[4] = phosg::bswap16(0x8000 | (char_indexes[4] & 0x1F) | ((char_indexes[3] & 0x1F) << 5) | ((char_indexes[2] & 0x1F) << 10)); + ret.data1w[5] = phosg::bswap16(0x8000 | (char_indexes[7] & 0x1F) | ((char_indexes[6] & 0x1F) << 5) | ((char_indexes[5] & 0x1F) << 10)); } else { - auto p_tokens = split(token, '/'); + auto p_tokens = phosg::split(token, '/'); if (p_tokens.size() > 5) { throw runtime_error("invalid bonuses token"); } @@ -544,15 +544,15 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript ret.data1w[3] = modifiers.at(desc); } else { // Armor/shield - for (const auto& token : split(desc, ' ')) { + for (const auto& token : phosg::split(desc, ' ')) { if (token.empty()) { continue; - } else if (!starts_with(token, "+")) { + } else if (!phosg::starts_with(token, "+")) { throw runtime_error("invalid armor/shield modifier"); } - if (ends_with(token, "def")) { + if (phosg::ends_with(token, "def")) { ret.data1w[3] = static_cast(stol(token.substr(1, token.size() - 4), nullptr, 10)); - } else if (ends_with(token, "evp")) { + } else if (phosg::ends_with(token, "evp")) { ret.data1w[4] = static_cast(stol(token.substr(1, token.size() - 4), nullptr, 10)); } else { ret.data1[5] = stoul(token.substr(1), nullptr, 10); @@ -565,11 +565,11 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript } } else if (ret.data1[0] == 0x02) { - for (const auto& token : split(desc, ' ')) { + for (const auto& token : phosg::split(desc, ' ')) { if (token.empty()) { continue; - } else if (starts_with(token, "pb:")) { // Photon blasts - auto pb_tokens = split(token.substr(3), ','); + } else if (phosg::starts_with(token, "pb:")) { // Photon blasts + auto pb_tokens = phosg::split(token.substr(3), ','); if (pb_tokens.size() > 3) { throw runtime_error("too many photon blasts specified"); } @@ -586,17 +586,17 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript for (const auto& pb_token : pb_tokens) { ret.add_mag_photon_blast(name_to_pb_num.at(pb_token)); } - } else if (ends_with(token, "%")) { // Synchro + } else if (phosg::ends_with(token, "%")) { // Synchro ret.data2[0] = stoul(token.substr(0, token.size() - 1), nullptr, 10); - } else if (ends_with(token, "iq")) { // IQ + } else if (phosg::ends_with(token, "iq")) { // IQ ret.data2[1] = stoul(token.substr(0, token.size() - 2), nullptr, 10); } else if (!token.empty() && isdigit(token[0])) { // Stats - auto s_tokens = split(token, '/'); + auto s_tokens = phosg::split(token, '/'); if (s_tokens.size() != 4) { throw runtime_error("incorrect stat count"); } for (size_t z = 0; z < 4; z++) { - auto n_tokens = split(s_tokens[z], '.'); + auto n_tokens = phosg::split(s_tokens[z], '.'); if (n_tokens.size() == 0 || n_tokens.size() > 2) { throw logic_error("incorrect stats argument format"); } else if ((n_tokens.size() == 1) || (n_tokens[1].size() == 0)) { @@ -620,7 +620,7 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript } } else if (ret.data1[0] == 0x03) { if (ret.max_stack_size(*this->limits) > 1) { - if (starts_with(desc, "x")) { + if (phosg::starts_with(desc, "x")) { ret.data1[5] = stoul(desc.substr(1), nullptr, 10); } else { ret.data1[5] = 1; @@ -650,7 +650,7 @@ void ItemNameIndex::print_table(FILE* stream) const { for (size_t data1_1 = 0; data1_1 < pmt->num_weapon_classes; data1_1++) { uint8_t v1_replacement = pmt->get_weapon_v1_replacement(data1_1); float sale_divisor = pmt->get_sale_divisor(0x00, data1_1); - string divisor_str = string_printf("%g", sale_divisor); + string divisor_str = phosg::string_printf("%g", sale_divisor); divisor_str.resize(13, ' '); size_t data1_2_limit = pmt->num_weapons_in_class(data1_1); @@ -708,7 +708,7 @@ void ItemNameIndex::print_table(FILE* stream) const { fprintf(stream, "ARMOR => ---ID--- TYPE SKIN POINTS -DFP- -EVP- BP BE FLAG LVL EFR ETH EIC EDK ELT DFR EVR SB TB -A2- ST* ---DIVISOR--- NAME\n"); for (size_t data1_1 = 1; data1_1 < 3; data1_1++) { float sale_divisor = pmt->get_sale_divisor(0x01, data1_1); - string divisor_str = string_printf("%g", sale_divisor); + string divisor_str = phosg::string_printf("%g", sale_divisor); divisor_str.resize(13, ' '); size_t data1_2_limit = pmt->num_armors_or_shields_in_class(data1_1); @@ -754,7 +754,7 @@ void ItemNameIndex::print_table(FILE* stream) const { fprintf(stream, "UNIT => ---ID--- TYPE SKIN POINTS STAT COUNT ST-MOD ST* ---DIVISOR--- NAME\n"); { float sale_divisor = pmt->get_sale_divisor(0x01, 0x03); - string divisor_str = string_printf("%g", sale_divisor); + string divisor_str = phosg::string_printf("%g", sale_divisor); divisor_str.resize(13, ' '); size_t data1_2_limit = pmt->num_units(); @@ -791,7 +791,7 @@ void ItemNameIndex::print_table(FILE* stream) const { uint8_t stars = pmt->get_item_stars(m.base.id); float sale_divisor = pmt->get_sale_divisor(0x02, data1_1); - string divisor_str = string_printf("%g", sale_divisor); + string divisor_str = phosg::string_printf("%g", sale_divisor); divisor_str.resize(13, ' '); ItemData item; @@ -827,7 +827,7 @@ void ItemNameIndex::print_table(FILE* stream) const { fprintf(stream, "TOOL => ---ID--- TYPE SKIN POINTS COUNT TECH -COST- ITEMFLAG ST* ---DIVISOR--- NAME\n"); for (size_t data1_1 = 0; data1_1 < pmt->num_tool_classes; data1_1++) { float sale_divisor = pmt->get_sale_divisor(0x03, data1_1); - string divisor_str = string_printf("%g", sale_divisor); + string divisor_str = phosg::string_printf("%g", sale_divisor); divisor_str.resize(13, ' '); size_t data1_2_limit = pmt->num_tools_in_class(data1_1); diff --git a/src/ItemParameterTable.cc b/src/ItemParameterTable.cc index aa105ebb..72ec0b55 100644 --- a/src/ItemParameterTable.cc +++ b/src/ItemParameterTable.cc @@ -206,8 +206,8 @@ ItemParameterTable::WeaponV4 ItemParameterTable::WeaponGCNTE::to_v4() const { return ret; } -template -ItemParameterTable::WeaponV4 ItemParameterTable::WeaponV3T::to_v4() const { +template +ItemParameterTable::WeaponV4 ItemParameterTable::WeaponV3T::to_v4() const { WeaponV4 ret; ret.base.id = this->base.id.load(); ret.base.type = this->base.type.load(); @@ -281,8 +281,8 @@ ItemParameterTable::ArmorOrShieldV4 ItemParameterTable::ArmorOrShieldV1V2::to_v4 return ret; } -template -ItemParameterTable::ArmorOrShieldV4 ItemParameterTable::ArmorOrShieldV3T::to_v4() const { +template +ItemParameterTable::ArmorOrShieldV4 ItemParameterTable::ArmorOrShieldV3T::to_v4() const { ArmorOrShieldV4 ret; ret.base.id = this->base.id.load(); ret.base.type = this->base.type.load(); @@ -323,8 +323,8 @@ ItemParameterTable::UnitV4 ItemParameterTable::UnitV1V2::to_v4() const { return ret; } -template -ItemParameterTable::UnitV4 ItemParameterTable::UnitV3T::to_v4() const { +template +ItemParameterTable::UnitV4 ItemParameterTable::UnitV3T::to_v4() const { UnitV4 ret; ret.base.id = this->base.id.load(); ret.base.type = this->base.type.load(); @@ -370,8 +370,8 @@ ItemParameterTable::MagV4 ItemParameterTable::MagV2::to_v4() const { return ret; } -template -ItemParameterTable::MagV4 ItemParameterTable::MagV3T::to_v4() const { +template +ItemParameterTable::MagV4 ItemParameterTable::MagV3T::to_v4() const { MagV4 ret; ret.base.id = this->base.id.load(); ret.base.type = this->base.type.load(); @@ -401,8 +401,8 @@ ItemParameterTable::ToolV4 ItemParameterTable::ToolV1V2::to_v4() const { return ret; } -template -ItemParameterTable::ToolV4 ItemParameterTable::ToolV3T::to_v4() const { +template +ItemParameterTable::ToolV4 ItemParameterTable::ToolV3T::to_v4() const { ToolV4 ret; ret.base.id = this->base.id.load(); ret.base.type = this->base.type.load(); @@ -414,15 +414,15 @@ ItemParameterTable::ToolV4 ItemParameterTable::ToolV3T::to_v4() con return ret; } -template -size_t indirect_lookup_2d_count(const StringReader& r, size_t root_offset, size_t co_index) { - using ArrayRefT = typename std::conditional_t; +template +size_t indirect_lookup_2d_count(const phosg::StringReader& r, size_t root_offset, size_t co_index) { + using ArrayRefT = typename std::conditional_t; return r.pget(root_offset + sizeof(ArrayRefT) * co_index).count; } -template -const T& indirect_lookup_2d(const StringReader& r, size_t root_offset, size_t co_index, size_t item_index) { - using ArrayRefT = typename std::conditional_t; +template +const T& indirect_lookup_2d(const phosg::StringReader& r, size_t root_offset, size_t co_index, size_t item_index) { + using ArrayRefT = typename std::conditional_t; const auto& co = r.pget(root_offset + sizeof(ArrayRefT) * co_index); if (item_index >= co.count) { @@ -706,10 +706,10 @@ const ItemParameterTable::ToolV4& ItemParameterTable::get_tool(uint8_t data1_1, } } -template +template pair ItemParameterTable::find_tool_by_id_t(uint32_t tool_table_offset, uint32_t item_id) const { - const auto* cos = &this->r.pget>( - tool_table_offset, this->num_tool_classes * sizeof(ArrayRefT)); + const auto* cos = &this->r.pget>( + tool_table_offset, this->num_tool_classes * sizeof(ArrayRefT)); for (size_t z = 0; z < this->num_tool_classes; z++) { const auto& co = cos[z]; const auto* defs = &this->r.pget(co.offset, sizeof(ToolDefT) * co.count); @@ -719,7 +719,7 @@ pair ItemParameterTable::find_tool_by_id_t(uint32_t tool_table } } } - throw out_of_range(string_printf("invalid tool class %08" PRIX32, item_id)); + throw out_of_range(phosg::string_printf("invalid tool class %08" PRIX32, item_id)); } pair ItemParameterTable::find_tool_by_id(uint32_t item_id) const { @@ -740,19 +740,17 @@ pair ItemParameterTable::find_tool_by_id(uint32_t item_id) con } } -template +template float ItemParameterTable::get_sale_divisor_t(const OffsetsT* offsets, uint8_t data1_0, uint8_t data1_1) const { - using FloatT = typename std::conditional::type; - switch (data1_0) { case 0: if (data1_1 >= this->num_weapon_classes) { return 0.0f; } - return this->r.pget(offsets->weapon_sale_divisor_table + data1_1 * sizeof(FloatT)); + return this->r.pget>(offsets->weapon_sale_divisor_table + data1_1 * sizeof(F32T)); case 1: { - const auto& divisors = this->r.pget>(offsets->sale_divisor_table); + const auto& divisors = this->r.pget>(offsets->sale_divisor_table); switch (data1_1) { case 1: return divisors.armor_divisor; @@ -765,7 +763,7 @@ float ItemParameterTable::get_sale_divisor_t(const OffsetsT* offsets, uint8_t da } case 2: { - const auto& divisors = this->r.pget>(offsets->sale_divisor_table); + const auto& divisors = this->r.pget>(offsets->sale_divisor_table); return divisors.mag_divisor; } @@ -1136,9 +1134,9 @@ const std::map>& Item return this->item_combination_index; } -template +template size_t ItemParameterTable::num_events_t(uint32_t base_offset) const { - return this->r.pget>(base_offset).count; + return this->r.pget>(base_offset).count; } size_t ItemParameterTable::num_events() const { @@ -1155,14 +1153,14 @@ size_t ItemParameterTable::num_events() const { } } -template +template std::pair ItemParameterTable::get_event_items_t( uint32_t base_offset, uint8_t event_number) const { - const auto& co = this->r.pget>(base_offset); + const auto& co = this->r.pget>(base_offset); if (event_number >= co.count) { throw out_of_range("invalid event number"); } - const auto& event_co = this->r.pget>(co.offset + sizeof(ArrayRefT) * event_number); + const auto& event_co = this->r.pget>(co.offset + sizeof(ArrayRefT) * event_number); const auto* defs = &this->r.pget(event_co.offset, event_co.count * sizeof(EventItem)); return make_pair(defs, event_co.count); } diff --git a/src/ItemParameterTable.hh b/src/ItemParameterTable.hh index b609c5c7..19ff09ca 100644 --- a/src/ItemParameterTable.hh +++ b/src/ItemParameterTable.hh @@ -11,6 +11,7 @@ #include "ItemData.hh" #include "Text.hh" +#include "Types.hh" class ItemParameterTable { public: @@ -18,11 +19,10 @@ public: // functions instead of manually branching on various offset table pointers // being null or not in each public function. Rewrite this and make it better. - template + template struct ArrayRefT { - using U32T = typename std::conditional::type; - /* 00 */ U32T count; - /* 04 */ U32T offset; + /* 00 */ U32T count; + /* 04 */ U32T offset; /* 08 */ } __packed__; @@ -31,25 +31,22 @@ public: check_struct_size(ArrayRef, 8); check_struct_size(ArrayRefBE, 8); - template + template struct ItemBaseV2T { - using U32T = typename std::conditional::type; // id specifies several things; notably, it doubles as the index of the // item's name in the text archive (e.g. TextEnglish) collection 0. - /* 00 */ U32T id = 0xFFFFFFFF; + /* 00 */ U32T id = 0xFFFFFFFF; /* 04 */ } __packed__; - template - struct ItemBaseV3T : ItemBaseV2T { - using U16T = typename std::conditional::type; - /* 04 */ U16T type = 0; - /* 06 */ U16T skin = 0; + template + struct ItemBaseV3T : ItemBaseV2T { + /* 04 */ U16T type = 0; + /* 06 */ U16T skin = 0; /* 08 */ } __packed__; - template - struct ItemBaseV4T : ItemBaseV3T { - using U32T = typename std::conditional::type; - /* 08 */ U32T team_points = 0; + template + struct ItemBaseV4T : ItemBaseV3T { + /* 08 */ U32T team_points = 0; /* 0C */ } __packed__; @@ -118,17 +115,16 @@ public: WeaponV4 to_v4() const; } __packed_ws__(WeaponGCNTE, 0x24); - template + template struct WeaponV3T { - using U16T = typename std::conditional::type; - /* 00 */ ItemBaseV3T base; - /* 08 */ U16T class_flags = 0; - /* 0A */ U16T atp_min = 0; - /* 0C */ U16T atp_max = 0; - /* 0E */ U16T atp_required = 0; - /* 10 */ U16T mst_required = 0; - /* 12 */ U16T ata_required = 0; - /* 14 */ U16T mst = 0; + /* 00 */ ItemBaseV3T base; + /* 08 */ U16T class_flags = 0; + /* 0A */ U16T atp_min = 0; + /* 0C */ U16T atp_max = 0; + /* 0E */ U16T atp_required = 0; + /* 10 */ U16T mst_required = 0; + /* 12 */ U16T ata_required = 0; + /* 14 */ U16T mst = 0; /* 16 */ uint8_t max_grind = 0; /* 17 */ uint8_t photon = 0; /* 18 */ uint8_t special = 0; @@ -187,16 +183,15 @@ public: /* 2C */ } __packed_ws__(WeaponV4, 0x2C); - template + template struct ArmorOrShieldT { - using U16T = typename std::conditional::type; /* V1/V2 offsets */ /* 00 */ BaseT base; - /* 04 */ U16T dfp = 0; - /* 06 */ U16T evp = 0; + /* 04 */ U16T dfp = 0; + /* 06 */ U16T evp = 0; /* 08 */ uint8_t block_particle = 0; /* 09 */ uint8_t block_effect = 0; - /* 0A */ U16T class_flags = 0x00FF; + /* 0A */ U16T class_flags = 0x00FF; /* 0C */ uint8_t required_level = 0; /* 0D */ uint8_t efr = 0; /* 0E */ uint8_t eth = 0; @@ -208,12 +203,11 @@ public: /* 14 */ } __packed__; - template - struct ArmorOrShieldFinalT : ArmorOrShieldT { - using U16T = typename std::conditional::type; + template + struct ArmorOrShieldFinalT : ArmorOrShieldT { /* 14 */ uint8_t stat_boost = 0; /* 15 */ uint8_t tech_boost = 0; - /* 16 */ U16T unknown_a2 = 0; + /* 16 */ U16T unknown_a2 = 0; /* 18 */ } __packed__; using ArmorOrShieldV4 = ArmorOrShieldFinalT, false>; @@ -225,8 +219,8 @@ public: struct ArmorOrShieldV1V2 : ArmorOrShieldFinalT, false> { ArmorOrShieldV4 to_v4() const; } __packed_ws__(ArmorOrShieldV1V2, 0x18); - template - struct ArmorOrShieldV3T : ArmorOrShieldFinalT, IsBigEndian> { + template + struct ArmorOrShieldV3T : ArmorOrShieldFinalT, BE> { ArmorOrShieldV4 to_v4() const; } __packed__; using ArmorOrShieldV3 = ArmorOrShieldV3T; @@ -234,21 +228,18 @@ public: check_struct_size(ArmorOrShieldV3, 0x1C); check_struct_size(ArmorOrShieldV3BE, 0x1C); - template + template struct UnitT { - using U16T = typename std::conditional::type; - using S16T = typename std::conditional::type; /* V1/V2 offsets */ /* 00 */ BaseT base; - /* 04 */ U16T stat = 0; - /* 06 */ U16T stat_amount = 0; + /* 04 */ U16T stat = 0; + /* 06 */ U16T stat_amount = 0; /* 08 */ } __packed__; - template - struct UnitFinalT : UnitT { - using S16T = typename std::conditional::type; - /* 08 */ S16T modifier_amount = 0; + template + struct UnitFinalT : UnitT { + /* 08 */ S16T modifier_amount = 0; /* 0A */ parray unused; /* 0C */ } __packed__; @@ -260,8 +251,8 @@ public: struct UnitV1V2 : UnitFinalT, false> { UnitV4 to_v4() const; } __packed_ws__(UnitV1V2, 0x0C); - template - struct UnitV3T : UnitFinalT, IsBigEndian> { + template + struct UnitV3T : UnitFinalT, BE> { UnitV4 to_v4() const; } __packed__; using UnitV3 = UnitV3T; @@ -269,12 +260,11 @@ public: check_struct_size(UnitV3, 0x10); check_struct_size(UnitV3BE, 0x10); - template + template struct MagT { - using U16T = typename std::conditional::type; /* V1/V2 offsets */ /* 00 */ BaseT base; - /* 04 */ U16T feed_table = 0; + /* 04 */ U16T feed_table = 0; /* 06 */ uint8_t photon_blast = 0; /* 07 */ uint8_t activation = 0; /* 08 */ uint8_t on_pb_full = 0; @@ -317,10 +307,9 @@ public: MagV4 to_v4() const; } __packed_ws__(MagV2, 0x14); - template - struct MagV3T : MagT, IsBigEndian> { - using U16T = typename std::conditional::type; - /* 10 */ U16T class_flags = 0x00FF; + template + struct MagV3T : MagT, BE> { + /* 10 */ U16T class_flags = 0x00FF; /* 12 */ parray unused; /* 14 */ @@ -331,16 +320,13 @@ public: check_struct_size(MagV3, 0x18); check_struct_size(MagV3BE, 0x18); - template + template struct ToolT { - using U16T = typename std::conditional::type; - using S32T = typename std::conditional::type; - using U32T = typename std::conditional::type; /* V1/V2 offsets */ /* 00 */ BaseT base; - /* 04 */ U16T amount = 0; - /* 06 */ U16T tech = 0; - /* 08 */ S32T cost = 0; + /* 04 */ U16T amount = 0; + /* 06 */ U16T tech = 0; + /* 08 */ S32T cost = 0; // Bits in item_flags: // 00000001 - ever usable by player ("Use" appears in inventory menu) // 00000002 - unknown @@ -350,7 +336,7 @@ public: // 00000020 - usable in boss arenas // 00000040 - usable in Challenge mode // 00000080 - is rare (renders as red box; V3+) - /* 0C */ U32T item_flags = 0; + /* 0C */ U32T item_flags = 0; /* 10 */ } __packed__; @@ -359,8 +345,8 @@ public: struct ToolV1V2 : ToolT, false> { ToolV4 to_v4() const; } __packed_ws__(ToolV1V2, 0x10); - template - struct ToolV3T : ToolT, IsBigEndian> { + template + struct ToolV3T : ToolT, BE> { ToolV4 to_v4() const; } __packed__; using ToolV3 = ToolV3T; @@ -380,34 +366,31 @@ public: using MagFeedResultsList = parray; - template + template struct MagFeedResultsListOffsetsT { - using U32T = typename std::conditional::type; - parray offsets; // Offsets of MagFeedResultsList objects + parray, 8> offsets; // Offsets of MagFeedResultsList objects } __packed__; using MagFeedResultsListOffsets = MagFeedResultsListOffsetsT; using MagFeedResultsListOffsetsBE = MagFeedResultsListOffsetsT; check_struct_size(MagFeedResultsListOffsets, 0x20); check_struct_size(MagFeedResultsListOffsetsBE, 0x20); - template + template struct SpecialT { - using U16T = typename std::conditional::type; - U16T type = 0xFFFF; - U16T amount = 0; + U16T type = 0xFFFF; + U16T amount = 0; } __packed__; using Special = SpecialT; using SpecialBE = SpecialT; check_struct_size(Special, 4); check_struct_size(SpecialBE, 4); - template + template struct StatBoostT { - using U16T = typename std::conditional::type; uint8_t stat1 = 0; uint8_t stat2 = 0; - U16T amount1 = 0; - U16T amount2 = 0; + U16T amount1 = 0; + U16T amount2 = 0; } __packed__; using StatBoost = StatBoostT; using StatBoostBE = StatBoostT; @@ -428,16 +411,14 @@ public: parray unused; } __packed_ws__(ItemCombination, 0x10); - template + template struct TechniqueBoostT { - using U32T = typename std::conditional::type; - using FloatT = typename std::conditional::type; - U32T tech1 = 0; - FloatT boost1 = 0.0f; - U32T tech2 = 0; - FloatT boost2 = 0.0f; - U32T tech3 = 0; - FloatT boost3 = 0.0f; + U32T tech1 = 0; + F32T boost1 = 0.0f; + U32T tech2 = 0; + F32T boost2 = 0.0f; + U32T tech3 = 0; + F32T boost3 = 0.0f; } __packed__; using TechniqueBoost = TechniqueBoostT; using TechniqueBoostBE = TechniqueBoostT; @@ -454,13 +435,12 @@ public: uint8_t unused = 0; } __packed_ws__(UnsealableItem, 4); - template + template struct NonWeaponSaleDivisorsT { - using FloatT = typename std::conditional::type; - FloatT armor_divisor = 0.0f; - FloatT shield_divisor = 0.0f; - FloatT unit_divisor = 0.0f; - FloatT mag_divisor = 0.0f; + F32T armor_divisor = 0.0f; + F32T shield_divisor = 0.0f; + F32T unit_divisor = 0.0f; + F32T mag_divisor = 0.0f; } __packed__; using NonWeaponSaleDivisors = NonWeaponSaleDivisorsT; using NonWeaponSaleDivisorsBE = NonWeaponSaleDivisorsT; @@ -587,33 +567,32 @@ private: /* 4C / 6B1C */ be_uint32_t tech_boost_table; // -> [TechniqueBoost] (always 0x2C of them? from counts struct?) } __packed_ws__(TableOffsetsGCNTE, 0x50); - template + template struct TableOffsetsV3V4T { - using U32T = typename std::conditional::type; /* ## / GC / BB */ - /* 00 / F078 / 14884 */ U32T weapon_table; // -> [{count, offset -> [WeaponV3/WeaponV4]}](0xED) - /* 04 / EF90 / 1478C */ U32T armor_table; // -> [{count, offset -> [ArmorOrShieldV3/ArmorOrShieldV4]}](2; armors and shields) - /* 08 / EFA0 / 1479C */ U32T unit_table; // -> {count, offset -> [UnitV3/UnitV4]} (last if out of range) - /* 0C / EFB0 / 147AC */ U32T tool_table; // -> [{count, offset -> [ToolV3/ToolV4]}](0x1A) (last if out of range) - /* 10 / EFA8 / 147A4 */ U32T mag_table; // -> {count, offset -> [MagV3/MagV4]} - /* 14 / B88C / 0F4B8 */ U32T v1_replacement_table; // -> [uint8_t](0xED) - /* 18 / A7FC / 0DE7C */ U32T photon_color_table; // -> [0x24-byte structs](0x20) - /* 1C / AACC / 0E194 */ U32T weapon_range_table; // -> ??? - /* 20 / B938 / 0F5A8 */ U32T weapon_sale_divisor_table; // -> [float](0xED) - /* 24 / BBCC / 0F83C */ U32T sale_divisor_table; // -> NonWeaponSaleDivisors - /* 28 / F608 / 1502C */ U32T mag_feed_table; // -> MagFeedResultsTable - /* 2C / BE9C / 0FB0C */ U32T star_value_table; // -> [uint8_t](0x330) (indexed by .id from weapon, armor, etc.) - /* 30 / C100 / 0FE3C */ U32T special_data_table; // -> [Special] - /* 34 / C1A4 / 0FEE0 */ U32T weapon_effect_table; // -> [16-byte structs] - /* 38 / DE50 / 1275C */ U32T stat_boost_table; // -> [StatBoost] - /* 3C / D6E4 / 11C80 */ U32T shield_effect_table; // -> [8-byte structs] - /* 40 / DF88 / 12894 */ U32T max_tech_level_table; // -> MaxTechniqueLevels - /* 44 / F5D0 / 14FF4 */ U32T combination_table; // -> {count, offset -> [ItemCombination]} - /* 48 / DE48 / 12754 */ U32T unknown_a1; - /* 4C / EB8C / 14278 */ U32T tech_boost_table; // -> [TechniqueBoost] (always 0x2C of them? from counts struct?) - /* 50 / F5F0 / 15014 */ U32T unwrap_table; // -> {count, offset -> [{count, offset -> [EventItem]}]} - /* 54 / F5F8 / 1501C */ U32T unsealable_table; // -> {count, offset -> [UnsealableItem]} - /* 58 / F600 / 15024 */ U32T ranged_special_table; // -> {count, offset -> [4-byte structs]} + /* 00 / F078 / 14884 */ U32T weapon_table; // -> [{count, offset -> [WeaponV3/WeaponV4]}](0xED) + /* 04 / EF90 / 1478C */ U32T armor_table; // -> [{count, offset -> [ArmorOrShieldV3/ArmorOrShieldV4]}](2; armors and shields) + /* 08 / EFA0 / 1479C */ U32T unit_table; // -> {count, offset -> [UnitV3/UnitV4]} (last if out of range) + /* 0C / EFB0 / 147AC */ U32T tool_table; // -> [{count, offset -> [ToolV3/ToolV4]}](0x1A) (last if out of range) + /* 10 / EFA8 / 147A4 */ U32T mag_table; // -> {count, offset -> [MagV3/MagV4]} + /* 14 / B88C / 0F4B8 */ U32T v1_replacement_table; // -> [uint8_t](0xED) + /* 18 / A7FC / 0DE7C */ U32T photon_color_table; // -> [0x24-byte structs](0x20) + /* 1C / AACC / 0E194 */ U32T weapon_range_table; // -> ??? + /* 20 / B938 / 0F5A8 */ U32T weapon_sale_divisor_table; // -> [float](0xED) + /* 24 / BBCC / 0F83C */ U32T sale_divisor_table; // -> NonWeaponSaleDivisors + /* 28 / F608 / 1502C */ U32T mag_feed_table; // -> MagFeedResultsTable + /* 2C / BE9C / 0FB0C */ U32T star_value_table; // -> [uint8_t](0x330) (indexed by .id from weapon, armor, etc.) + /* 30 / C100 / 0FE3C */ U32T special_data_table; // -> [Special] + /* 34 / C1A4 / 0FEE0 */ U32T weapon_effect_table; // -> [16-byte structs] + /* 38 / DE50 / 1275C */ U32T stat_boost_table; // -> [StatBoost] + /* 3C / D6E4 / 11C80 */ U32T shield_effect_table; // -> [8-byte structs] + /* 40 / DF88 / 12894 */ U32T max_tech_level_table; // -> MaxTechniqueLevels + /* 44 / F5D0 / 14FF4 */ U32T combination_table; // -> {count, offset -> [ItemCombination]} + /* 48 / DE48 / 12754 */ U32T unknown_a1; + /* 4C / EB8C / 14278 */ U32T tech_boost_table; // -> [TechniqueBoost] (always 0x2C of them? from counts struct?) + /* 50 / F5F0 / 15014 */ U32T unwrap_table; // -> {count, offset -> [{count, offset -> [EventItem]}]} + /* 54 / F5F8 / 1501C */ U32T unsealable_table; // -> {count, offset -> [UnsealableItem]} + /* 58 / F600 / 15024 */ U32T ranged_special_table; // -> {count, offset -> [4-byte structs]} } __packed__; using TableOffsetsV3V4 = TableOffsetsV3V4T; using TableOffsetsV3V4BE = TableOffsetsV3V4T; @@ -622,7 +601,7 @@ private: Version version; std::shared_ptr data; - StringReader r; + phosg::StringReader r; const TableOffsetsDCProtos* offsets_dc_protos; const TableOffsetsV1V2* offsets_v1_v2; const TableOffsetsGCNTE* offsets_gc_nte; @@ -644,13 +623,13 @@ private: // equipped_item may contain wildcards, and the matching order matters. mutable std::map> item_combination_index; - template + template std::pair find_tool_by_id_t(uint32_t tool_table_offset, uint32_t id) const; - template + template float get_sale_divisor_t(const OffsetsT* offsets, uint8_t data1_0, uint8_t data1_1) const; - template + template size_t num_events_t(uint32_t base_offset) const; - template + template std::pair get_event_items_t(uint32_t base_offset, uint8_t event_number) const; }; @@ -677,6 +656,6 @@ public: private: std::shared_ptr data; - StringReader r; + phosg::StringReader r; const TableOffsets* offsets; }; diff --git a/src/LevelTable.cc b/src/LevelTable.cc index 12d88a38..c382c615 100644 --- a/src/LevelTable.cc +++ b/src/LevelTable.cc @@ -54,13 +54,13 @@ LevelTableV2::LevelTableV2(const string& data, bool compressed) { le_uint32_t unknown_a12; // -> u32[3] -> (0x14-byte struct)[0x0F] } __packed_ws__(Offsets, 0x40); - StringReader r; + phosg::StringReader r; string decompressed_data; if (compressed) { decompressed_data = prs_decompress(data); - r = StringReader(decompressed_data); + r = phosg::StringReader(decompressed_data); } else { - r = StringReader(data); + r = phosg::StringReader(data); } const auto& offsets = r.pget(r.pget_u32l(r.size() - 0x10)); @@ -94,7 +94,7 @@ const LevelStatsDelta& LevelTableV2::stats_delta_for_level(uint8_t char_class, u } LevelTableV3BE::LevelTableV3BE(const string& data, bool encrypted) { - StringReader r; + phosg::StringReader r; string decompressed_data; if (encrypted) { auto decrypted = decrypt_pr2_data(data); @@ -102,9 +102,9 @@ LevelTableV3BE::LevelTableV3BE(const string& data, bool encrypted) { if (decompressed_data.size() != decrypted.decompressed_size) { throw runtime_error("decompressed data size does not match expected size"); } - r = StringReader(decompressed_data); + r = phosg::StringReader(decompressed_data); } else { - r = StringReader(data); + r = phosg::StringReader(data); } // The GC format is very simple (but everything is big-endian): @@ -160,13 +160,13 @@ LevelTableV4::LevelTableV4(const string& data, bool compressed) { le_uint32_t level_deltas; // -> u32[12] -> LevelStatsDelta[200] } __packed_ws__(Offsets, 8); - StringReader r; + phosg::StringReader r; string decompressed_data; if (compressed) { decompressed_data = prs_decompress(data); - r = StringReader(decompressed_data); + r = phosg::StringReader(decompressed_data); } else { - r = StringReader(data); + r = phosg::StringReader(data); } const auto& offsets = r.pget(r.pget_u32l(r.size() - 0x10)); diff --git a/src/LevelTable.hh b/src/LevelTable.hh index 2d87c2ab..8e857821 100644 --- a/src/LevelTable.hh +++ b/src/LevelTable.hh @@ -11,21 +11,19 @@ class LevelTable; -template +template struct CharacterStatsT { - using U16T = typename std::conditional::type; - - /* 00 */ U16T atp = 0; - /* 02 */ U16T mst = 0; - /* 04 */ U16T evp = 0; - /* 06 */ U16T hp = 0; - /* 08 */ U16T dfp = 0; - /* 0A */ U16T ata = 0; - /* 0C */ U16T lck = 0; + /* 00 */ U16T atp = 0; + /* 02 */ U16T mst = 0; + /* 04 */ U16T evp = 0; + /* 06 */ U16T hp = 0; + /* 08 */ U16T dfp = 0; + /* 0A */ U16T ata = 0; + /* 0C */ U16T lck = 0; /* 0E */ - operator CharacterStatsT() const { - CharacterStatsT ret; + operator CharacterStatsT() const { + CharacterStatsT ret; ret.atp = this->atp.load(); ret.mst = this->mst.load(); ret.evp = this->evp.load(); @@ -41,23 +39,19 @@ using CharacterStatsBE = CharacterStatsT; check_struct_size(CharacterStats, 0x0E); check_struct_size(CharacterStatsBE, 0x0E); -template +template struct PlayerStatsT { - using U16T = typename std::conditional::type; - using U32T = typename std::conditional::type; - using F32T = typename std::conditional::type; - - /* 00 */ CharacterStatsT char_stats; - /* 0E */ U16T esp = 0; - /* 10 */ F32T height = 0.0; - /* 14 */ F32T unknown_a3 = 0.0; - /* 18 */ U32T level = 0; - /* 1C */ U32T experience = 0; - /* 20 */ U32T meseta = 0; + /* 00 */ CharacterStatsT char_stats; + /* 0E */ U16T esp = 0; + /* 10 */ F32T height = 0.0; + /* 14 */ F32T unknown_a3 = 0.0; + /* 18 */ U32T level = 0; + /* 1C */ U32T experience = 0; + /* 20 */ U32T meseta = 0; /* 24 */ - operator PlayerStatsT() const { - PlayerStatsT ret; + operator PlayerStatsT() const { + PlayerStatsT ret; ret.char_stats = this->char_stats; ret.esp = this->esp.load(); ret.height = this->height.load(); @@ -73,10 +67,8 @@ using PlayerStatsBE = PlayerStatsT; check_struct_size(PlayerStats, 0x24); check_struct_size(PlayerStatsBE, 0x24); -template +template struct LevelStatsDeltaT { - using U32T = typename std::conditional::type; - /* 00 */ uint8_t atp; /* 01 */ uint8_t mst; /* 02 */ uint8_t evp; @@ -85,7 +77,7 @@ struct LevelStatsDeltaT { /* 05 */ uint8_t ata; /* 06 */ uint8_t lck; /* 07 */ uint8_t tp; - /* 08 */ U32T experience; + /* 08 */ U32T experience; /* 0C */ void apply(CharacterStats& ps) const { diff --git a/src/Lobby.cc b/src/Lobby.cc index ca3cc0cd..24c0a4ad 100644 --- a/src/Lobby.cc +++ b/src/Lobby.cc @@ -16,7 +16,7 @@ bool Lobby::FloorItem::visible_to_client(uint8_t client_id) const { } Lobby::FloorItemManager::FloorItemManager(uint32_t lobby_id, uint8_t floor) - : log(string_printf("[Lobby:%08" PRIX32 ":FloorItems:%02hhX] ", lobby_id, floor), lobby_log.min_level), + : log(phosg::string_printf("[Lobby:%08" PRIX32 ":FloorItems:%02hhX] ", lobby_id, floor), lobby_log.min_level), next_drop_number(0) {} bool Lobby::FloorItemManager::exists(uint32_t item_id) const { @@ -137,7 +137,7 @@ uint32_t Lobby::FloorItemManager::reassign_all_item_ids(uint32_t next_item_id) { Lobby::Lobby(shared_ptr s, uint32_t id, bool is_game) : server_state(s), - log(string_printf("[%s:%" PRIX32 "] ", is_game ? "Game" : "Lobby", id), lobby_log.min_level), + log(phosg::string_printf("[%s:%" PRIX32 "] ", is_game ? "Game" : "Lobby", id), lobby_log.min_level), lobby_id(id), min_level(0), max_level(0xFFFFFFFF), @@ -151,7 +151,7 @@ Lobby::Lobby(shared_ptr s, uint32_t id, bool is_game) base_exp_multiplier(1), exp_share_multiplier(0.5), challenge_exp_multiplier(1.0f), - random_seed(random_object()), + random_seed(phosg::random_object()), drop_mode(DropMode::CLIENT), event(0), block(0), @@ -325,7 +325,7 @@ shared_ptr Lobby::load_maps( uint32_t random_seed, shared_ptr opt_rand_crypt, const parray& variations, - const PrefixedLogger* log) { + const phosg::PrefixedLogger* log) { auto enemy_filenames = sdt->map_filenames_for_variations(variations, episode, mode, SetDataTable::FilenameType::ENEMIES); auto object_filenames = sdt->map_filenames_for_variations(variations, episode, mode, SetDataTable::FilenameType::OBJECTS); auto event_filenames = sdt->map_filenames_for_variations(variations, episode, mode, SetDataTable::FilenameType::EVENTS); @@ -360,7 +360,7 @@ shared_ptr Lobby::load_maps( shared_ptr rare_rates, uint32_t rare_seed, shared_ptr opt_rand_crypt, - const PrefixedLogger* log) { + const phosg::PrefixedLogger* log) { auto map = make_shared(version, lobby_id, rare_seed, opt_rand_crypt); // Don't load free-roam maps in Challenge mode, since players can't go to @@ -682,7 +682,7 @@ void Lobby::add_client(shared_ptr c, ssize_t required_client_id) { void Lobby::remove_client(shared_ptr c) { if (this->clients.at(c->lobby_client_id) != c) { auto other_c = this->clients[c->lobby_client_id].get(); - throw logic_error(string_printf( + throw logic_error(phosg::string_printf( "client\'s lobby client id (%hhu) does not match client list (%u)", c->lobby_client_id, static_cast(other_c ? other_c->lobby_client_id : 0xFF))); @@ -743,7 +743,7 @@ void Lobby::remove_client(shared_ptr c) { (this->idle_timeout_usecs > 0)) { // If the lobby is persistent but has an idle timeout, make it expire after // the specified time - auto tv = usecs_to_timeval(this->idle_timeout_usecs); + auto tv = phosg::usecs_to_timeval(this->idle_timeout_usecs); event_add(this->idle_timeout_event.get(), &tv); this->log.info("Idle timeout scheduled"); } @@ -1031,7 +1031,7 @@ bool Lobby::compare_shared(const shared_ptr& a, const shared_ptr -Lobby::DropMode enum_for_name(const char* name) { +Lobby::DropMode phosg::enum_for_name(const char* name) { if (!strcmp(name, "DISABLED")) { return Lobby::DropMode::DISABLED; } else if (!strcmp(name, "CLIENT")) { @@ -1048,7 +1048,7 @@ Lobby::DropMode enum_for_name(const char* name) { } template <> -const char* name_for_enum(Lobby::DropMode value) { +const char* phosg::name_for_enum(Lobby::DropMode value) { switch (value) { case Lobby::DropMode::DISABLED: return "DISABLED"; diff --git a/src/Lobby.hh b/src/Lobby.hh index 0c313df7..9d5e3c5f 100644 --- a/src/Lobby.hh +++ b/src/Lobby.hh @@ -40,7 +40,7 @@ struct Lobby : public std::enable_shared_from_this { bool visible_to_client(uint8_t client_id) const; }; struct FloorItemManager { - PrefixedLogger log; + phosg::PrefixedLogger log; uint64_t next_drop_number; // It's important that this is a map and not an unordered_map. See the // comment in send_game_item_state for more details. @@ -92,7 +92,7 @@ struct Lobby : public std::enable_shared_from_this { }; std::weak_ptr server_state; - PrefixedLogger log; + phosg::PrefixedLogger log; uint32_t lobby_id; @@ -231,7 +231,7 @@ struct Lobby : public std::enable_shared_from_this { uint32_t random_seed, std::shared_ptr opt_rand_crypt, const parray& variations, - const PrefixedLogger* log = nullptr); + const phosg::PrefixedLogger* log = nullptr); static std::shared_ptr load_maps( const std::vector& enemy_filenames, const std::vector& object_filenames, @@ -246,7 +246,7 @@ struct Lobby : public std::enable_shared_from_this { std::shared_ptr rare_rates, uint32_t random_seed, std::shared_ptr opt_rand_crypt, - const PrefixedLogger* log = nullptr); + const phosg::PrefixedLogger* log = nullptr); void load_maps(); void create_ep3_server(); @@ -316,6 +316,6 @@ struct Lobby : public std::enable_shared_from_this { }; template <> -Lobby::DropMode enum_for_name(const char* name); +Lobby::DropMode phosg::enum_for_name(const char* name); template <> -const char* name_for_enum(Lobby::DropMode value); +const char* phosg::name_for_enum(Lobby::DropMode value); diff --git a/src/Loggers.cc b/src/Loggers.cc index f492f8bc..09d4ae01 100644 --- a/src/Loggers.cc +++ b/src/Loggers.cc @@ -4,32 +4,32 @@ using namespace std; -PrefixedLogger ax_messages_log("[$ax message] ", LogLevel::USE_DEFAULT); -PrefixedLogger channel_exceptions_log("[Channel] ", LogLevel::USE_DEFAULT); -PrefixedLogger client_log("", LogLevel::USE_DEFAULT); -PrefixedLogger command_data_log("[Commands] ", LogLevel::USE_DEFAULT); -PrefixedLogger config_log("[Config] ", LogLevel::USE_DEFAULT); -PrefixedLogger dns_server_log("[DNSServer] ", LogLevel::USE_DEFAULT); -PrefixedLogger function_compiler_log("[FunctionCompiler] ", LogLevel::USE_DEFAULT); -PrefixedLogger ip_stack_simulator_log("[IPStackSimulator] ", LogLevel::USE_DEFAULT); -PrefixedLogger lobby_log("", LogLevel::USE_DEFAULT); -PrefixedLogger patch_index_log("[PatchFileIndex] ", LogLevel::USE_DEFAULT); -PrefixedLogger player_data_log("", LogLevel::USE_DEFAULT); -PrefixedLogger proxy_server_log("[ProxyServer] ", LogLevel::USE_DEFAULT); -PrefixedLogger replay_log("[ReplaySession] ", LogLevel::USE_DEFAULT); -PrefixedLogger server_log("[Server] ", LogLevel::USE_DEFAULT); -PrefixedLogger static_game_data_log("[StaticGameData] ", LogLevel::USE_DEFAULT); +phosg::PrefixedLogger ax_messages_log("[$ax message] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger channel_exceptions_log("[Channel] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger client_log("", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger command_data_log("[Commands] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger config_log("[Config] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger dns_server_log("[DNSServer] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger function_compiler_log("[FunctionCompiler] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger ip_stack_simulator_log("[IPStackSimulator] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger lobby_log("", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger patch_index_log("[PatchFileIndex] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger player_data_log("", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger proxy_server_log("[ProxyServer] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger replay_log("[ReplaySession] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger server_log("[Server] ", phosg::LogLevel::USE_DEFAULT); +phosg::PrefixedLogger static_game_data_log("[StaticGameData] ", phosg::LogLevel::USE_DEFAULT); static void set_log_level_from_json( - PrefixedLogger& log, const JSON& d, const char* json_key) { + phosg::PrefixedLogger& log, const phosg::JSON& d, const char* json_key) { try { - string name = toupper(d.at(json_key).as_string()); - log.min_level = enum_for_name(name.c_str()); + string name = phosg::toupper(d.at(json_key).as_string()); + log.min_level = phosg::enum_for_name(name.c_str()); } catch (const out_of_range&) { } } -void set_log_levels_from_json(const JSON& json) { +void set_log_levels_from_json(const phosg::JSON& json) { set_log_level_from_json(ax_messages_log, json, "AXMessages"); set_log_level_from_json(channel_exceptions_log, json, "ChannelExceptions"); set_log_level_from_json(client_log, json, "Clients"); diff --git a/src/Loggers.hh b/src/Loggers.hh index 7f8796b3..72eccc47 100644 --- a/src/Loggers.hh +++ b/src/Loggers.hh @@ -3,20 +3,20 @@ #include #include -extern PrefixedLogger ax_messages_log; -extern PrefixedLogger channel_exceptions_log; -extern PrefixedLogger client_log; -extern PrefixedLogger command_data_log; -extern PrefixedLogger config_log; -extern PrefixedLogger dns_server_log; -extern PrefixedLogger function_compiler_log; -extern PrefixedLogger ip_stack_simulator_log; -extern PrefixedLogger lobby_log; -extern PrefixedLogger patch_index_log; -extern PrefixedLogger player_data_log; -extern PrefixedLogger proxy_server_log; -extern PrefixedLogger replay_log; -extern PrefixedLogger server_log; -extern PrefixedLogger static_game_data_log; +extern phosg::PrefixedLogger ax_messages_log; +extern phosg::PrefixedLogger channel_exceptions_log; +extern phosg::PrefixedLogger client_log; +extern phosg::PrefixedLogger command_data_log; +extern phosg::PrefixedLogger config_log; +extern phosg::PrefixedLogger dns_server_log; +extern phosg::PrefixedLogger function_compiler_log; +extern phosg::PrefixedLogger ip_stack_simulator_log; +extern phosg::PrefixedLogger lobby_log; +extern phosg::PrefixedLogger patch_index_log; +extern phosg::PrefixedLogger player_data_log; +extern phosg::PrefixedLogger proxy_server_log; +extern phosg::PrefixedLogger replay_log; +extern phosg::PrefixedLogger server_log; +extern phosg::PrefixedLogger static_game_data_log; -void set_log_levels_from_json(const JSON& json); +void set_log_levels_from_json(const phosg::JSON& json); diff --git a/src/Main.cc b/src/Main.cc index 21de25f9..e6f5e32c 100644 --- a/src/Main.cc +++ b/src/Main.cc @@ -56,13 +56,13 @@ bool use_terminal_colors = false; void print_version_info(); void print_usage(); -std::string get_config_filename(Arguments& args) { +std::string get_config_filename(phosg::Arguments& args) { string config_filename = args.get("config"); return config_filename.empty() ? "system/config.json" : config_filename; } template -vector parse_int_vector(const JSON& o) { +vector parse_int_vector(const phosg::JSON& o) { vector ret; for (const auto& x : o.as_list()) { ret.emplace_back(x->as_int()); @@ -72,32 +72,32 @@ vector parse_int_vector(const JSON& o) { void drop_privileges(const string& username) { if ((getuid() != 0) || (getgid() != 0)) { - throw runtime_error(string_printf( + throw runtime_error(phosg::string_printf( "newserv was not started as root; can\'t switch to user %s", username.c_str())); } struct passwd* pw = getpwnam(username.c_str()); if (!pw) { - string error = string_for_error(errno); - throw runtime_error(string_printf("user %s not found (%s)", + string error = phosg::string_for_error(errno); + throw runtime_error(phosg::string_printf("user %s not found (%s)", username.c_str(), error.c_str())); } if (setgid(pw->pw_gid) != 0) { - string error = string_for_error(errno); - throw runtime_error(string_printf("can\'t switch to group %d (%s)", + string error = phosg::string_for_error(errno); + throw runtime_error(phosg::string_printf("can\'t switch to group %d (%s)", pw->pw_gid, error.c_str())); } if (setuid(pw->pw_uid) != 0) { - string error = string_for_error(errno); - throw runtime_error(string_printf("can\'t switch to user %d (%s)", + string error = phosg::string_for_error(errno); + throw runtime_error(phosg::string_printf("can\'t switch to user %d (%s)", pw->pw_uid, error.c_str())); } config_log.info("Switched to user %s (%d:%d)", username.c_str(), pw->pw_uid, pw->pw_gid); } -Version get_cli_version(Arguments& args, Version default_value = Version::UNKNOWN) { +Version get_cli_version(phosg::Arguments& args, Version default_value = Version::UNKNOWN) { if (args.get("pc-patch")) { return Version::PC_PATCH; } else if (args.get("bb-patch")) { @@ -133,7 +133,7 @@ Version get_cli_version(Arguments& args, Version default_value = Version::UNKNOW } } -Episode get_cli_episode(Arguments& args) { +Episode get_cli_episode(phosg::Arguments& args) { if (args.get("ep1")) { return Episode::EP1; } else if (args.get("ep2")) { @@ -147,7 +147,7 @@ Episode get_cli_episode(Arguments& args) { } } -GameMode get_cli_game_mode(Arguments& args) { +GameMode get_cli_game_mode(phosg::Arguments& args) { if (args.get("battle")) { return GameMode::BATTLE; } else if (args.get("challenge")) { @@ -159,7 +159,7 @@ GameMode get_cli_game_mode(Arguments& args) { } } -uint8_t get_cli_difficulty(Arguments& args) { +uint8_t get_cli_difficulty(phosg::Arguments& args) { if (args.get("hard")) { return 1; } else if (args.get("very-hard")) { @@ -171,17 +171,17 @@ uint8_t get_cli_difficulty(Arguments& args) { } } -string read_input_data(Arguments& args) { +string read_input_data(phosg::Arguments& args) { const string& input_filename = args.get(1, false); string data; if (!input_filename.empty() && (input_filename != "-")) { - data = load_file(input_filename); + data = phosg::load_file(input_filename); } else { - data = read_all(stdin); + data = phosg::read_all(stdin); } if (args.get("parse-data")) { - data = parse_data_string(data, nullptr, ParseDataFlags::ALLOW_FILES); + data = phosg::parse_data_string(data, nullptr, phosg::ParseDataFlags::ALLOW_FILES); } return data; } @@ -190,13 +190,13 @@ bool is_text_extension(const char* extension) { return (!strcmp(extension, "txt") || !strcmp(extension, "json")); } -void write_output_data(Arguments& args, const void* data, size_t size, const char* extension) { +void write_output_data(phosg::Arguments& args, const void* data, size_t size, const char* extension) { const string& input_filename = args.get(1, false); const string& output_filename = args.get(2, false); if (!output_filename.empty() && (output_filename != "-")) { // If the output is to a specified file, write it there - save_file(output_filename, data, size); + phosg::save_file(output_filename, data, size); } else if (output_filename.empty() && (output_filename != "-") && !input_filename.empty() && (input_filename != "-")) { // If no output filename is given and an input filename is given, write to @@ -207,17 +207,17 @@ void write_output_data(Arguments& args, const void* data, size_t size, const cha string filename = input_filename; filename += "."; filename += extension; - save_file(filename, data, size); + phosg::save_file(filename, data, size); } else if (isatty(fileno(stdout)) && (!extension || !is_text_extension(extension))) { // If stdout is a terminal and the data is not known to be text, use // print_data to write the result - print_data(stdout, data, size); + phosg::print_data(stdout, data, size); fflush(stdout); } else { // If stdout is not a terminal, write the data as-is - fwritex(stdout, data, size); + phosg::fwritex(stdout, data, size); fflush(stdout); } } @@ -229,18 +229,18 @@ vector action_order; struct Action { const char* name; const char* help_text; // May be null - function run; + function run; Action( const char* name, const char* help_text, - function run) + function run) : name(name), help_text(help_text), run(run) { auto emplace_ret = all_actions.emplace(this->name, this); if (!emplace_ret.second) { - throw logic_error(string_printf("multiple actions with the same name: %s", this->name)); + throw logic_error(phosg::string_printf("multiple actions with the same name: %s", this->name)); } action_order.emplace_back(this); } @@ -250,7 +250,7 @@ Action a_help( "help", "\ help\n\ You\'re reading it now.\n", - +[](Arguments&) -> void { + +[](phosg::Arguments&) -> void { print_usage(); }); @@ -258,17 +258,17 @@ Action a_version( "version", "\ version\n\ Show newserv\'s revision and build date.\n", - +[](Arguments&) -> void { + +[](phosg::Arguments&) -> void { print_version_info(); }); -static void a_compress_decompress_fn(Arguments& args) { +static void a_compress_decompress_fn(phosg::Arguments& args) { const auto& action = args.get(0); - bool is_prs = ends_with(action, "-prs"); - bool is_bc0 = ends_with(action, "-bc0"); - bool is_pr2 = ends_with(action, "-pr2"); - bool is_prc = ends_with(action, "-prc"); - bool is_decompress = starts_with(action, "decompress-"); + bool is_prs = phosg::ends_with(action, "-prs"); + bool is_bc0 = phosg::ends_with(action, "-bc0"); + bool is_pr2 = phosg::ends_with(action, "-pr2"); + bool is_prc = phosg::ends_with(action, "-prc"); + bool is_decompress = phosg::starts_with(action, "decompress-"); bool is_big_endian = args.get("big-endian"); bool is_optimal = args.get("optimal"); bool is_pessimal = args.get("pessimal"); @@ -293,14 +293,14 @@ static void a_compress_decompress_fn(Arguments& args) { input_progress, input_bytes, progress, output_progress, size_ratio); }; auto optimal_progress_fn = [&](auto phase, size_t input_progress, size_t input_bytes, size_t output_progress) -> void { - const char* phase_name = name_for_enum(phase); + const char* phase_name = phosg::name_for_enum(phase); float progress = static_cast(input_progress * 100) / input_bytes; float size_ratio = static_cast(output_progress * 100) / input_progress; fprintf(stderr, "... [%s] %zu/%zu (%g%%) => %zu (%g%%) \r", phase_name, input_progress, input_bytes, progress, output_progress, size_ratio); }; - uint64_t start = now(); + uint64_t start = phosg::now(); if (!is_decompress && (is_prs || is_pr2 || is_prc)) { if (is_optimal) { data = prs_compress_optimal(data.data(), data.size(), optimal_progress_fn); @@ -324,20 +324,20 @@ static void a_compress_decompress_fn(Arguments& args) { } else { throw logic_error("invalid behavior"); } - uint64_t end = now(); - string time_str = format_duration(end - start); + uint64_t end = phosg::now(); + string time_str = phosg::format_duration(end - start); float size_ratio = static_cast(data.size() * 100) / input_bytes; double bytes_per_sec = input_bytes / (static_cast(end - start) / 1000000.0); - string bytes_per_sec_str = format_size(bytes_per_sec); - log_info("%zu (0x%zX) bytes input => %zu (0x%zX) bytes output (%g%%) in %s (%s / sec)", + string bytes_per_sec_str = phosg::format_size(bytes_per_sec); + phosg::log_info("%zu (0x%zX) bytes input => %zu (0x%zX) bytes output (%g%%) in %s (%s / sec)", input_bytes, input_bytes, data.size(), data.size(), size_ratio, time_str.c_str(), bytes_per_sec_str.c_str()); if (is_pr2 || is_prc) { if (is_decompress && (data.size() != pr2_expected_size)) { - log_warning("Result data size (%zu bytes) does not match expected size from PR2 header (%zu bytes)", data.size(), pr2_expected_size); + phosg::log_warning("Result data size (%zu bytes) does not match expected size from PR2 header (%zu bytes)", data.size(), pr2_expected_size); } else if (!is_decompress) { - uint32_t pr2_seed = seed.empty() ? random_object() : stoul(seed, nullptr, 16); + uint32_t pr2_seed = seed.empty() ? phosg::random_object() : stoul(seed, nullptr, 16); data = is_big_endian ? encrypt_pr2_data(data, input_bytes, pr2_seed) : encrypt_pr2_data(data, input_bytes, pr2_seed); @@ -398,16 +398,16 @@ Action a_prs_size( prs-size [INPUT-FILENAME]\n\ Compute the decompressed size of the PRS-compressed input data, but don\'t\n\ write the decompressed data anywhere.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string data = read_input_data(args); size_t input_bytes = data.size(); size_t output_bytes = prs_decompress_size(data); - log_info("%zu (0x%zX) bytes input => %zu (0x%zX) bytes output", + phosg::log_info("%zu (0x%zX) bytes input => %zu (0x%zX) bytes output", input_bytes, input_bytes, output_bytes, output_bytes); }); Action a_disassemble_prs( - "disassemble-prs", nullptr, +[](Arguments& args) { + "disassemble-prs", nullptr, +[](phosg::Arguments& args) { prs_disassemble(stdout, read_input_data(args)); }); Action a_disassemble_bc0( @@ -417,11 +417,11 @@ Action a_disassemble_bc0( Write a textual representation of the commands contained in a PRS or BC0\n\ command stream. The output is written to stdout. This is mainly useful for\n\ debugging the compressors and decompressors themselves.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { bc0_disassemble(stdout, read_input_data(args)); }); -static void a_encrypt_decrypt_fn(Arguments& args) { +static void a_encrypt_decrypt_fn(phosg::Arguments& args) { bool is_decrypt = (args.get(0) == "decrypt-data"); string seed = args.get("seed"); bool is_big_endian = args.get("big-endian"); @@ -449,8 +449,8 @@ static void a_encrypt_decrypt_fn(Arguments& args) { if (key_name.empty()) { throw runtime_error("the --key option is required for BB"); } - seed = parse_data_string(seed, nullptr, ParseDataFlags::ALLOW_FILES); - auto key = load_object_file("system/blueburst/keys/" + key_name + ".nsk"); + seed = phosg::parse_data_string(seed, nullptr, phosg::ParseDataFlags::ALLOW_FILES); + auto key = phosg::load_object_file("system/blueburst/keys/" + key_name + ".nsk"); crypt = make_shared(key, seed.data(), seed.size()); break; } @@ -466,7 +466,7 @@ static void a_encrypt_decrypt_fn(Arguments& args) { if (is_big_endian) { uint32_t* dwords = reinterpret_cast(data.data()); for (size_t x = 0; x < (data.size() >> 2); x++) { - dwords[x] = bswap32(dwords[x]); + dwords[x] = phosg::bswap32(dwords[x]); } } @@ -479,7 +479,7 @@ static void a_encrypt_decrypt_fn(Arguments& args) { if (is_big_endian) { uint32_t* dwords = reinterpret_cast(data.data()); for (size_t x = 0; x < (data.size() >> 2); x++) { - dwords[x] = bswap32(dwords[x]); + dwords[x] = phosg::bswap32(dwords[x]); } } @@ -503,7 +503,7 @@ Action a_decrypt_data("decrypt-data", "\ file formats.\n", a_encrypt_decrypt_fn); -static void a_encrypt_decrypt_trivial_fn(Arguments& args) { +static void a_encrypt_decrypt_trivial_fn(phosg::Arguments& args) { bool is_decrypt = (args.get(0) == "decrypt-trivial-data"); string seed = args.get("seed"); @@ -552,14 +552,14 @@ Action a_decrypt_trivial_data("decrypt-trivial-data", "\ a_encrypt_decrypt_trivial_fn); Action a_decrypt_registry_value( - "decrypt-registry-value", nullptr, +[](Arguments& args) { + "decrypt-registry-value", nullptr, +[](phosg::Arguments& args) { string data = read_input_data(args); string out_data = decrypt_v2_registry_value(data.data(), data.size()); write_output_data(args, out_data.data(), out_data.size(), "dec"); }); Action a_encrypt_challenge_data( - "encrypt-challenge-data", nullptr, +[](Arguments& args) { + "encrypt-challenge-data", nullptr, +[](phosg::Arguments& args) { string data = read_input_data(args); encrypt_challenge_rank_text_t(data.data(), data.size()); write_output_data(args, data.data(), data.size(), "dec"); @@ -569,23 +569,23 @@ Action a_decrypt_challenge_data( encrypt-challenge-data [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ decrypt-challenge-data [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Encrypt or decrypt data using the challenge mode trivial algorithm.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string data = read_input_data(args); decrypt_challenge_rank_text_t(data.data(), data.size()); write_output_data(args, data.data(), data.size(), "dec"); }); -static void a_encrypt_decrypt_gci_save_fn(Arguments& args) { +static void a_encrypt_decrypt_gci_save_fn(phosg::Arguments& args) { bool is_decrypt = (args.get(0) == "decrypt-gci-save"); bool skip_checksum = args.get("skip-checksum"); string seed = args.get("seed"); string system_filename = args.get("sys"); - int64_t override_round2_seed = args.get("round2-seed", -1, Arguments::IntFormat::HEX); + int64_t override_round2_seed = args.get("round2-seed", -1, phosg::Arguments::IntFormat::HEX); uint32_t round1_seed; if (!system_filename.empty()) { - string system_data = load_file(system_filename); - StringReader r(system_data); + string system_data = phosg::load_file(system_filename); + phosg::StringReader r(system_data); const auto& header = r.get(); header.check(); const auto& system = r.get(); @@ -597,7 +597,7 @@ static void a_encrypt_decrypt_gci_save_fn(Arguments& args) { } auto data = read_input_data(args); - StringReader r(data); + phosg::StringReader r(data); const auto& header = r.get(); header.check(); @@ -627,7 +627,7 @@ static void a_encrypt_decrypt_gci_save_fn(Arguments& args) { auto* charfile = reinterpret_cast(data.data() + data_start_offset); if (!is_decrypt) { for (size_t z = 0; z < charfile->characters.size(); z++) { - charfile->characters[z].ep3_config.encrypt(random_object()); + charfile->characters[z].ep3_config.encrypt(phosg::random_object()); } } process_file.template operator()(); @@ -654,11 +654,11 @@ Action a_encrypt_gci_save("encrypt-gci-save", "\ --seed=ROUND1-SEED (specified as a 32-bit hexadecimal number).\n", a_encrypt_decrypt_gci_save_fn); -static void a_encrypt_decrypt_pc_save_fn(Arguments& args) { +static void a_encrypt_decrypt_pc_save_fn(phosg::Arguments& args) { bool is_decrypt = (args.get(0) == "decrypt-pc-save"); bool skip_checksum = args.get("skip-checksum"); string seed = args.get("seed"); - int64_t override_round2_seed = args.get("round2-seed", -1, Arguments::IntFormat::HEX); + int64_t override_round2_seed = args.get("round2-seed", -1, phosg::Arguments::IntFormat::HEX); if (seed.empty()) { throw runtime_error("--seed must be given to specify the serial number"); @@ -720,12 +720,12 @@ Action a_encrypt_pc_save("encrypt-pc-save", "\ associated with the save file, as a 32-bit hexadecimal integer.\n", a_encrypt_decrypt_pc_save_fn); -static void a_encrypt_decrypt_save_data_fn(Arguments& args) { +static void a_encrypt_decrypt_save_data_fn(phosg::Arguments& args) { bool is_decrypt = (args.get(0) == "decrypt-save-data"); bool skip_checksum = args.get("skip-checksum"); bool is_big_endian = args.get("big-endian"); string seed = args.get("seed"); - int64_t override_round2_seed = args.get("round2-seed", -1, Arguments::IntFormat::HEX); + int64_t override_round2_seed = args.get("round2-seed", -1, phosg::Arguments::IntFormat::HEX); size_t bytes = args.get("bytes", 0); if (seed.empty()) { @@ -734,7 +734,7 @@ static void a_encrypt_decrypt_save_data_fn(Arguments& args) { uint32_t round1_seed = stoul(seed, nullptr, 16); auto data = read_input_data(args); - StringReader r(data); + phosg::StringReader r(data); string output_data; size_t effective_size = bytes ? min(bytes, data.size()) : data.size(); @@ -766,9 +766,9 @@ Action a_decrypt_dcv2_executable( community modifications of the game. In this case, --seed is not required;\n\ if not given, finds the seed automatically, and prints it to stderr so you\n\ will be able to use it when re-encrypting.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string executable_filename = args.get("executable", true); - string executable_data = load_file(executable_filename); + string executable_data = phosg::load_file(executable_filename); string decrypted; if (args.get("simple")) { string seed_str = args.get("seed"); @@ -777,11 +777,11 @@ Action a_decrypt_dcv2_executable( } else { string values_filename = args.get("values", true); string indexes_filename = args.get("indexes", true); - string values_data = load_file(values_filename); - string indexes_data = load_file(indexes_filename); + string values_data = phosg::load_file(values_filename); + string indexes_data = phosg::load_file(indexes_filename); decrypted = decrypt_dp_address_jpn(executable_data, values_data, indexes_data); } - save_file(executable_filename + ".dec", decrypted); + phosg::save_file(executable_filename + ".dec", decrypted); }); Action a_encrypt_dcv2_executable( "encrypt-dcv2-executable", "\ @@ -793,43 +793,43 @@ Action a_encrypt_dcv2_executable( INDEXES.enc.\n\ If --simple is given, uses the simpler encryption method used in some\n\ community modifications of the game. In this case, --seed is required.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string executable_filename = args.get("executable", true); - string executable_data = load_file(executable_filename); + string executable_data = phosg::load_file(executable_filename); string encrypted_executable; if (args.get("simple")) { int64_t seed = stoull(args.get("seed", true), nullptr, 16); encrypted_executable = crypt_dp_address_jpn_simple(executable_data, seed); } else { string indexes_filename = args.get("indexes", true); - string indexes_data = load_file(indexes_filename); + string indexes_data = phosg::load_file(indexes_filename); auto encrypted = encrypt_dp_address_jpn(executable_data, indexes_data); - save_file(indexes_filename + ".enc", encrypted.indexes); + phosg::save_file(indexes_filename + ".enc", encrypted.indexes); encrypted_executable = std::move(encrypted.executable); } - save_file(executable_filename + ".enc", encrypted_executable); + phosg::save_file(executable_filename + ".enc", encrypted_executable); }); Action a_decode_gci_snapshot( "decode-gci-snapshot", "\ decode-gci-snapshot [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Decode a PSO GC snapshot file into a Windows BMP image.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto data = read_input_data(args); - StringReader r(data); + phosg::StringReader r(data); const auto& header = r.get(); try { header.check(); } catch (const exception& e) { - log_warning("File header failed validation (%s)", e.what()); + phosg::log_warning("File header failed validation (%s)", e.what()); } const auto& file = r.get(); if (!file.checksum_correct()) { - log_warning("File internal checksum is incorrect"); + phosg::log_warning("File internal checksum is incorrect"); } auto img = file.decode_image(); - string saved = img.save(Image::Format::WINDOWS_BITMAP); + string saved = img.save(phosg::Image::Format::WINDOWS_BITMAP); write_output_data(args, saved.data(), saved.size(), "bmp"); }); @@ -838,13 +838,13 @@ Action a_encode_gvm( encode-gvm [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Encode an image in BMP or PPM/PNM format into a GVM texture. The resulting\n\ GVM file can be used as an Episode 3 lobby banner.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const string& input_filename = args.get(1, false); - Image img; + phosg::Image img; if (!input_filename.empty() && (input_filename != "-")) { - img = Image(input_filename); + img = phosg::Image(input_filename); } else { - img = Image(stdin); + img = phosg::Image(stdin); } string encoded = encode_gvm(img, img.get_has_alpha() ? GVRDataFormat::RGB5A3 : GVRDataFormat::RGB565, "image.gvr", 0); write_output_data(args, encoded.data(), encoded.size(), "gvm"); @@ -856,7 +856,7 @@ Action a_salvage_gci( Attempt to find either the round-1 or round-2 decryption seed for a\n\ corrupted GCI file. If --round2 is given, then CRYPT-OPTION must be given\n\ (and should specify either a valid system file or the round1 seed).\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { bool round2 = args.get("round2"); string seed = args.get("seed"); string system_filename = args.get("sys"); @@ -868,19 +868,19 @@ Action a_salvage_gci( uint64_t likely_round1_seed = 0xFFFFFFFFFFFFFFFF; if (!system_filename.empty()) { try { - string system_data = load_file(system_filename); - StringReader r(system_data); + string system_data = phosg::load_file(system_filename); + phosg::StringReader r(system_data); const auto& header = r.get(); header.check(); const auto& system = r.get(); likely_round1_seed = system.creation_timestamp; - log_info("System file appears to be in order; round1 seed is %08" PRIX64, likely_round1_seed); + phosg::log_info("System file appears to be in order; round1 seed is %08" PRIX64, likely_round1_seed); } catch (const exception& e) { - log_warning("Cannot parse system file (%s); ignoring it", e.what()); + phosg::log_warning("Cannot parse system file (%s); ignoring it", e.what()); } } else if (!seed.empty()) { likely_round1_seed = stoul(seed, nullptr, 16); - log_info("Specified round1 seed is %08" PRIX64, likely_round1_seed); + phosg::log_info("Specified round1 seed is %08" PRIX64, likely_round1_seed); } if (round2 && likely_round1_seed > 0x100000000) { @@ -888,7 +888,7 @@ Action a_salvage_gci( } auto data = read_input_data(args); - StringReader r(data); + phosg::StringReader r(data); const auto& header = r.get(); header.check(); @@ -897,13 +897,13 @@ Action a_salvage_gci( auto process_file = [&]() { vector> top_seeds_by_thread( num_threads ? num_threads : thread::hardware_concurrency()); - parallel_range( + phosg::parallel_range( [&](uint64_t seed, size_t thread_num) -> bool { size_t zero_count; if (round2) { string decrypted = decrypt_gci_fixed_size_data_section_for_salvage( data_section, header.data_size, likely_round1_seed, seed, bytes); - zero_count = count_zeroes( + zero_count = phosg::count_zeroes( decrypted.data() + offset, decrypted.size() - offset, stride); @@ -913,7 +913,7 @@ Action a_salvage_gci( header.data_size, seed, true); - zero_count = count_zeroes( + zero_count = phosg::count_zeroes( reinterpret_cast(&decrypted) + offset, sizeof(decrypted) - offset, stride); @@ -941,7 +941,7 @@ Action a_salvage_gci( const char* sys_seed_str = (!round2 && (it.second == likely_round1_seed)) ? " (this is the seed from the system file)" : ""; - log_info("Round %c seed %08" PRIX32 " resulted in %zu zero bytes%s", + phosg::log_info("Round %c seed %08" PRIX32 " resulted in %zu zero bytes%s", round2 ? '2' : '1', it.second, it.first, sys_seed_str); } }; @@ -970,7 +970,7 @@ Action a_find_decryption_seed( function.) By default, the number of worker threads is equal to the number\n\ of CPU cores in the system, but this can be overridden with the\n\ --threads=NUM-THREADS option.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const auto& plaintexts_ascii = args.get_multi("decrypted"); const auto& ciphertext_ascii = args.get("encrypted"); auto version = get_cli_version(args); @@ -988,14 +988,14 @@ Action a_find_decryption_seed( vector> plaintexts; for (const auto& plaintext_ascii : plaintexts_ascii) { string mask; - string data = parse_data_string(plaintext_ascii, &mask, ParseDataFlags::ALLOW_FILES); + string data = phosg::parse_data_string(plaintext_ascii, &mask, phosg::ParseDataFlags::ALLOW_FILES); if (data.size() != mask.size()) { throw logic_error("plaintext and mask are not the same size"); } max_plaintext_size = max(max_plaintext_size, data.size()); plaintexts.emplace_back(std::move(data), std::move(mask)); } - string ciphertext = parse_data_string(ciphertext_ascii, nullptr, ParseDataFlags::ALLOW_FILES); + string ciphertext = phosg::parse_data_string(ciphertext_ascii, nullptr, phosg::ParseDataFlags::ALLOW_FILES); auto mask_match = +[](const void* a, const void* b, const void* m, size_t size) -> bool { const uint8_t* a8 = reinterpret_cast(a); @@ -1009,7 +1009,7 @@ Action a_find_decryption_seed( return true; }; - uint64_t seed = parallel_range([&](uint64_t seed, size_t) -> bool { + uint64_t seed = phosg::parallel_range([&](uint64_t seed, size_t) -> bool { string be_decrypt_buf = ciphertext.substr(0, max_plaintext_size); string le_decrypt_buf = ciphertext.substr(0, max_plaintext_size); if (uses_v3_encryption(version)) { @@ -1041,14 +1041,14 @@ Action a_find_decryption_seed( 0, 0x100000000, num_threads); if (seed < 0x100000000) { - log_info("Found seed %08" PRIX64, seed); + phosg::log_info("Found seed %08" PRIX64, seed); } else { - log_error("No seed found"); + phosg::log_error("No seed found"); } }); Action a_decode_gci( - "decode-gci", nullptr, +[](Arguments& args) { + "decode-gci", nullptr, +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw invalid_argument("an input filename is required"); @@ -1058,10 +1058,10 @@ Action a_decode_gci( bool skip_checksum = args.get("skip-checksum"); int64_t dec_seed = seed.empty() ? -1 : stoul(seed, nullptr, 16); auto decoded = decode_gci_data(read_input_data(args), num_threads, dec_seed, skip_checksum); - save_file(input_filename + ".dec", decoded); + phosg::save_file(input_filename + ".dec", decoded); }); Action a_decode_vms( - "decode-vms", nullptr, +[](Arguments& args) { + "decode-vms", nullptr, +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw invalid_argument("an input filename is required"); @@ -1071,16 +1071,16 @@ Action a_decode_vms( bool skip_checksum = args.get("skip-checksum"); int64_t dec_seed = seed.empty() ? -1 : stoul(seed, nullptr, 16); auto decoded = decode_vms_data(read_input_data(args), num_threads, dec_seed, skip_checksum); - save_file(input_filename + ".dec", decoded); + phosg::save_file(input_filename + ".dec", decoded); }); Action a_decode_dlq( - "decode-dlq", nullptr, +[](Arguments& args) { + "decode-dlq", nullptr, +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw invalid_argument("an input filename is required"); } auto decoded = decode_dlq_data(read_input_data(args)); - save_file(input_filename + ".dec", decoded); + phosg::save_file(input_filename + ".dec", decoded); }); Action a_decode_qst( "decode-qst", "\ @@ -1099,14 +1099,14 @@ Action a_decode_qst( GCI or VMS file, use the --seed=SEED option and give the serial number (as\n\ a hex-encoded 32-bit integer). If you don\'t know the serial number,\n\ newserv will find it via a brute-force search, which will take a long time.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw invalid_argument("an input filename is required"); } auto files = decode_qst_data(read_input_data(args)); for (const auto& it : files) { - save_file(input_filename + "-" + it.first, it.second); + phosg::save_file(input_filename + "-" + it.first, it.second); } }); @@ -1117,7 +1117,7 @@ Action a_encode_qst( --download is given, generates a download .qst instead of an online .qst.\n\ Specify the quest\'s game version with one of the --dc-nte, --dc-v1,\n\ --dc-v2, --pc, --gc-nte, --gc, --gc-ep3, --xb, or --bb options.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw invalid_argument("an input filename is required"); @@ -1126,18 +1126,18 @@ Action a_encode_qst( bool download = args.get("download"); string bin_filename = input_filename; - string dat_filename = ends_with(bin_filename, ".bin") + string dat_filename = phosg::ends_with(bin_filename, ".bin") ? (bin_filename.substr(0, bin_filename.size() - 3) + "dat") : (bin_filename + ".dat"); - string pvr_filename = ends_with(bin_filename, ".bin") + string pvr_filename = phosg::ends_with(bin_filename, ".bin") ? (bin_filename.substr(0, bin_filename.size() - 3) + "pvr") : (bin_filename + ".pvr"); - auto bin_data = make_shared(load_file(bin_filename)); - auto dat_data = make_shared(load_file(dat_filename)); + auto bin_data = make_shared(phosg::load_file(bin_filename)); + auto dat_data = make_shared(phosg::load_file(dat_filename)); shared_ptr pvr_data; try { - pvr_data = make_shared(load_file(pvr_filename)); - } catch (const cannot_open_file&) { + pvr_data = make_shared(phosg::load_file(pvr_filename)); + } catch (const phosg::cannot_open_file&) { } auto vq = make_shared(0, 0, version, 0, bin_data, dat_data, pvr_data); if (download) { @@ -1157,7 +1157,7 @@ Action a_disassemble_quest_script( --xb, or --bb options. If you intend to edit and reassemble the script, use\n\ the --reassembly option to add explicit label numbers and remove offsets\n\ and data in code sections.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string data = read_input_data(args); auto version = get_cli_version(args); if (!args.get("decompressed")) { @@ -1173,7 +1173,7 @@ Action a_disassemble_quest_map( disassemble-quest-map [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Disassemble the input quest map (.dat file) into a text representation of\n\ the data it contains.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string data = read_input_data(args); if (!args.get("decompressed")) { data = prs_decompress(data); @@ -1190,11 +1190,11 @@ Action a_disassemble_free_map( compressed, use the --compressed option. Also unlike other options, the\n\ input must be from a file (that is, INPUT-FILENAME is required and cannot\n\ be \"-\").\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const string& input_filename = args.get(1, true); - bool is_events = ends_with(input_filename, ".evt"); - bool is_enemies = ends_with(input_filename, "e.dat") || ends_with(input_filename, "e_s.dat") || ends_with(input_filename, "e_c1.dat") || ends_with(input_filename, "e_d.dat"); - bool is_objects = ends_with(input_filename, "o.dat") || ends_with(input_filename, "o_s.dat") || ends_with(input_filename, "o_c1.dat") || ends_with(input_filename, "o_d.dat"); + bool is_events = phosg::ends_with(input_filename, ".evt"); + bool is_enemies = phosg::ends_with(input_filename, "e.dat") || phosg::ends_with(input_filename, "e_s.dat") || phosg::ends_with(input_filename, "e_c1.dat") || phosg::ends_with(input_filename, "e_d.dat"); + bool is_objects = phosg::ends_with(input_filename, "o.dat") || phosg::ends_with(input_filename, "o_s.dat") || phosg::ends_with(input_filename, "o_c1.dat") || phosg::ends_with(input_filename, "o_d.dat"); if (!is_objects && !is_enemies && !is_events) { throw runtime_error("cannot determine input file type"); } @@ -1222,7 +1222,7 @@ Action a_disassemble_set_data_table( "disassemble-set-data-table", "\ disassemble-set-data-table [INPUT-FILENAME]\n\ Show the contents of a SetDataTable.rel file. A version option is required.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { Version version = get_cli_version(args); SetDataTable sdt(version, read_input_data(args)); string str = sdt.str(); @@ -1235,12 +1235,12 @@ Action a_assemble_quest_script( Assemble the input quest script (.txt file) into a compressed .bin file\n\ usable as an online quest script. If --decompressed is given, produces an\n\ uncompressed .bind file instead.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string text = read_input_data(args); const string& input_filename = args.get(1, false); string include_dir = (!input_filename.empty() && (input_filename != "-")) - ? dirname(input_filename) + ? phosg::dirname(input_filename) : "."; string result = assemble_quest_script(text, include_dir); @@ -1258,7 +1258,7 @@ Action a_assemble_all_patches( two compiled .bin files for each patch (one unencrypted, for most PSO\n\ versions, and one encrypted, for PSO GC JP v1.4, JP Ep3, and Ep3 Trial\n\ Edition). The output files are saved in system/client-functions.\n", - +[](Arguments&) { + +[](phosg::Arguments&) { auto fci = make_shared("system/client-functions"); auto process_code = +[](shared_ptr code, @@ -1266,13 +1266,13 @@ Action a_assemble_all_patches( uint32_t checksum_size, uint32_t override_start_addr) -> void { for (uint8_t encrypted = 0; encrypted < 2; encrypted++) { - StringWriter w; + phosg::StringWriter w; string data = prepare_send_function_call_data( code, {}, nullptr, 0, checksum_addr, checksum_size, override_start_addr, encrypted); w.put(PSOCommandHeaderDCV3{.command = 0xB2, .flag = code->index, .size = data.size() + 4}); w.write(data); string out_path = code->source_path + (encrypted ? ".enc.bin" : ".std.bin"); - save_file(out_path, w.str()); + phosg::save_file(out_path, w.str()); fprintf(stderr, "... %s\n", out_path.c_str()); } }; @@ -1302,7 +1302,7 @@ Action a_assemble_all_patches( } }); -void a_extract_archive_fn(Arguments& args) { +void a_extract_archive_fn(phosg::Arguments& args) { string output_prefix = args.get(2, false); if (output_prefix == "-") { throw invalid_argument("output prefix cannot be stdout"); @@ -1322,8 +1322,8 @@ void a_extract_archive_fn(Arguments& args) { const auto& all_entries = arch.all_entries(); for (size_t z = 0; z < all_entries.size(); z++) { auto e = arch.get(z); - string out_file = string_printf("%s-%zu", output_prefix.c_str(), z); - save_file(out_file.c_str(), e.first, e.second); + string out_file = phosg::string_printf("%s-%zu", output_prefix.c_str(), z); + phosg::save_file(out_file.c_str(), e.first, e.second); fprintf(stderr, "... %s\n", out_file.c_str()); } } else if (args.get(0) == "extract-gsl") { @@ -1331,7 +1331,7 @@ void a_extract_archive_fn(Arguments& args) { for (const auto& entry_it : arch.all_entries()) { auto e = arch.get(entry_it.first); string out_file = output_prefix + entry_it.first; - save_file(out_file.c_str(), e.first, e.second); + phosg::save_file(out_file.c_str(), e.first, e.second); fprintf(stderr, "... %s\n", out_file.c_str()); } } else if (args.get(0) == "extract-bml") { @@ -1341,7 +1341,7 @@ void a_extract_archive_fn(Arguments& args) { auto e = arch.get(entry_it.first); string data = prs_decompress(e.first, e.second); string out_file = output_prefix + entry_it.first; - save_file(out_file, data); + phosg::save_file(out_file, data); fprintf(stderr, "... %s\n", out_file.c_str()); } @@ -1349,7 +1349,7 @@ void a_extract_archive_fn(Arguments& args) { if (gvm_e.second) { string data = prs_decompress(gvm_e.first, gvm_e.second); string out_file = output_prefix + entry_it.first + ".gvm"; - save_file(out_file, data); + phosg::save_file(out_file, data); fprintf(stderr, "... %s\n", out_file.c_str()); } } @@ -1373,13 +1373,13 @@ Action a_extract_bml("extract-bml", "\ a_extract_archive_fn); Action a_encode_sjis( - "encode-sjis", nullptr, +[](Arguments& args) { + "encode-sjis", nullptr, +[](phosg::Arguments& args) { string data = read_input_data(args); string result = tt_utf8_to_sega_sjis(data); write_output_data(args, result.data(), result.size(), "txt"); }); Action a_decode_sjis( - "decode-sjis", nullptr, +[](Arguments& args) { + "decode-sjis", nullptr, +[](phosg::Arguments& args) { string data = read_input_data(args); string result = tt_sega_sjis_to_utf8(data); write_output_data(args, result.data(), result.size(), "txt"); @@ -1391,7 +1391,7 @@ Action a_decode_text_archive( Decode a text archive to JSON. --collections=NUM_COLLECTIONS is given,\n\ expects a fixed number of collections in the input. If --has-pr3 is given,\n\ expects the input not to have a REL footer.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string data = read_input_data(args); bool is_sjis = args.get("japanese"); @@ -1402,48 +1402,48 @@ Action a_decode_text_archive( } else { ts = make_unique(data, args.get("big-endian"), is_sjis); } - JSON j = ts->json(); - string out_data = j.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::ESCAPE_CONTROLS_ONLY); + phosg::JSON j = ts->json(); + string out_data = j.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::ESCAPE_CONTROLS_ONLY); write_output_data(args, out_data.data(), out_data.size(), "json"); }); Action a_encode_text_archive( "encode-text-archive", "\ encode-text-archive [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Encode a text archive. Currently only supports GC and Xbox format.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const string& input_filename = args.get(1, false); const string& output_filename = args.get(2, false); bool is_sjis = args.get("japanese"); - auto json = JSON::parse(read_input_data(args)); + auto json = phosg::JSON::parse(read_input_data(args)); BinaryTextAndKeyboardsSet a(json); auto result = a.serialize(args.get("big-endian"), is_sjis); if (output_filename.empty()) { if (input_filename.empty() || (input_filename == "-")) { throw runtime_error("encoded text archive cannot be written to stdout"); } - save_file(string_printf("%s.pr2", input_filename.c_str()), result.first); - save_file(string_printf("%s.pr3", input_filename.c_str()), result.second); + phosg::save_file(phosg::string_printf("%s.pr2", input_filename.c_str()), result.first); + phosg::save_file(phosg::string_printf("%s.pr3", input_filename.c_str()), result.second); } else if (output_filename == "-") { throw runtime_error("encoded text archive cannot be written to stdout"); } else { string out_filename = output_filename; - if (ends_with(out_filename, ".pr2")) { - save_file(out_filename, result.first); + if (phosg::ends_with(out_filename, ".pr2")) { + phosg::save_file(out_filename, result.first); out_filename[out_filename.size() - 1] = '3'; - save_file(out_filename, result.second); + phosg::save_file(out_filename, result.second); } else { - save_file(out_filename + ".pr2", result.first); - save_file(out_filename + ".pr3", result.second); + phosg::save_file(out_filename + ".pr2", result.first); + phosg::save_file(out_filename + ".pr3", result.second); } } }); Action a_decode_unicode_text_set( - "decode-unicode-text-set", nullptr, +[](Arguments& args) { + "decode-unicode-text-set", nullptr, +[](phosg::Arguments& args) { UnicodeTextSet uts(read_input_data(args)); - JSON j = uts.json(); - string out_data = j.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::ESCAPE_CONTROLS_ONLY); + phosg::JSON j = uts.json(); + string out_data = j.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::ESCAPE_CONTROLS_ONLY); write_output_data(args, out_data.data(), out_data.size(), "json"); }); Action a_encode_unicode_text_set( @@ -1452,8 +1452,8 @@ Action a_encode_unicode_text_set( encode-unicode-text-set [INPUT-FILENAME [OUTPUT-FILENAME]]\n\ Decode a Unicode text set (e.g. unitxt_e.prs) to JSON for easy editing, or\n\ encode a JSON file to a Unicode text set.\n", - +[](Arguments& args) { - UnicodeTextSet uts(JSON::parse(read_input_data(args))); + +[](phosg::Arguments& args) { + UnicodeTextSet uts(phosg::JSON::parse(read_input_data(args))); string encoded = uts.serialize(); write_output_data(args, encoded.data(), encoded.size(), "prs"); }); @@ -1466,17 +1466,17 @@ Action a_decode_word_select_set( --unitxt option is also required, and must point to a unitxt file in prs\n\ or JSON format. For PC (V2), the unitxt_e.prs file should be used; for BB,\n\ the unitxt_ws_e.prs file should be used.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto version = get_cli_version(args); string unitxt_filename = args.get("unitxt"); const vector* unitxt_collection; if (!unitxt_filename.empty()) { unique_ptr uts; - if (ends_with(unitxt_filename, ".prs")) { - uts = make_unique(load_file(unitxt_filename)); - } else if (ends_with(unitxt_filename, ".json")) { - uts = make_unique(JSON::parse(load_file(unitxt_filename))); + if (phosg::ends_with(unitxt_filename, ".prs")) { + uts = make_unique(phosg::load_file(unitxt_filename)); + } else if (phosg::ends_with(unitxt_filename, ".json")) { + uts = make_unique(phosg::JSON::parse(phosg::load_file(unitxt_filename))); } else { throw runtime_error("unitxt filename must end in .prs or .json"); } @@ -1494,7 +1494,7 @@ Action a_print_word_select_table( Print the Word Select token translation table. If a version option is\n\ given, prints the table sorted by token ID for that version. If no version\n\ option is given, prints the token table sorted by canonical name.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto s = make_shared(get_config_filename(args)); s->load_patch_indexes(false); s->load_text_index(false); @@ -1522,7 +1522,7 @@ Action a_cat_client( --gc, and --bb options can be used to select the command format and\n\ encryption. If --bb is used, the --key=KEY-NAME option is also required (as\n\ in decrypt-data above).\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto version = get_cli_version(args); shared_ptr key; if (uses_v4_encryption(version)) { @@ -1531,10 +1531,10 @@ Action a_cat_client( throw runtime_error("a key filename is required for BB client emulation"); } key = make_shared( - load_object_file("system/blueburst/keys/" + key_file_name + ".nsk")); + phosg::load_object_file("system/blueburst/keys/" + key_file_name + ".nsk")); } shared_ptr base(event_base_new(), event_base_free); - auto cat_client_remote = make_sockaddr_storage(parse_netloc(args.get(1))).first; + auto cat_client_remote = phosg::make_sockaddr_storage(phosg::parse_netloc(args.get(1))).first; CatSession session(base, cat_client_remote, get_cli_version(args), key); event_base_dispatch(base.get()); }); @@ -1553,7 +1553,7 @@ Action a_convert_rare_item_set( .rel (Schtserv rare table; cannot be used in output filename)\n\ If the --multiply=X option is given, multiplies all drop rates by X (given\n\ as a decimal value).\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto version = get_cli_version(args); double rate_factor = args.get("multiply", 1.0); @@ -1571,15 +1571,15 @@ Action a_convert_rare_item_set( auto data = make_shared(read_input_data(args)); shared_ptr rs; - if (ends_with(input_filename, ".json")) { - rs = make_shared(JSON::parse(*data), s->item_name_index(version)); - } else if (ends_with(input_filename, ".gsl")) { + if (phosg::ends_with(input_filename, ".json")) { + rs = make_shared(phosg::JSON::parse(*data), s->item_name_index(version)); + } else if (phosg::ends_with(input_filename, ".gsl")) { rs = make_shared(GSLArchive(data, false), false); - } else if (ends_with(input_filename, ".gslb")) { + } else if (phosg::ends_with(input_filename, ".gslb")) { rs = make_shared(GSLArchive(data, true), true); - } else if (ends_with(input_filename, ".afs")) { + } else if (phosg::ends_with(input_filename, ".afs")) { rs = make_shared(AFSArchive(data), is_v1(version)); - } else if (ends_with(input_filename, ".rel")) { + } else if (phosg::ends_with(input_filename, ".rel")) { rs = make_shared(*data, true); } else { throw runtime_error("cannot determine input format; use a filename ending with .json, .gsl, .gslb, .afs, or .rel"); @@ -1592,17 +1592,17 @@ Action a_convert_rare_item_set( string output_filename = args.get(2, false); if (output_filename.empty() || (output_filename == "-")) { rs->print_all_collections(stdout, s->item_name_index(version)); - } else if (ends_with(output_filename, ".json")) { + } else if (phosg::ends_with(output_filename, ".json")) { auto json = rs->json(s->item_name_index(version)); - string data = json.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::HEX_INTEGERS | JSON::SerializeOption::SORT_DICT_KEYS); + string data = json.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS | phosg::JSON::SerializeOption::SORT_DICT_KEYS); write_output_data(args, data.data(), data.size(), nullptr); - } else if (ends_with(output_filename, ".gsl")) { + } else if (phosg::ends_with(output_filename, ".gsl")) { string data = rs->serialize_gsl(args.get("big-endian")); write_output_data(args, data.data(), data.size(), nullptr); - } else if (ends_with(output_filename, ".gslb")) { + } else if (phosg::ends_with(output_filename, ".gslb")) { string data = rs->serialize_gsl(true); write_output_data(args, data.data(), data.size(), nullptr); - } else if (ends_with(output_filename, ".afs")) { + } else if (phosg::ends_with(output_filename, ".afs")) { bool is_v1 = ::is_v1(get_cli_version(args, Version::GC_V3)); string data = rs->serialize_afs(is_v1); write_output_data(args, data.data(), data.size(), nullptr); @@ -1619,7 +1619,7 @@ Action a_convert_common_item_set( .json (newserv JSON common item table)\n\ .gsl (PSO BB little-endian GSL archive)\n\ .gslb (PSO GC big-endian GSL archive)\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string input_filename = args.get(1, false); if (input_filename.empty() || (input_filename == "-")) { throw runtime_error("input filename must be given"); @@ -1627,11 +1627,11 @@ Action a_convert_common_item_set( auto data = make_shared(read_input_data(args)); shared_ptr cs; - if (ends_with(input_filename, ".json")) { - cs = make_shared(JSON::parse(*data)); - } else if (ends_with(input_filename, ".gsl")) { + if (phosg::ends_with(input_filename, ".json")) { + cs = make_shared(phosg::JSON::parse(*data)); + } else if (phosg::ends_with(input_filename, ".gsl")) { cs = make_shared(data, args.get("big-endian")); - } else if (ends_with(input_filename, ".gslb")) { + } else if (phosg::ends_with(input_filename, ".gslb")) { cs = make_shared(data, true); } else { throw runtime_error("cannot determine input format; use a filename ending with .json, .gsl, .gslb, or .afs"); @@ -1642,7 +1642,7 @@ Action a_convert_common_item_set( cs->print(stdout); } else { auto json = cs->json(); - string json_data = json.serialize(JSON::SerializeOption::FORMAT | JSON::SerializeOption::HEX_INTEGERS | JSON::SerializeOption::SORT_DICT_KEYS); + string json_data = json.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS | phosg::JSON::SerializeOption::SORT_DICT_KEYS); write_output_data(args, json_data.data(), json_data.size(), "json"); } }); @@ -1653,7 +1653,7 @@ Action a_describe_item( Describe an item. The argument may be the item\'s raw hex code or a textual\n\ description of the item. If the description contains spaces, it must be\n\ quoted, such as \"L&K14 COMBAT +10 0/10/15/0/35\".\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { string description = args.get(1); auto version = get_cli_version(args); @@ -1674,7 +1674,7 @@ Action a_describe_item( string desc = name_index->describe_item(item); string desc_colored = name_index->describe_item(item, true); - log_info("Data (decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", + phosg::log_info("Data (decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", item.data1[0], item.data1[1], item.data1[2], item.data1[3], item.data1[4], item.data1[5], item.data1[6], item.data1[7], item.data1[8], item.data1[9], item.data1[10], item.data1[11], @@ -1685,14 +1685,14 @@ Action a_describe_item( ItemData item_v2_decoded = item_v2; item_v2_decoded.decode_for_version(Version::PC_V2); - log_info("Data (V2-encoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", + phosg::log_info("Data (V2-encoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", item_v2.data1[0], item_v2.data1[1], item_v2.data1[2], item_v2.data1[3], item_v2.data1[4], item_v2.data1[5], item_v2.data1[6], item_v2.data1[7], item_v2.data1[8], item_v2.data1[9], item_v2.data1[10], item_v2.data1[11], item_v2.data2[0], item_v2.data2[1], item_v2.data2[2], item_v2.data2[3]); if (item_v2_decoded != item) { - log_warning("V2-decoded data does not match original data"); - log_warning("Data (V2-decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", + phosg::log_warning("V2-decoded data does not match original data"); + phosg::log_warning("Data (V2-decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", item_v2_decoded.data1[0], item_v2_decoded.data1[1], item_v2_decoded.data1[2], item_v2_decoded.data1[3], item_v2_decoded.data1[4], item_v2_decoded.data1[5], item_v2_decoded.data1[6], item_v2_decoded.data1[7], item_v2_decoded.data1[8], item_v2_decoded.data1[9], item_v2_decoded.data1[10], item_v2_decoded.data1[11], @@ -1704,30 +1704,30 @@ Action a_describe_item( ItemData item_gc_decoded = item_gc; item_gc_decoded.decode_for_version(Version::GC_V3); - log_info("Data (GC-encoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", + phosg::log_info("Data (GC-encoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", item_gc.data1[0], item_gc.data1[1], item_gc.data1[2], item_gc.data1[3], item_gc.data1[4], item_gc.data1[5], item_gc.data1[6], item_gc.data1[7], item_gc.data1[8], item_gc.data1[9], item_gc.data1[10], item_gc.data1[11], item_gc.data2[0], item_gc.data2[1], item_gc.data2[2], item_gc.data2[3]); if (item_gc_decoded != item) { - log_warning("GC-decoded data does not match original data"); - log_warning("Data (GC-decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", + phosg::log_warning("GC-decoded data does not match original data"); + phosg::log_warning("Data (GC-decoded): %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX -------- %02hhX%02hhX%02hhX%02hhX", item_gc_decoded.data1[0], item_gc_decoded.data1[1], item_gc_decoded.data1[2], item_gc_decoded.data1[3], item_gc_decoded.data1[4], item_gc_decoded.data1[5], item_gc_decoded.data1[6], item_gc_decoded.data1[7], item_gc_decoded.data1[8], item_gc_decoded.data1[9], item_gc_decoded.data1[10], item_gc_decoded.data1[11], item_gc_decoded.data2[0], item_gc_decoded.data2[1], item_gc_decoded.data2[2], item_gc_decoded.data2[3]); } - log_info("Description: %s", desc.c_str()); - log_info("Description (in-game): %s", desc_colored.c_str()); + phosg::log_info("Description: %s", desc.c_str()); + phosg::log_info("Description (in-game): %s", desc_colored.c_str()); size_t purchase_price = s->item_parameter_table(Version::BB_V4)->price_for_item(item); size_t sale_price = purchase_price >> 3; - log_info("Purchase price: %zu; sale price: %zu", purchase_price, sale_price); + phosg::log_info("Purchase price: %zu; sale price: %zu", purchase_price, sale_price); }); Action a_name_all_items( - "name-all-items", nullptr, +[](Arguments& args) { + "name-all-items", nullptr, +[](phosg::Arguments& args) { auto s = make_shared(get_config_filename(args)); s->load_config_early(); s->load_patch_indexes(false); @@ -1750,7 +1750,7 @@ Action a_name_all_items( Version version = static_cast(v_s); const auto& index = s->item_name_indexes.at(v_s); if (index) { - fprintf(stderr, " %30s ", name_for_enum(version)); + fprintf(stderr, " %30s ", phosg::name_for_enum(version)); } } fputc('\n', stderr); @@ -1777,7 +1777,7 @@ Action a_name_all_items( }); Action a_print_item_parameter_tables( - "print-item-tables", nullptr, +[](Arguments& args) { + "print-item-tables", nullptr, +[](phosg::Arguments& args) { auto s = make_shared(get_config_filename(args)); s->load_patch_indexes(false); s->load_text_index(false); @@ -1787,7 +1787,7 @@ Action a_print_item_parameter_tables( const auto& index = s->item_name_indexes.at(v_s); if (index) { Version v = static_cast(v_s); - fprintf(stdout, "======== %s\n", name_for_enum(v)); + fprintf(stdout, "======== %s\n", phosg::name_for_enum(v)); index->print_table(stdout); } } @@ -1798,7 +1798,7 @@ Action a_show_ep3_cards( show-ep3-cards\n\ Print the Episode 3 card definitions from the system/ep3 directory in a\n\ human-readable format.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { bool one_line = args.get("one-line"); auto s = make_shared(get_config_filename(args)); @@ -1806,13 +1806,13 @@ Action a_show_ep3_cards( unique_ptr text_english; try { - JSON json = JSON::parse(load_file("system/ep3/text-english.json")); + phosg::JSON json = phosg::JSON::parse(phosg::load_file("system/ep3/text-english.json")); text_english = make_unique(json); } catch (const exception& e) { } auto card_ids = s->ep3_card_index->all_ids(); - log_info("%zu card definitions", card_ids.size()); + phosg::log_info("%zu card definitions", card_ids.size()); for (uint32_t card_id : card_ids) { auto entry = s->ep3_card_index->definition_for_id(card_id); string def_str = entry->def.str(one_line, text_english.get()); @@ -1821,7 +1821,7 @@ Action a_show_ep3_cards( } else { fprintf(stdout, "%s\n", def_str.c_str()); if (!entry->debug_tags.empty()) { - string tags = join(entry->debug_tags, ", "); + string tags = phosg::join(entry->debug_tags, ", "); fprintf(stdout, " Tags: %s\n", tags.c_str()); } if (!entry->dice_caption.empty()) { @@ -1831,8 +1831,8 @@ Action a_show_ep3_cards( fprintf(stdout, " Dice text: %s\n", entry->dice_text.c_str()); } if (!entry->text.empty()) { - string text = str_replace_all(entry->text, "\n", "\n "); - strip_trailing_whitespace(text); + string text = phosg::str_replace_all(entry->text, "\n", "\n "); + phosg::strip_trailing_whitespace(text); fprintf(stdout, " Text:\n %s\n", text.c_str()); } fputc('\n', stdout); @@ -1846,7 +1846,7 @@ Action a_generate_ep3_cards_html( Generate an HTML file describing all Episode 3 card definitions from the\n\ system/ep3 directory. If --ep3-nte is given, use the Trial Edition card\n\ definitions instead.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { size_t num_threads = args.get("threads", 0); bool is_nte = (get_cli_version(args, Version::GC_EP3) == Version::GC_EP3_NTE); @@ -1886,7 +1886,7 @@ Action a_generate_ep3_cards_html( bool show_large_column = false; bool show_medium_column = false; bool show_small_column = false; - for (const auto& filename : list_directory_sorted("system/ep3/cardtex")) { + for (const auto& filename : phosg::list_directory_sorted("system/ep3/cardtex")) { if ((filename[0] == 'C' || filename[0] == 'M' || filename[0] == 'L') && (filename[1] == '_')) { size_t card_id = stoull(filename.substr(2, 3), nullptr, 10); if (infos.size() <= card_id) { @@ -1906,23 +1906,23 @@ Action a_generate_ep3_cards_html( } } - parallel_range([&](uint32_t index, size_t) -> bool { + phosg::parallel_range([&](uint32_t index, size_t) -> bool { auto& info = infos[index]; if (!info.large_filename.empty()) { - Image img(info.large_filename); - Image cropped(512, 399); + phosg::Image img(info.large_filename); + phosg::Image cropped(512, 399); cropped.blit(img, 0, 0, 512, 399, 0, 0); info.large_data_url = cropped.png_data_url(); } if (!info.medium_filename.empty()) { - Image img(info.medium_filename); - Image cropped(184, 144); + phosg::Image img(info.medium_filename); + phosg::Image cropped(184, 144); cropped.blit(img, 0, 0, 184, 144, 0, 0); info.medium_data_url = cropped.png_data_url(); } if (!info.small_filename.empty()) { - Image img(info.small_filename); - Image cropped(58, 43); + phosg::Image img(info.small_filename); + phosg::Image cropped(58, 43); cropped.blit(img, 0, 0, 58, 43, 0, 0); info.small_data_url = cropped.png_data_url(); } @@ -1962,8 +1962,8 @@ Action a_generate_ep3_cards_html( background_color = "#333333"; } - blocks.emplace_back(string_printf("", background_color)); - blocks.emplace_back(string_printf("", card_id)); + blocks.emplace_back(phosg::string_printf("", background_color)); + blocks.emplace_back(phosg::string_printf("", card_id)); if (show_small_column) { blocks.emplace_back("
%04zX
%04zX
"); if (!entry.small_data_url.empty()) { @@ -2005,7 +2005,7 @@ Action a_generate_ep3_cards_html( } blocks.emplace_back("
"); - save_file("cards.html", join(blocks, "")); + phosg::save_file("cards.html", phosg::join(blocks, "")); }); Action a_show_ep3_maps( @@ -2013,7 +2013,7 @@ Action a_show_ep3_maps( show-ep3-maps\n\ Print the Episode 3 maps from the system/ep3 directory in a (sort of)\n\ human-readable format.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { config_log.info("Collecting Episode 3 data"); auto s = make_shared(get_config_filename(args)); @@ -2021,7 +2021,7 @@ Action a_show_ep3_maps( s->load_ep3_maps(false); auto map_ids = s->ep3_map_index->all_numbers(); - log_info("%zu maps", map_ids.size()); + phosg::log_info("%zu maps", map_ids.size()); for (uint32_t map_id : map_ids) { auto map = s->ep3_map_index->for_number(map_id); const auto& vms = map->all_versions(); @@ -2040,7 +2040,7 @@ Action a_show_battle_params( show-battle-params\n\ Print the Blue Burst battle parameters from the system/blueburst directory\n\ in a human-readable format.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto s = make_shared(get_config_filename(args)); s->load_patch_indexes(false); s->load_battle_params(false); @@ -2073,7 +2073,7 @@ Action a_find_rare_enemy_seeds( by default, one thread per CPU core is used. --min-count specifies how many\n\ rare enemies must be found to output the seed. Finally, --quest=NAME may be\n\ given to use that quest\'s map instead of the free-roam maps.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { auto version = get_cli_version(args); auto episode = get_cli_episode(args); auto difficulty = get_cli_difficulty(args); @@ -2153,7 +2153,7 @@ Action a_find_rare_enemy_seeds( lock_guard g(output_lock); fprintf(stdout, "%08" PRIX64 ":", seed); for (size_t index : rare_indexes) { - fprintf(stdout, " E-%zX:%s", index, name_for_enum(map->enemies[index].type)); + fprintf(stdout, " E-%zX:%s", index, phosg::name_for_enum(map->enemies[index].type)); } fprintf(stdout, "\n"); } @@ -2161,11 +2161,11 @@ Action a_find_rare_enemy_seeds( return false; }; - parallel_range(thread_fn, 0, 0x100000000, num_threads, nullptr); + phosg::parallel_range(thread_fn, 0, 0x100000000, num_threads, nullptr); }); Action a_load_maps_test( - "load-maps-test", nullptr, +[](Arguments& args) { + "load-maps-test", nullptr, +[](phosg::Arguments& args) { using SDT = SetDataTable; auto s = make_shared(get_config_filename(args)); s->load_config_early(); @@ -2211,7 +2211,7 @@ Action a_load_maps_test( floor, var1, var2, episode, mode, SDT::FilenameType::EVENTS); fprintf(stderr, "... %s %s %s %s %02hhX %zX %zX", - name_for_enum(v), name_for_episode(episode), name_for_mode(mode), name_for_difficulty(difficulty), floor, var1, var2); + phosg::name_for_enum(v), name_for_episode(episode), name_for_mode(mode), name_for_difficulty(difficulty), floor, var1, var2); auto map = make_shared(v, 0, 0, nullptr); if (!enemies_filename.empty()) { fprintf(stderr, " [%s => ", enemies_filename.c_str()); @@ -2270,7 +2270,7 @@ Action a_load_maps_test( vq->quest_number, vq->name.c_str(), name_for_episode(vq->episode), - name_for_enum(vq->version), + phosg::name_for_enum(vq->version), name_for_language_code(vq->language), map->enemies.size(), map->enemy_set_flags.size(), @@ -2281,8 +2281,8 @@ Action a_load_maps_test( }); Action a_parse_object_graph( - "parse-object-graph", nullptr, +[](Arguments& args) { - uint32_t root_object_address = args.get("root", Arguments::IntFormat::HEX); + "parse-object-graph", nullptr, +[](phosg::Arguments& args) { + uint32_t root_object_address = args.get("root", phosg::Arguments::IntFormat::HEX); string data = read_input_data(args); PSOGCObjectGraph g(data, root_object_address); g.print(stdout); @@ -2293,7 +2293,7 @@ Action a_generate_dc_serial_number( generate-dc-serial-number DOMAIN SUBDOMAIN\n\ Generate a PSO DC serial number. DOMAIN should be 0 for Japanese, 1 for\n\ USA, or 2 for Europe. SUBDOMAIN should be 0 for v1, or 1 for v2.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { uint8_t domain = args.get(1); uint8_t subdomain = args.get(2); string serial_number = generate_dc_serial_number(domain, subdomain); @@ -2303,7 +2303,7 @@ Action a_generate_all_dc_serial_numbers( "generate-all-dc-serial-numbers", "\ generate-all-dc-serial-numbers\n\ Generate all possible PSO DC serial numbers.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { size_t num_threads = args.get("threads", 0); auto serial_numbers = generate_all_dc_serial_numbers(); @@ -2337,7 +2337,7 @@ Action a_generate_all_dc_serial_numbers( fprintf(stderr, "... %08" PRIX64 " %" PRId64 " (0x%" PRIX64 ") found\r", current_value, num_found, num_found); }; - parallel_range(thread_fn, 0, 0x100000000, num_threads, progress_fn); + phosg::parallel_range(thread_fn, 0, 0x100000000, num_threads, progress_fn); }); Action a_inspect_dc_serial_number( "inspect-dc-serial-number", "\ @@ -2345,7 +2345,7 @@ Action a_inspect_dc_serial_number( Show which domain and subdomain the serial number belongs to. (As with\n\ generate-dc-serial-number, described above, this will tell you which PSO\n\ version it is valid for.)\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const string& serial_number_str = args.get(1, false); if (serial_number_str.empty()) { throw invalid_argument("no serial number given"); @@ -2367,7 +2367,7 @@ Action a_dc_serial_number_speed_test( "dc-serial-number-speed-test", "\ dc-serial-number-speed-test\n\ Run a speed test of the two DC serial number validation functions.\n", - +[](Arguments& args) { + +[](phosg::Arguments& args) { const string& seed = args.get("seed"); if (seed.empty()) { dc_serial_number_speed_test(); @@ -2377,7 +2377,7 @@ Action a_dc_serial_number_speed_test( }); Action a_address_translator( - "address-translator", nullptr, +[](Arguments& args) { + "address-translator", nullptr, +[](phosg::Arguments& args) { const string& dir = args.get(1, false); if (dir.empty() || (dir == "-")) { throw invalid_argument("a directory name is required"); @@ -2386,34 +2386,34 @@ Action a_address_translator( }); Action a_diff_dol_files( - "diff-dol-files", nullptr, +[](Arguments& args) { + "diff-dol-files", nullptr, +[](phosg::Arguments& args) { const string& a_filename = args.get(1); const string& b_filename = args.get(2); auto result = diff_dol_files(a_filename, b_filename); for (const auto& it : result) { - string data = format_data_string(it.second, nullptr, FormatDataFlags::HEX_ONLY); + string data = phosg::format_data_string(it.second, nullptr, phosg::FormatDataFlags::HEX_ONLY); fprintf(stdout, "%08" PRIX32 " %s\n", it.first, data.c_str()); } }); Action a_generate_hangame_creds( - "generate-hangame-creds", nullptr, +[](Arguments& args) { + "generate-hangame-creds", nullptr, +[](phosg::Arguments& args) { const string& user_id = args.get(1); const string& token = args.get(2); const string& unused = args.get(3, false); - string hex = format_data_string(encode_psobb_hangame_credentials(user_id, token, unused)); + string hex = phosg::format_data_string(encode_psobb_hangame_credentials(user_id, token, unused)); fprintf(stdout, "psobb.exe 1196310600 %s\n", hex.c_str()); }); Action a_format_ep3_battle_record( - "format-ep3-battle-record", nullptr, +[](Arguments& args) { + "format-ep3-battle-record", nullptr, +[](phosg::Arguments& args) { string data = read_input_data(args); Episode3::BattleRecord rec(data); rec.print(stdout); }); Action a_replay_ep3_battle_commands( - "replay-ep3-battle-commands", nullptr, +[](Arguments& args) { + "replay-ep3-battle-commands", nullptr, +[](phosg::Arguments& args) { auto s = make_shared(get_config_filename(args)); s->load_ep3_cards(false); s->load_ep3_maps(false); @@ -2423,8 +2423,8 @@ Action a_replay_ep3_battle_commands( auto input = read_input_data(args); vector commands; - for (const auto& line : split(input, '\n')) { - string data = parse_data_string(line); + for (const auto& line : phosg::split(input, '\n')) { + string data = phosg::parse_data_string(line); if (!data.empty()) { commands.emplace_back(std::move(data)); } @@ -2458,12 +2458,12 @@ Action a_replay_ep3_battle_commands( run_replay(base_seed, 0); } else { size_t num_threads = args.get("threads", 0); - parallel_range(run_replay, 0, 0x100000000, num_threads); + phosg::parallel_range(run_replay, 0, 0x100000000, num_threads); } }); Action a_replay_ep3_battle_record( - "replay-ep3-battle-record", nullptr, +[](Arguments& args) { + "replay-ep3-battle-record", nullptr, +[](phosg::Arguments& args) { auto rec = make_shared(read_input_data(args)); auto s = make_shared(get_config_filename(args)); @@ -2479,7 +2479,7 @@ Action a_replay_ep3_battle_record( Episode3::BehaviorFlag::ENABLE_STATUS_MESSAGES | Episode3::BehaviorFlag::DISABLE_MASKING | Episode3::BehaviorFlag::LOG_COMMANDS_IF_LOBBY_MISSING), - .opt_rand_stream = make_shared(rec->get_random_stream()), + .opt_rand_stream = make_shared(rec->get_random_stream()), .opt_rand_crypt = nullptr, .tournament = nullptr, .trap_card_ids = {}, @@ -2491,21 +2491,21 @@ Action a_replay_ep3_battle_record( auto server = make_shared(nullptr, std::move(options)); server->init(); for (const auto& command : rec->get_all_server_data_commands()) { - log_info("Server data command"); - print_data(stderr, command, 0, nullptr, PrintDataFlags::PRINT_ASCII | PrintDataFlags::DISABLE_COLOR | PrintDataFlags::OFFSET_16_BITS); + phosg::log_info("Server data command"); + phosg::print_data(stderr, command, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS); server->on_server_data_input(nullptr, command); } }); Action a_disassemble_ep3_battle_record( - "disassemble-ep3-battle-record", nullptr, +[](Arguments& args) { + "disassemble-ep3-battle-record", nullptr, +[](phosg::Arguments& args) { Episode3::BattleRecord(read_input_data(args)).print(stdout); }); Action a_run_server_replay_log( - "", nullptr, +[](Arguments& args) { + "", nullptr, +[](phosg::Arguments& args) { { - string build_date = format_time(BUILD_TIMESTAMP); + string build_date = phosg::format_time(BUILD_TIMESTAMP); config_log.info("newserv %s compiled at %s", GIT_REVISION_HASH, build_date.c_str()); } @@ -2513,7 +2513,7 @@ Action a_run_server_replay_log( throw runtime_error("failed to set up libevent threads"); } - if (!isdir("system/players")) { + if (!phosg::isdir("system/players")) { config_log.info("Players directory does not exist; creating it"); mkdir("system/players", 0755); } @@ -2558,7 +2558,7 @@ Action a_run_server_replay_log( auto nop_destructor = +[](FILE*) {}; shared_ptr log_f(stdin, nop_destructor); if (replay_log_filename != "-") { - log_f = fopen_shared(replay_log_filename, "rt"); + log_f = phosg::fopen_shared(replay_log_filename, "rt"); } replay_session = make_shared(base, log_f.get(), state, args.get("require-basic-credentials")); @@ -2580,12 +2580,12 @@ Action a_run_server_replay_log( // destination is supported, and we have to manually specify the // destination netloc here. if (is_patch(pc->version)) { - auto [ss, size] = make_sockaddr_storage( + auto [ss, size] = phosg::make_sockaddr_storage( state->proxy_destination_patch.first, state->proxy_destination_patch.second); state->proxy_server->listen(pc->addr, pc->port, pc->version, &ss); } else if (is_v4(pc->version)) { - auto [ss, size] = make_sockaddr_storage( + auto [ss, size] = phosg::make_sockaddr_storage( state->proxy_destination_bb.first, state->proxy_destination_bb.second); state->proxy_server->listen(pc->addr, pc->port, pc->version, &ss); @@ -2599,7 +2599,7 @@ Action a_run_server_replay_log( config_log.info("Starting PC_V2 patch server"); state->pc_patch_server = make_shared(state->generate_patch_server_config(false)); } - string spec = string_printf("TU-%hu-%s-patch2", pc->port, pc->name.c_str()); + string spec = phosg::string_printf("TU-%hu-%s-patch2", pc->port, pc->name.c_str()); state->pc_patch_server->listen(spec, pc->addr, pc->port, Version::PC_PATCH); } else if (pc->behavior == ServerBehavior::PATCH_SERVER_BB) { @@ -2607,7 +2607,7 @@ Action a_run_server_replay_log( config_log.info("Starting BB_V4 patch server"); state->bb_patch_server = make_shared(state->generate_patch_server_config(true)); } - string spec = string_printf("TU-%hu-%s-patch4", pc->port, pc->name.c_str()); + string spec = phosg::string_printf("TU-%hu-%s-patch4", pc->port, pc->name.c_str()); state->bb_patch_server->listen(spec, pc->addr, pc->port, Version::BB_PATCH); } else { @@ -2615,7 +2615,7 @@ Action a_run_server_replay_log( config_log.info("Starting game server"); state->game_server = make_shared(base, state); } - string spec = string_printf("TG-%hu-%s-%s-%s", pc->port, name_for_enum(pc->version), pc->name.c_str(), name_for_enum(pc->behavior)); + string spec = phosg::string_printf("TG-%hu-%s-%s-%s", pc->port, phosg::name_for_enum(pc->version), pc->name.c_str(), phosg::name_for_enum(pc->behavior)); state->game_server->listen(spec, pc->addr, pc->port, pc->version, pc->behavior); } } @@ -2624,20 +2624,20 @@ Action a_run_server_replay_log( config_log.info("Starting IP/PPP stack simulator"); state->ip_stack_simulator = make_shared(base, state); for (const auto& it : state->ip_stack_addresses) { - auto netloc = parse_netloc(it); - string spec = (netloc.second == 0) ? ("T-IPS-" + netloc.first) : string_printf("T-IPS-%hu", netloc.second); + auto netloc = phosg::parse_netloc(it); + string spec = (netloc.second == 0) ? ("T-IPS-" + netloc.first) : phosg::string_printf("T-IPS-%hu", netloc.second); state->ip_stack_simulator->listen( spec, netloc.first, netloc.second, IPStackSimulator::Protocol::ETHERNET_TAPSERVER); } for (const auto& it : state->ppp_stack_addresses) { - auto netloc = parse_netloc(it); - string spec = (netloc.second == 0) ? ("T-PPPST-" + netloc.first) : string_printf("T-PPPST-%hu", netloc.second); + auto netloc = phosg::parse_netloc(it); + string spec = (netloc.second == 0) ? ("T-PPPST-" + netloc.first) : phosg::string_printf("T-PPPST-%hu", netloc.second); state->ip_stack_simulator->listen( spec, netloc.first, netloc.second, IPStackSimulator::Protocol::HDLC_TAPSERVER); } for (const auto& it : state->ppp_raw_addresses) { - auto netloc = parse_netloc(it); - string spec = (netloc.second == 0) ? ("T-PPPSR-" + netloc.first) : string_printf("T-PPPSR-%hu", netloc.second); + auto netloc = phosg::parse_netloc(it); + string spec = (netloc.second == 0) ? ("T-PPPSR-" + netloc.first) : phosg::string_printf("T-PPPSR-%hu", netloc.second); state->ip_stack_simulator->listen( spec, netloc.first, netloc.second, IPStackSimulator::Protocol::HDLC_RAW); if (netloc.second) { @@ -2660,7 +2660,7 @@ Action a_run_server_replay_log( config_log.info("Starting HTTP server"); state->http_server = make_shared(state); for (const auto& it : state->http_addresses) { - auto netloc = parse_netloc(it); + auto netloc = phosg::parse_netloc(it); state->http_server->listen(netloc.first, netloc.second); } } @@ -2693,7 +2693,7 @@ Action a_run_server_replay_log( // If in a replay session, run the event loop for a bit longer to make // sure the server doesn't send anything unexpected after the end of // the session. - auto tv = usecs_to_timeval(500000); + auto tv = phosg::usecs_to_timeval(500000); event_base_loopexit(base.get(), &tv); event_base_dispatch(base.get()); } @@ -2724,7 +2724,7 @@ Action a_run_server_replay_log( }); void print_version_info() { - string build_date = format_time(BUILD_TIMESTAMP); + string build_date = phosg::format_time(BUILD_TIMESTAMP); fprintf(stderr, "newserv-%s built %s UTC\n", GIT_REVISION_HASH, build_date.c_str()); } @@ -2782,7 +2782,7 @@ Many versions also accept or require a version option. The version options are:\ } int main(int argc, char** argv) { - Arguments args(&argv[1], argc - 1); + phosg::Arguments args(&argv[1], argc - 1); if (args.get("help")) { print_usage(); return 0; @@ -2793,7 +2793,7 @@ int main(int argc, char** argv) { try { a = all_actions.at(action_name); } catch (const out_of_range&) { - log_error("Unknown or invalid action; try --help"); + phosg::log_error("Unknown or invalid action; try --help"); return 1; } #ifdef PHOSG_WINDOWS @@ -2803,19 +2803,19 @@ int main(int argc, char** argv) { try { a->run(args); } catch (const cannot_open_file& e) { - log_error("Top-level exception (cannot_open_file): %s", e.what()); + phosg::log_error("Top-level exception (cannot_open_file): %s", e.what()); throw; } catch (const invalid_argument& e) { - log_error("Top-level exception (invalid_argument): %s", e.what()); + phosg::log_error("Top-level exception (invalid_argument): %s", e.what()); throw; } catch (const out_of_range& e) { - log_error("Top-level exception (out_of_range): %s", e.what()); + phosg::log_error("Top-level exception (out_of_range): %s", e.what()); throw; } catch (const runtime_error& e) { - log_error("Top-level exception (runtime_error): %s", e.what()); + phosg::log_error("Top-level exception (runtime_error): %s", e.what()); throw; } catch (const exception& e) { - log_error("Top-level exception: %s", e.what()); + phosg::log_error("Top-level exception: %s", e.what()); throw; } #else diff --git a/src/Map.cc b/src/Map.cc index 66a17b3d..6c986ff0 100644 --- a/src/Map.cc +++ b/src/Map.cc @@ -583,7 +583,7 @@ Map::RareEnemyRates::RareEnemyRates(uint32_t enemy_rate, uint32_t boss_rate) dorphon_eclair(enemy_rate), kondrieu(boss_rate) {} -Map::RareEnemyRates::RareEnemyRates(const JSON& json) +Map::RareEnemyRates::RareEnemyRates(const phosg::JSON& json) : hildeblue(json.get_int("Hildeblue")), rappy(json.get_int("Rappy")), nar_lily(json.get_int("NarLily")), @@ -593,8 +593,8 @@ Map::RareEnemyRates::RareEnemyRates(const JSON& json) dorphon_eclair(json.get_int("DorphonEclair")), kondrieu(json.get_int("Kondrieu")) {} -JSON Map::RareEnemyRates::json() const { - return JSON::dict({ +phosg::JSON Map::RareEnemyRates::json() const { + return phosg::JSON::dict({ {"Hildeblue", this->hildeblue}, {"Rappy", this->rappy}, {"NarLily", this->nar_lily}, @@ -608,7 +608,7 @@ JSON Map::RareEnemyRates::json() const { string Map::ObjectEntry::str() const { string name_str = Map::name_for_object_type(this->base_type); - return string_printf("[ObjectEntry type=%04hX \"%s\" flags=%04hX index=%04hX a2=%04hX entity_id=%04hX group=%04hX section=%04hX a3=%04hX x=%g y=%g z=%g x_angle=%08" PRIX32 " y_angle=%08" PRIX32 " z_angle=%08" PRIX32 " params=[%g %g %g %08" PRIX32 " %08" PRIX32 " %08" PRIX32 "] unused=%08" PRIX32 "]", + return phosg::string_printf("[ObjectEntry type=%04hX \"%s\" flags=%04hX index=%04hX a2=%04hX entity_id=%04hX group=%04hX section=%04hX a3=%04hX x=%g y=%g z=%g x_angle=%08" PRIX32 " y_angle=%08" PRIX32 " z_angle=%08" PRIX32 " params=[%g %g %g %08" PRIX32 " %08" PRIX32 " %08" PRIX32 "] unused=%08" PRIX32 "]", this->base_type.load(), name_str.c_str(), this->flags.load(), @@ -634,7 +634,7 @@ string Map::ObjectEntry::str() const { } string Map::EnemyEntry::str() const { - return string_printf("[EnemyEntry type=%04hX flags=%04hX index=%04hX num_children=%04hX floor=%04hX entity_id=%04hX section=%04hX wave_number=%04hX wave_number2=%04hX a1=%04hX x=%g y=%g z=%g x_angle=%08" PRIX32 " y_angle=%08" PRIX32 " z_angle=%08" PRIX32 " params=[%g %g %g %g %g %04hX %04hX] unused=%08" PRIX32 "]", + return phosg::string_printf("[EnemyEntry type=%04hX flags=%04hX index=%04hX num_children=%04hX floor=%04hX entity_id=%04hX section=%04hX wave_number=%04hX wave_number2=%04hX a1=%04hX x=%g y=%g z=%g x_angle=%08" PRIX32 " y_angle=%08" PRIX32 " z_angle=%08" PRIX32 " params=[%g %g %g %g %g %04hX %04hX] unused=%08" PRIX32 "]", this->base_type.load(), this->flags.load(), this->index.load(), @@ -681,10 +681,10 @@ Map::Enemy::Enemy( server_flags(0) {} string Map::Enemy::str() const { - return string_printf("[Map::Enemy E-%hX source %zX %s%s floor=%02hhX section=%04hX wave_number=%04hX server_flags=%02hhX]", + return phosg::string_printf("[Map::Enemy E-%hX source %zX %s%s floor=%02hhX section=%04hX wave_number=%04hX server_flags=%02hhX]", this->enemy_id, this->source_index, - name_for_enum(this->type), + phosg::name_for_enum(this->type), enemy_type_is_rare(this->type) ? " RARE" : "", this->floor, this->section, @@ -693,7 +693,7 @@ string Map::Enemy::str() const { } string Map::Event::str() const { - return string_printf("[Map::Event W-%02hhX-%" PRIX32 " flags=%04hX floor=%02hhX action_stream_offset=%" PRIX32 "]", + return phosg::string_printf("[Map::Event W-%02hhX-%" PRIX32 " flags=%04hX floor=%02hhX action_stream_offset=%" PRIX32 "]", this->floor, this->event_id, this->flags, @@ -702,7 +702,7 @@ string Map::Event::str() const { } string Map::Object::str() const { - return string_printf("[Map::Object source %zX %04hX(%s) @%04hX p1=%g p456=[%08" PRIX32 " %08" PRIX32 " %08" PRIX32 "] floor=%02hhX item_drop_checked=%s]", + return phosg::string_printf("[Map::Object source %zX %04hX(%s) @%04hX p1=%g p456=[%08" PRIX32 " %08" PRIX32 " %08" PRIX32 "] floor=%02hhX item_drop_checked=%s]", this->source_index, this->base_type, Map::name_for_object_type(this->base_type), @@ -716,7 +716,7 @@ string Map::Object::str() const { } Map::Map(Version version, uint32_t lobby_id, uint32_t rare_seed, std::shared_ptr opt_rand_crypt) - : log(string_printf("[Lobby:%08" PRIX32 ":map] ", lobby_id), lobby_log.min_level), + : log(phosg::string_printf("[Lobby:%08" PRIX32 ":map] ", lobby_id), lobby_log.min_level), version(version), rare_seed(rare_seed), opt_rand_crypt(opt_rand_crypt) {} @@ -1254,7 +1254,7 @@ void Map::add_enemies_from_map_data( throw runtime_error("data size is not a multiple of entry size"); } - StringReader r(data, size); + phosg::StringReader r(data, size); for (size_t y = 0; y < entry_count; y++) { this->add_enemy(episode, difficulty, event, floor, y, r.get(), rare_rates); } @@ -1284,12 +1284,12 @@ uint32_t Map::DATParserRandomState::next_location_index() { } void Map::DATParserRandomState::generate_shuffled_location_table( - const Map::RandomEnemyLocationsHeader& header, StringReader r, uint16_t section) { + const Map::RandomEnemyLocationsHeader& header, phosg::StringReader r, uint16_t section) { if (header.num_sections == 0) { throw runtime_error("no locations defined"); } - StringReader sections_r = r.sub(header.section_table_offset, header.num_sections * sizeof(Map::RandomEnemyLocationSection)); + phosg::StringReader sections_r = r.sub(header.section_table_offset, header.num_sections * sizeof(Map::RandomEnemyLocationSection)); size_t bs_min = 0; size_t bs_max = header.num_sections - 1; @@ -1330,9 +1330,9 @@ void Map::add_random_enemies_from_map_data( uint8_t difficulty, uint8_t event, uint8_t floor, - StringReader wave_events_segment_r, - StringReader locations_segment_r, - StringReader definitions_segment_r, + phosg::StringReader wave_events_segment_r, + phosg::StringReader locations_segment_r, + phosg::StringReader definitions_segment_r, std::shared_ptr random_state, std::shared_ptr rare_rates) { @@ -1362,7 +1362,7 @@ void Map::add_random_enemies_from_map_data( definitions_header.weight_entry_count * sizeof(RandomEnemyWeight)); for (size_t wave_entry_index = 0; wave_entry_index < wave_events_header.entry_count; wave_entry_index++) { - auto entry_log = this->log.sub(string_printf("(Entry %zu/%" PRIu32 ") ", wave_entry_index, wave_events_header.entry_count.load())); + auto entry_log = this->log.sub(phosg::string_printf("(Entry %zu/%" PRIu32 ") ", wave_entry_index, wave_events_header.entry_count.load())); const auto& entry = wave_events_segment_r.get(); size_t remaining_waves = random_state->rand_int_biased(1, entry.max_waves); @@ -1372,7 +1372,7 @@ void Map::add_random_enemies_from_map_data( uint32_t wave_number = entry.wave_number; while (remaining_waves) { remaining_waves--; - auto wave_log = entry_log.sub(string_printf("(Wave %zu) ", remaining_waves)); + auto wave_log = entry_log.sub(phosg::string_printf("(Wave %zu) ", remaining_waves)); size_t remaining_enemies = random_state->rand_int_biased(entry.min_enemies, entry.max_enemies); // Trace: at 0080E208 EDI is enemy count @@ -1382,7 +1382,7 @@ void Map::add_random_enemies_from_map_data( while (remaining_enemies) { remaining_enemies--; - auto enemy_log = wave_log.sub(string_printf("(Enemy %zu) ", remaining_enemies)); + auto enemy_log = wave_log.sub(phosg::string_printf("(Enemy %zu) ", remaining_enemies)); // TODO: Factor this sum out of the loops weights_r.go(0); @@ -1506,7 +1506,7 @@ vector Map::get_events(uint8_t floor, uint32_t event_id) cons } void Map::add_events_from_map_data(uint8_t floor, const void* data, size_t size) { - StringReader r(data, size); + phosg::StringReader r(data, size); const auto& header = r.get(); if (header.format != 0) { throw runtime_error("events section format is not zero"); @@ -1525,7 +1525,7 @@ void Map::add_events_from_map_data(uint8_t floor, const void* data, size_t size) vector Map::collect_quest_map_data_sections(const void* data, size_t size) { vector ret; - StringReader r(data, size); + phosg::StringReader r(data, size); while (!r.eof()) { size_t header_offset = r.where(); const auto& header = r.get(); @@ -1534,7 +1534,7 @@ vector Map::collect_quest_map_data_sections(const void break; } if (header.section_size < sizeof(header)) { - throw runtime_error(string_printf("quest layout has invalid section header at offset 0x%zX", r.where() - sizeof(header))); + throw runtime_error(phosg::string_printf("quest layout has invalid section header at offset 0x%zX", r.where() - sizeof(header))); } if (header.floor > 0x100) { @@ -1593,7 +1593,7 @@ void Map::add_entities_from_quest_data( std::shared_ptr rare_rates) { auto all_floor_sections = this->collect_quest_map_data_sections(data, size); - StringReader r(data, size); + phosg::StringReader r(data, size); shared_ptr random_state; for (size_t floor = 0; floor < all_floor_sections.size(); floor++) { const auto& floor_sections = all_floor_sections[floor]; @@ -1713,7 +1713,7 @@ std::vector Map::get_events(uint8_t floor) { template static string disassemble_vector_file_t(const void* data, size_t size, size_t* entry_number, char type_ch) { deque ret; - StringReader r(data, size); + phosg::StringReader r(data, size); size_t local_entry_number = 0; if (!entry_number) { @@ -1722,14 +1722,14 @@ static string disassemble_vector_file_t(const void* data, size_t size, size_t* e while (r.remaining() >= sizeof(EntryT)) { string o_str = r.get().str(); - ret.emplace_back(string_printf("/* %c-%zX */ %s", type_ch, (*entry_number)++, o_str.c_str())); + ret.emplace_back(phosg::string_printf("/* %c-%zX */ %s", type_ch, (*entry_number)++, o_str.c_str())); } if (r.remaining()) { ret.emplace_back("// Warning: section size is not a multiple of entry size"); size_t size = r.remaining(); - ret.emplace_back(format_data(r.getv(size), size)); + ret.emplace_back(phosg::format_data(r.getv(size), size)); } - return join(ret, "\n"); + return phosg::join(ret, "\n"); } string Map::disassemble_objects_data(const void* data, size_t size, size_t* object_number) { @@ -1742,18 +1742,18 @@ string Map::disassemble_enemies_data(const void* data, size_t size, size_t* enem string Map::disassemble_wave_events_data(const void* data, size_t size, uint8_t floor) { deque ret; - StringReader r(data, size); + phosg::StringReader r(data, size); const auto& evt_header = r.get(); if (evt_header.format == 0x65767432) { // 'evt2' ret.emplace_back(".evt2_format"); // TODO size_t size = r.remaining(); - ret.emplace_back(format_data(r.getv(size), size)); + ret.emplace_back(phosg::format_data(r.getv(size), size)); } else { auto action_stream_r = r.sub(evt_header.action_stream_offset); for (size_t z = 0; z < evt_header.entry_count; z++) { const auto& entry = r.get(); - ret.emplace_back(string_printf("/* W-%02hhX-%" PRIX32 " */ [Event1Entry flags=%04hX type=%04hX section=%04hX wave_number=%04hX delay=%" PRIu32 "]", + ret.emplace_back(phosg::string_printf("/* W-%02hhX-%" PRIX32 " */ [Event1Entry flags=%04hX type=%04hX section=%04hX wave_number=%04hX delay=%" PRIu32 "]", floor, entry.event_id.load(), entry.flags.load(), @@ -1767,103 +1767,103 @@ string Map::disassemble_wave_events_data(const void* data, size_t size, uint8_t uint8_t opcode = ev_actions_r.get_u8(); switch (opcode) { case 0x00: - ret.emplace_back(string_printf(" 00 nop")); + ret.emplace_back(phosg::string_printf(" 00 nop")); break; case 0x01: - ret.emplace_back(string_printf(" 01 stop")); + ret.emplace_back(phosg::string_printf(" 01 stop")); should_continue = false; break; case 0x08: { uint16_t section = ev_actions_r.get_u16l(); uint16_t group = ev_actions_r.get_u16l(); - ret.emplace_back(string_printf(" 08 %04hX %04hX construct_objects section=%04hX group=%04hX", + ret.emplace_back(phosg::string_printf(" 08 %04hX %04hX construct_objects section=%04hX group=%04hX", section, group, section, group)); break; } case 0x09: { uint16_t section = ev_actions_r.get_u16l(); uint16_t wave_number = ev_actions_r.get_u16l(); - ret.emplace_back(string_printf(" 09 %04hX %04hX construct_enemies section=%04hX wave_number=%04hX", + ret.emplace_back(phosg::string_printf(" 09 %04hX %04hX construct_enemies section=%04hX wave_number=%04hX", section, wave_number, section, wave_number)); break; } case 0x0A: { uint16_t id = ev_actions_r.get_u16l(); - ret.emplace_back(string_printf(" 0A %04hX enable_switch_flag id=%04hX", id, id)); + ret.emplace_back(phosg::string_printf(" 0A %04hX enable_switch_flag id=%04hX", id, id)); break; } case 0x0B: { uint16_t id = ev_actions_r.get_u16l(); - ret.emplace_back(string_printf(" 0B %04hX disable_switch_flag id=%04hX", id, id)); + ret.emplace_back(phosg::string_printf(" 0B %04hX disable_switch_flag id=%04hX", id, id)); break; } case 0x0C: { uint32_t event_id = ev_actions_r.get_u32l(); - ret.emplace_back(string_printf(" 0C %08" PRIX32 " trigger_event event_id=%08" PRIX32, event_id, event_id)); + ret.emplace_back(phosg::string_printf(" 0C %08" PRIX32 " trigger_event event_id=%08" PRIX32, event_id, event_id)); break; } case 0x0D: { uint16_t section = ev_actions_r.get_u16l(); uint16_t wave_number = ev_actions_r.get_u16l(); - ret.emplace_back(string_printf(" 0D %04hX %04hX construct_enemies_stop section=%04hX wave_number=%04hX", + ret.emplace_back(phosg::string_printf(" 0D %04hX %04hX construct_enemies_stop section=%04hX wave_number=%04hX", section, wave_number, section, wave_number)); break; } default: - ret.emplace_back(string_printf(" %02hhX .invalid", opcode)); + ret.emplace_back(phosg::string_printf(" %02hhX .invalid", opcode)); } } } } - return join(ret, "\n"); + return phosg::join(ret, "\n"); } string Map::disassemble_quest_data(const void* data, size_t size) { auto all_floor_sections = Map::collect_quest_map_data_sections(data, size); deque ret; - StringReader r(data, size); + phosg::StringReader r(data, size); size_t object_number = 0; size_t enemy_number = 0; for (size_t floor = 0; floor < all_floor_sections.size(); floor++) { const auto& floor_sections = all_floor_sections[floor]; if (floor_sections.objects != 0xFFFFFFFF) { - ret.emplace_back(string_printf(".objects %zu", floor)); + ret.emplace_back(phosg::string_printf(".objects %zu", floor)); const auto& header = r.pget(floor_sections.objects); size_t offset = floor_sections.objects + sizeof(SectionHeader); ret.emplace_back(Map::disassemble_objects_data(r.pgetv(offset, header.data_size), header.data_size, &object_number)); } if (floor_sections.enemies != 0xFFFFFFFF) { - ret.emplace_back(string_printf(".enemies %zu", floor)); + ret.emplace_back(phosg::string_printf(".enemies %zu", floor)); const auto& header = r.pget(floor_sections.enemies); size_t offset = floor_sections.enemies + sizeof(SectionHeader); ret.emplace_back(Map::disassemble_enemies_data(r.pgetv(offset, header.data_size), header.data_size, &enemy_number)); } if (floor_sections.wave_events != 0xFFFFFFFF) { - ret.emplace_back(string_printf(".wave_events %zu", floor)); + ret.emplace_back(phosg::string_printf(".wave_events %zu", floor)); const auto& header = r.pget(floor_sections.wave_events); size_t offset = floor_sections.wave_events + sizeof(SectionHeader); ret.emplace_back(Map::disassemble_wave_events_data(r.pgetv(offset, header.data_size), header.data_size, floor)); } if (floor_sections.random_enemy_locations != 0xFFFFFFFF) { - ret.emplace_back(string_printf(".random_enemy_locations %zu", floor)); + ret.emplace_back(phosg::string_printf(".random_enemy_locations %zu", floor)); const auto& header = r.pget(floor_sections.random_enemy_locations); size_t offset = floor_sections.random_enemy_locations + sizeof(SectionHeader); auto sub_r = r.sub(offset, header.data_size); - ret.emplace_back(format_data(sub_r.getv(sub_r.remaining()), header.data_size, offset)); + ret.emplace_back(phosg::format_data(sub_r.getv(sub_r.remaining()), header.data_size, offset)); } if (floor_sections.random_enemy_definitions != 0xFFFFFFFF) { - ret.emplace_back(string_printf(".random_enemy_definitions %zu", floor)); + ret.emplace_back(phosg::string_printf(".random_enemy_definitions %zu", floor)); const auto& header = r.pget(floor_sections.random_enemy_definitions); size_t offset = floor_sections.random_enemy_definitions + sizeof(SectionHeader); auto sub_r = r.sub(offset, header.data_size); - ret.emplace_back(format_data(sub_r.getv(sub_r.remaining()), header.data_size, offset)); + ret.emplace_back(phosg::format_data(sub_r.getv(sub_r.remaining()), header.data_size, offset)); } } - return join(ret, "\n") + "\n"; + return phosg::join(ret, "\n") + "\n"; } SetDataTableBase::SetDataTableBase(Version version) : version(version) {} @@ -1925,21 +1925,19 @@ SetDataTable::SetDataTable(Version version, const string& data) : SetDataTableBa } } -template +template void SetDataTable::load_table_t(const string& data) { - using U32T = typename conditional::type; - - StringReader r(data); + phosg::StringReader r(data); struct Footer { - U32T table3_offset; - U32T table3_count; // In le_uint16_ts (so *2 for size in bytes) - U32T unknown_a3; // == 1 - U32T unknown_a4; // == 0 - U32T root_table_offset_offset; - U32T unknown_a6; // == 0 - U32T unknown_a7; // == 0 - U32T unknown_a8; // == 0 + U32T table3_offset; + U32T table3_count; // In le_uint16_ts (so *2 for size in bytes) + U32T unknown_a3; // == 1 + U32T unknown_a4; // == 0 + U32T root_table_offset_offset; + U32T unknown_a6; // == 0 + U32T unknown_a7; // == 0 + U32T unknown_a8; // == 0 } __packed_ws__(Footer, 0x20); if (r.size() < sizeof(Footer)) { @@ -1947,23 +1945,23 @@ void SetDataTable::load_table_t(const string& data) { } auto& footer = r.pget