GameFile.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. // Copyright 2008 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "UICommon/GameFile.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <iterator>
  9. #include <map>
  10. #include <memory>
  11. #include <string>
  12. #include <string_view>
  13. #include <tuple>
  14. #include <utility>
  15. #include <vector>
  16. #include <fmt/format.h>
  17. #include <fmt/ranges.h>
  18. #include <pugixml.hpp>
  19. #include "Common/BitUtils.h"
  20. #include "Common/ChunkFile.h"
  21. #include "Common/CommonPaths.h"
  22. #include "Common/CommonTypes.h"
  23. #include "Common/Crypto/SHA1.h"
  24. #include "Common/FileUtil.h"
  25. #include "Common/HttpRequest.h"
  26. #include "Common/IOFile.h"
  27. #include "Common/Image.h"
  28. #include "Common/IniFile.h"
  29. #include "Common/MsgHandler.h"
  30. #include "Common/NandPaths.h"
  31. #include "Common/StringUtil.h"
  32. #include "Common/Swap.h"
  33. #include "Core/Config/UISettings.h"
  34. #include "Core/ConfigManager.h"
  35. #include "Core/IOS/ES/Formats.h"
  36. #include "Core/TitleDatabase.h"
  37. #include "DiscIO/Blob.h"
  38. #include "DiscIO/DiscExtractor.h"
  39. #include "DiscIO/Enums.h"
  40. #include "DiscIO/GameModDescriptor.h"
  41. #include "DiscIO/Volume.h"
  42. #include "DiscIO/WiiSaveBanner.h"
  43. namespace UICommon
  44. {
  45. namespace
  46. {
  47. const std::string EMPTY_STRING;
  48. bool UseGameCovers()
  49. {
  50. #ifdef ANDROID
  51. // Android has its own code for handling covers, written completely in Java.
  52. // It's best if we disable the C++ cover code on Android to avoid duplicated data and such.
  53. return false;
  54. #else
  55. return Config::Get(Config::MAIN_USE_GAME_COVERS);
  56. #endif
  57. }
  58. } // Anonymous namespace
  59. DiscIO::Language GameFile::GetConfigLanguage() const
  60. {
  61. return SConfig::GetInstance().GetLanguageAdjustedForRegion(DiscIO::IsWii(m_platform), m_region);
  62. }
  63. const std::string& GameFile::Lookup(DiscIO::Language language,
  64. const std::map<DiscIO::Language, std::string>& strings)
  65. {
  66. auto end = strings.end();
  67. auto it = strings.find(language);
  68. if (it != end)
  69. return it->second;
  70. // English tends to be a good fallback when the requested language isn't available
  71. if (language != DiscIO::Language::English)
  72. {
  73. it = strings.find(DiscIO::Language::English);
  74. if (it != end)
  75. return it->second;
  76. }
  77. // If English isn't available either, just pick something
  78. if (!strings.empty())
  79. return strings.cbegin()->second;
  80. return EMPTY_STRING;
  81. }
  82. const std::string&
  83. GameFile::LookupUsingConfigLanguage(const std::map<DiscIO::Language, std::string>& strings) const
  84. {
  85. return Lookup(GetConfigLanguage(), strings);
  86. }
  87. GameFile::GameFile() = default;
  88. GameFile::GameFile(std::string path) : m_file_path(std::move(path))
  89. {
  90. m_file_name = PathToFileName(m_file_path);
  91. {
  92. std::unique_ptr<DiscIO::Volume> volume(DiscIO::CreateVolume(m_file_path));
  93. if (volume != nullptr)
  94. {
  95. m_platform = volume->GetVolumeType();
  96. m_short_names = volume->GetShortNames();
  97. m_long_names = volume->GetLongNames();
  98. m_short_makers = volume->GetShortMakers();
  99. m_long_makers = volume->GetLongMakers();
  100. m_descriptions = volume->GetDescriptions();
  101. m_region = volume->GetRegion();
  102. m_country = volume->GetCountry();
  103. m_blob_type = volume->GetBlobType();
  104. m_block_size = volume->GetBlobReader().GetBlockSize();
  105. m_compression_method = volume->GetBlobReader().GetCompressionMethod();
  106. m_file_size = volume->GetRawSize();
  107. m_volume_size = volume->GetDataSize();
  108. m_volume_size_type = volume->GetDataSizeType();
  109. m_is_datel_disc = volume->IsDatelDisc();
  110. m_is_nkit = volume->IsNKit();
  111. m_internal_name = volume->GetInternalName();
  112. m_game_id = volume->GetGameID();
  113. m_gametdb_id = volume->GetGameTDBID();
  114. m_triforce_id = volume->GetTriforceID();
  115. m_title_id = volume->GetTitleID().value_or(0);
  116. m_maker_id = volume->GetMakerID();
  117. m_revision = volume->GetRevision().value_or(0);
  118. m_disc_number = volume->GetDiscNumber().value_or(0);
  119. m_is_two_disc_game = CheckIfTwoDiscGame(m_game_id);
  120. m_apploader_date = volume->GetApploaderDate();
  121. m_volume_banner.buffer = volume->GetBanner(&m_volume_banner.width, &m_volume_banner.height);
  122. m_valid = true;
  123. }
  124. }
  125. if (!IsValid() && IsElfOrDol())
  126. {
  127. m_valid = true;
  128. m_file_size = m_volume_size = File::GetSize(m_file_path);
  129. m_game_id = SConfig::MakeGameID(m_file_name);
  130. m_volume_size_type = DiscIO::DataSizeType::Accurate;
  131. m_is_datel_disc = false;
  132. m_is_nkit = false;
  133. m_platform = DiscIO::Platform::ELFOrDOL;
  134. m_blob_type = DiscIO::BlobType::DIRECTORY;
  135. }
  136. if (!IsValid() && GetExtension() == ".json")
  137. {
  138. auto descriptor = DiscIO::ParseGameModDescriptorFile(m_file_path);
  139. if (descriptor)
  140. {
  141. GameFile proxy(descriptor->base_file);
  142. if (proxy.IsValid())
  143. {
  144. m_valid = true;
  145. m_file_size = File::GetSize(m_file_path);
  146. m_long_names.emplace(DiscIO::Language::English, std::move(descriptor->display_name));
  147. if (!descriptor->maker.empty())
  148. m_long_makers.emplace(DiscIO::Language::English, std::move(descriptor->maker));
  149. m_internal_name = proxy.GetInternalName();
  150. m_game_id = proxy.GetGameID();
  151. m_gametdb_id = proxy.GetGameTDBID();
  152. m_title_id = proxy.GetTitleID();
  153. m_maker_id = proxy.GetMakerID();
  154. m_region = proxy.GetRegion();
  155. m_country = proxy.GetCountry();
  156. m_platform = proxy.GetPlatform();
  157. m_revision = proxy.GetRevision();
  158. m_disc_number = proxy.GetDiscNumber();
  159. m_blob_type = DiscIO::BlobType::MOD_DESCRIPTOR;
  160. }
  161. }
  162. }
  163. }
  164. GameFile::~GameFile() = default;
  165. bool GameFile::IsValid() const
  166. {
  167. if (!m_valid)
  168. return false;
  169. if (m_platform == DiscIO::Platform::WiiWAD && !IOS::ES::IsChannel(m_title_id))
  170. return false;
  171. return true;
  172. }
  173. bool GameFile::CustomCoverChanged()
  174. {
  175. if (!m_custom_cover.buffer.empty() || !UseGameCovers())
  176. return false;
  177. std::string path, name;
  178. SplitPath(m_file_path, &path, &name, nullptr);
  179. std::string contents;
  180. // This icon naming format is intended as an alternative to Homebrew Channel icons
  181. // for those who don't want to have a Homebrew Channel style folder structure.
  182. const std::string cover_path = path + name + ".cover.png";
  183. bool success = File::Exists(cover_path) && File::ReadFileToString(cover_path, contents);
  184. if (!success)
  185. {
  186. const std::string alt_cover_path = path + "cover.png";
  187. success = File::Exists(alt_cover_path) && File::ReadFileToString(alt_cover_path, contents);
  188. }
  189. if (success)
  190. m_pending.custom_cover.buffer = {contents.begin(), contents.end()};
  191. return success;
  192. }
  193. void GameFile::DownloadDefaultCover()
  194. {
  195. if (!m_default_cover.buffer.empty() || !UseGameCovers() || m_gametdb_id.empty())
  196. return;
  197. const auto cover_path = File::GetUserPath(D_COVERCACHE_IDX) + DIR_SEP;
  198. const auto png_path = cover_path + m_gametdb_id + ".png";
  199. // If the cover has already been downloaded, abort
  200. if (File::Exists(png_path))
  201. return;
  202. const std::string region_code =
  203. SConfig::GetInstance().GetGameTDBImageRegionCode(DiscIO::IsWii(GetPlatform()), m_region);
  204. Common::HttpRequest request;
  205. static constexpr char cover_url[] = "https://art.gametdb.com/wii/cover/{}/{}.png";
  206. const auto response = request.Get(fmt::format(cover_url, region_code, m_gametdb_id));
  207. if (!response)
  208. return;
  209. File::WriteStringToFile(png_path, std::string(response->begin(), response->end()));
  210. }
  211. bool GameFile::DefaultCoverChanged()
  212. {
  213. if (!m_default_cover.buffer.empty() || !UseGameCovers())
  214. return false;
  215. const auto cover_path = File::GetUserPath(D_COVERCACHE_IDX) + DIR_SEP;
  216. std::string contents;
  217. File::ReadFileToString(cover_path + m_gametdb_id + ".png", contents);
  218. if (contents.empty())
  219. return false;
  220. m_pending.default_cover.buffer = {contents.begin(), contents.end()};
  221. return true;
  222. }
  223. void GameFile::CustomCoverCommit()
  224. {
  225. m_custom_cover = std::move(m_pending.custom_cover);
  226. }
  227. void GameFile::DefaultCoverCommit()
  228. {
  229. m_default_cover = std::move(m_pending.default_cover);
  230. }
  231. void GameBanner::DoState(PointerWrap& p)
  232. {
  233. p.Do(buffer);
  234. p.Do(width);
  235. p.Do(height);
  236. }
  237. void GameCover::DoState(PointerWrap& p)
  238. {
  239. p.Do(buffer);
  240. }
  241. void GameFile::DoState(PointerWrap& p)
  242. {
  243. p.Do(m_valid);
  244. p.Do(m_file_path);
  245. p.Do(m_file_name);
  246. p.Do(m_file_size);
  247. p.Do(m_volume_size);
  248. p.Do(m_volume_size_type);
  249. p.Do(m_is_datel_disc);
  250. p.Do(m_is_nkit);
  251. p.Do(m_short_names);
  252. p.Do(m_long_names);
  253. p.Do(m_short_makers);
  254. p.Do(m_long_makers);
  255. p.Do(m_descriptions);
  256. p.Do(m_internal_name);
  257. p.Do(m_game_id);
  258. p.Do(m_gametdb_id);
  259. p.Do(m_triforce_id);
  260. p.Do(m_title_id);
  261. p.Do(m_maker_id);
  262. p.Do(m_region);
  263. p.Do(m_country);
  264. p.Do(m_platform);
  265. p.Do(m_blob_type);
  266. p.Do(m_block_size);
  267. p.Do(m_compression_method);
  268. p.Do(m_revision);
  269. p.Do(m_disc_number);
  270. p.Do(m_is_two_disc_game);
  271. p.Do(m_apploader_date);
  272. p.Do(m_custom_name);
  273. p.Do(m_custom_description);
  274. p.Do(m_custom_maker);
  275. m_volume_banner.DoState(p);
  276. m_custom_banner.DoState(p);
  277. m_default_cover.DoState(p);
  278. m_custom_cover.DoState(p);
  279. }
  280. std::string GameFile::GetExtension() const
  281. {
  282. std::string extension;
  283. SplitPath(m_file_path, nullptr, nullptr, &extension);
  284. Common::ToLower(&extension);
  285. return extension;
  286. }
  287. bool GameFile::IsElfOrDol() const
  288. {
  289. const std::string extension = GetExtension();
  290. return extension == ".elf" || extension == ".dol";
  291. }
  292. bool GameFile::ReadXMLMetadata(const std::string& path)
  293. {
  294. std::string data;
  295. if (!File::ReadFileToString(path, data))
  296. return false;
  297. pugi::xml_document doc;
  298. // We use load_buffer instead of load_file to avoid path encoding problems on Windows
  299. if (!doc.load_buffer(data.data(), data.size()))
  300. return false;
  301. const pugi::xml_node app_node = doc.child("app");
  302. m_pending.custom_name = app_node.child("name").text().as_string();
  303. m_pending.custom_maker = app_node.child("coder").text().as_string();
  304. m_pending.custom_description = app_node.child("short_description").text().as_string();
  305. // Elements that we aren't using:
  306. // version (can be written in any format)
  307. // release_date (YYYYmmddHHMMSS format)
  308. // long_description (can be several screens long!)
  309. return true;
  310. }
  311. bool GameFile::XMLMetadataChanged()
  312. {
  313. std::string path, name;
  314. SplitPath(m_file_path, &path, &name, nullptr);
  315. // This XML file naming format is intended as an alternative to the Homebrew Channel naming
  316. // for those who don't want to have a Homebrew Channel style folder structure.
  317. if (!ReadXMLMetadata(path + name + ".xml"))
  318. {
  319. // Homebrew Channel naming. Typical for DOLs and ELFs, but we also support it for volumes.
  320. if (!ReadXMLMetadata(path + "meta.xml"))
  321. {
  322. // If no XML metadata is found, remove any old XML metadata from memory.
  323. m_pending.custom_banner = {};
  324. }
  325. }
  326. return m_pending.custom_name != m_custom_name && m_pending.custom_maker != m_custom_maker &&
  327. m_pending.custom_description != m_custom_description;
  328. }
  329. void GameFile::XMLMetadataCommit()
  330. {
  331. m_custom_name = std::move(m_pending.custom_name);
  332. m_custom_description = std::move(m_pending.custom_description);
  333. m_custom_maker = std::move(m_pending.custom_maker);
  334. }
  335. bool GameFile::WiiBannerChanged()
  336. {
  337. // Wii banners can only be read if there is a save file.
  338. // In case the cache was created without a save file existing,
  339. // let's try reading the save file again, because it might exist now.
  340. if (!m_volume_banner.empty())
  341. return false;
  342. if (!DiscIO::IsWii(m_platform))
  343. return false;
  344. m_pending.volume_banner.buffer =
  345. DiscIO::WiiSaveBanner(m_title_id)
  346. .GetBanner(&m_pending.volume_banner.width, &m_pending.volume_banner.height);
  347. // We only reach here if the old banner was empty, so if the new banner isn't empty,
  348. // the new banner is guaranteed to be different from the old banner
  349. return !m_pending.volume_banner.buffer.empty();
  350. }
  351. void GameFile::WiiBannerCommit()
  352. {
  353. m_volume_banner = std::move(m_pending.volume_banner);
  354. }
  355. bool GameFile::ReadPNGBanner(const std::string& path)
  356. {
  357. File::IOFile file(path, "rb");
  358. if (!file)
  359. return false;
  360. std::vector<u8> png_data(file.GetSize());
  361. if (!file.ReadBytes(png_data.data(), png_data.size()))
  362. return false;
  363. GameBanner& banner = m_pending.custom_banner;
  364. Common::UniqueBuffer<u8> data_out;
  365. if (!Common::LoadPNG(png_data, &data_out, &banner.width, &banner.height))
  366. return false;
  367. // Make an ARGB copy of the RGBA data
  368. banner.buffer.resize(data_out.size() / sizeof(u32));
  369. for (size_t i = 0; i < banner.buffer.size(); i++)
  370. {
  371. const size_t j = i * sizeof(u32);
  372. banner.buffer[i] = (Common::swap32(data_out.data() + j) >> 8) + (data_out[j] << 24);
  373. }
  374. return true;
  375. }
  376. bool GameFile::TryLoadGameModDescriptorBanner()
  377. {
  378. if (m_blob_type != DiscIO::BlobType::MOD_DESCRIPTOR)
  379. return false;
  380. auto descriptor = DiscIO::ParseGameModDescriptorFile(m_file_path);
  381. if (!descriptor)
  382. return false;
  383. return ReadPNGBanner(descriptor->banner);
  384. }
  385. bool GameFile::CustomBannerChanged()
  386. {
  387. std::string path, name;
  388. SplitPath(m_file_path, &path, &name, nullptr);
  389. // This icon naming format is intended as an alternative to the Homebrew Channel naming
  390. // for those who don't want to have a Homebrew Channel style folder structure.
  391. if (!ReadPNGBanner(path + name + ".png"))
  392. {
  393. // Homebrew Channel icon naming. Typical for DOLs and ELFs, but we also support it for volumes.
  394. if (!ReadPNGBanner(path + "icon.png"))
  395. {
  396. // If it's a game mod descriptor file, it may specify its own custom banner.
  397. if (!TryLoadGameModDescriptorBanner())
  398. {
  399. // If no custom icon is found, go back to the non-custom one.
  400. m_pending.custom_banner = {};
  401. }
  402. }
  403. }
  404. return m_pending.custom_banner != m_custom_banner;
  405. }
  406. void GameFile::CustomBannerCommit()
  407. {
  408. m_custom_banner = std::move(m_pending.custom_banner);
  409. }
  410. const std::string& GameFile::GetName(const Core::TitleDatabase& title_database) const
  411. {
  412. if (!m_custom_name.empty())
  413. return m_custom_name;
  414. if (IsModDescriptor())
  415. return GetName(Variant::LongAndPossiblyCustom);
  416. const std::string& database_name =
  417. title_database.GetTitleName(m_gametdb_id, m_triforce_id, GetConfigLanguage());
  418. return database_name.empty() ? GetName(Variant::LongAndPossiblyCustom) : database_name;
  419. }
  420. const std::string& GameFile::GetName(Variant variant) const
  421. {
  422. if (variant == Variant::LongAndPossiblyCustom && !m_custom_name.empty())
  423. return m_custom_name;
  424. const std::string& name = variant == Variant::ShortAndNotCustom ? GetShortName() : GetLongName();
  425. if (!name.empty())
  426. return name;
  427. // No usable name, return filename (better than nothing)
  428. return m_file_name;
  429. }
  430. const std::string& GameFile::GetMaker(Variant variant) const
  431. {
  432. if (variant == Variant::LongAndPossiblyCustom && !m_custom_maker.empty())
  433. return m_custom_maker;
  434. const std::string& maker =
  435. variant == Variant::ShortAndNotCustom ? GetShortMaker() : GetLongMaker();
  436. if (!maker.empty())
  437. return maker;
  438. if (m_game_id.size() >= 6)
  439. return DiscIO::GetCompanyFromID(m_maker_id);
  440. return EMPTY_STRING;
  441. }
  442. const std::string& GameFile::GetDescription(Variant variant) const
  443. {
  444. if (variant == Variant::LongAndPossiblyCustom && !m_custom_description.empty())
  445. return m_custom_description;
  446. return LookupUsingConfigLanguage(m_descriptions);
  447. }
  448. std::vector<DiscIO::Language> GameFile::GetLanguages() const
  449. {
  450. std::vector<DiscIO::Language> languages;
  451. // TODO: What if some languages don't have long names but have other strings?
  452. for (const auto& name : m_long_names)
  453. languages.push_back(name.first);
  454. return languages;
  455. }
  456. bool GameFile::CheckIfTwoDiscGame(const std::string& game_id) const
  457. {
  458. constexpr size_t GAME_ID_PREFIX_SIZE = 3;
  459. if (game_id.size() < GAME_ID_PREFIX_SIZE)
  460. return false;
  461. static constexpr std::array<std::string_view, 30> two_disc_game_id_prefixes = {
  462. // Resident Evil
  463. "DBJ",
  464. // The Lord of the Rings: The Third Age
  465. "G3A",
  466. // Teenage Mutant Ninja Turtles 3: Mutant Nightmare
  467. "G3Q",
  468. // Resident Evil 4
  469. "G4B",
  470. // Tiger Woods PGA Tour 2005
  471. "G5T",
  472. // Resident Evil
  473. "GBI",
  474. // Resident Evil Zero
  475. "GBZ",
  476. // Conan
  477. "GC9",
  478. // Resident Evil Code: Veronica X
  479. "GCD",
  480. // Tom Clancy's Splinter Cell: Chaos Theory
  481. "GCJ",
  482. // Freaky Flyers
  483. "GFF",
  484. // GoldenEye: Rogue Agent
  485. "GGI",
  486. // Metal Gear Solid: The Twin Snakes
  487. "GGS",
  488. // Baten Kaitos Origins
  489. "GK4",
  490. // Killer7
  491. "GK7",
  492. // Baten Kaitos: Eternal Wings and the Lost Ocean
  493. "GKB",
  494. // Lupin the 3rd: Lost Treasure by the Sea
  495. "GL3",
  496. // Enter the Matrix
  497. "GMX",
  498. // Teenage Mutant Ninja Turtles 2: Battle Nexus
  499. "GNI",
  500. // GoldenEye: Rogue Agent
  501. "GOY",
  502. // Tales of Symphonia
  503. "GQS",
  504. // Medal of Honor: Rising Sun
  505. "GR8",
  506. "GRZ",
  507. // Tales of Symphonia
  508. "GTO",
  509. // Tiger Woods PGA Tour 2004
  510. "GW4",
  511. // Tom Clancy's Splinter Cell: Double Agent (GC)
  512. "GWY",
  513. // Dragon Quest X: Mezameshi Itsutsu no Shuzoku Online
  514. "S4M",
  515. "S4S",
  516. "S6T",
  517. "SDQ",
  518. };
  519. static_assert(std::ranges::is_sorted(two_disc_game_id_prefixes));
  520. std::string_view game_id_prefix(game_id.data(), GAME_ID_PREFIX_SIZE);
  521. return std::ranges::binary_search(two_disc_game_id_prefixes, game_id_prefix);
  522. }
  523. std::string GameFile::GetNetPlayName(const Core::TitleDatabase& title_database) const
  524. {
  525. std::vector<std::string> info;
  526. if (!GetGameID().empty())
  527. info.push_back(GetGameID());
  528. if (GetRevision() != 0)
  529. info.push_back("Revision " + std::to_string(GetRevision()));
  530. const std::string name = GetName(title_database);
  531. int disc_number = GetDiscNumber() + 1;
  532. std::string lower_name = name;
  533. Common::ToLower(&lower_name);
  534. if (disc_number > 1 &&
  535. lower_name.find(fmt::format("disc {}", disc_number)) == std::string::npos &&
  536. lower_name.find(fmt::format("disc{}", disc_number)) == std::string::npos)
  537. {
  538. std::string disc_text = "Disc ";
  539. info.push_back(disc_text + std::to_string(disc_number));
  540. }
  541. if (info.empty())
  542. return name;
  543. return fmt::format("{} ({})", name, fmt::join(info, ", "));
  544. }
  545. static Common::SHA1::Digest GetHash(u32 value)
  546. {
  547. auto data = Common::BitCastToArray<u8>(value);
  548. return Common::SHA1::CalculateDigest(data);
  549. }
  550. static Common::SHA1::Digest GetHash(std::string_view str)
  551. {
  552. return Common::SHA1::CalculateDigest(str);
  553. }
  554. static std::optional<Common::SHA1::Digest> GetFileHash(const std::string& path)
  555. {
  556. std::string buffer;
  557. if (!File::ReadFileToString(path, buffer))
  558. return std::nullopt;
  559. return GetHash(buffer);
  560. }
  561. static std::optional<Common::SHA1::Digest> MixHash(const std::optional<Common::SHA1::Digest>& lhs,
  562. const std::optional<Common::SHA1::Digest>& rhs)
  563. {
  564. if (!lhs && !rhs)
  565. return std::nullopt;
  566. if (!lhs || !rhs)
  567. return !rhs ? lhs : rhs;
  568. Common::SHA1::Digest result;
  569. for (size_t i = 0; i < result.size(); ++i)
  570. result[i] = (*lhs)[i] ^ (*rhs)[(i + 1) % result.size()];
  571. return result;
  572. }
  573. Common::SHA1::Digest GameFile::GetSyncHash() const
  574. {
  575. std::optional<Common::SHA1::Digest> hash;
  576. if (m_platform == DiscIO::Platform::ELFOrDOL)
  577. {
  578. hash = GetFileHash(m_file_path);
  579. }
  580. else if (m_blob_type == DiscIO::BlobType::MOD_DESCRIPTOR)
  581. {
  582. auto descriptor = DiscIO::ParseGameModDescriptorFile(m_file_path);
  583. if (descriptor)
  584. {
  585. GameFile proxy(descriptor->base_file);
  586. if (proxy.IsValid())
  587. hash = proxy.GetSyncHash();
  588. // add patches to hash if they're enabled
  589. if (descriptor->riivolution)
  590. {
  591. for (const auto& patch : descriptor->riivolution->patches)
  592. {
  593. hash = MixHash(hash, GetFileHash(patch.xml));
  594. for (const auto& option : patch.options)
  595. {
  596. hash = MixHash(hash, GetHash(option.section_name));
  597. hash = MixHash(hash, GetHash(option.option_id));
  598. hash = MixHash(hash, GetHash(option.option_name));
  599. hash = MixHash(hash, GetHash(option.choice));
  600. }
  601. }
  602. }
  603. }
  604. }
  605. else
  606. {
  607. if (std::unique_ptr<DiscIO::Volume> volume = DiscIO::CreateVolume(m_file_path))
  608. hash = volume->GetSyncHash();
  609. }
  610. return hash.value_or(Common::SHA1::Digest{});
  611. }
  612. NetPlay::SyncIdentifier GameFile::GetSyncIdentifier() const
  613. {
  614. const u64 dol_elf_size = m_platform == DiscIO::Platform::ELFOrDOL ? m_file_size : 0;
  615. return NetPlay::SyncIdentifier{dol_elf_size, m_game_id, m_revision,
  616. m_disc_number, m_is_datel_disc, GetSyncHash()};
  617. }
  618. NetPlay::SyncIdentifierComparison
  619. GameFile::CompareSyncIdentifier(const NetPlay::SyncIdentifier& sync_identifier) const
  620. {
  621. const bool is_elf_or_dol = m_platform == DiscIO::Platform::ELFOrDOL;
  622. if ((is_elf_or_dol ? m_file_size : 0) != sync_identifier.dol_elf_size)
  623. return NetPlay::SyncIdentifierComparison::DifferentGame;
  624. if (m_is_datel_disc != sync_identifier.is_datel)
  625. return NetPlay::SyncIdentifierComparison::DifferentGame;
  626. if (m_game_id.size() != sync_identifier.game_id.size())
  627. return NetPlay::SyncIdentifierComparison::DifferentGame;
  628. if (!is_elf_or_dol && !m_is_datel_disc && m_game_id.size() >= 4 && m_game_id.size() <= 6)
  629. {
  630. // This is a game ID, following specific rules which we can use to give clearer information to
  631. // the user.
  632. // If the first 3 characters don't match, then these are probably different games.
  633. // (There are exceptions; in particular Japanese-region games sometimes use a different ID;
  634. // for instance, GOYE69, GOYP69, and GGIJ13 are used by GoldenEye: Rogue Agent.)
  635. if (std::string_view(&m_game_id[0], 3) != std::string_view(&sync_identifier.game_id[0], 3))
  636. return NetPlay::SyncIdentifierComparison::DifferentGame;
  637. // If the first 3 characters match but the region doesn't match, reject it as such.
  638. if (m_game_id[3] != sync_identifier.game_id[3])
  639. return NetPlay::SyncIdentifierComparison::DifferentRegion;
  640. // If the maker code is present, and doesn't match between the two but the main ID does,
  641. // these might be different revisions of the same game (e.g. a rerelease with a different
  642. // publisher), which we should treat as a different revision.
  643. if (std::string_view(&m_game_id[4]) != std::string_view(&sync_identifier.game_id[4]))
  644. return NetPlay::SyncIdentifierComparison::DifferentRevision;
  645. }
  646. else
  647. {
  648. // Numeric title ID or another generated ID that does not follow the rules above
  649. if (m_game_id != sync_identifier.game_id)
  650. return NetPlay::SyncIdentifierComparison::DifferentGame;
  651. }
  652. if (m_revision != sync_identifier.revision)
  653. return NetPlay::SyncIdentifierComparison::DifferentRevision;
  654. if (m_disc_number != sync_identifier.disc_number)
  655. return NetPlay::SyncIdentifierComparison::DifferentDiscNumber;
  656. if (GetSyncHash() != sync_identifier.sync_hash)
  657. {
  658. // Most Datel titles re-use the same game ID (GNHE5d, with that lowercase D, or DTLX01).
  659. // So if the hash differs, then it's probably a different game even if the game ID matches.
  660. if (m_is_datel_disc)
  661. return NetPlay::SyncIdentifierComparison::DifferentGame;
  662. else
  663. return NetPlay::SyncIdentifierComparison::DifferentHash;
  664. }
  665. return NetPlay::SyncIdentifierComparison::SameGame;
  666. }
  667. std::string GameFile::GetWiiFSPath() const
  668. {
  669. ASSERT(DiscIO::IsWii(m_platform));
  670. return Common::GetTitleDataPath(m_title_id, Common::FromWhichRoot::Configured);
  671. }
  672. bool GameFile::ShouldShowFileFormatDetails() const
  673. {
  674. switch (m_blob_type)
  675. {
  676. case DiscIO::BlobType::PLAIN:
  677. break;
  678. case DiscIO::BlobType::DRIVE:
  679. case DiscIO::BlobType::MOD_DESCRIPTOR:
  680. return false;
  681. default:
  682. return true;
  683. }
  684. switch (m_platform)
  685. {
  686. case DiscIO::Platform::WiiWAD:
  687. return false;
  688. case DiscIO::Platform::ELFOrDOL:
  689. return false;
  690. default:
  691. return true;
  692. }
  693. }
  694. std::string GameFile::GetFileFormatName() const
  695. {
  696. switch (m_platform)
  697. {
  698. case DiscIO::Platform::WiiWAD:
  699. return "WAD";
  700. case DiscIO::Platform::ELFOrDOL:
  701. {
  702. std::string extension = GetExtension();
  703. Common::ToUpper(&extension);
  704. // substr removes the dot
  705. return extension.substr(std::min<size_t>(1, extension.size()));
  706. }
  707. default:
  708. {
  709. std::string name = DiscIO::GetName(m_blob_type, true);
  710. if (m_is_nkit)
  711. return Common::FmtFormatT("{0} (NKit)", name);
  712. return name;
  713. }
  714. }
  715. }
  716. bool GameFile::ShouldAllowConversion() const
  717. {
  718. return DiscIO::IsDisc(m_platform) && m_volume_size_type == DiscIO::DataSizeType::Accurate;
  719. }
  720. bool GameFile::IsModDescriptor() const
  721. {
  722. return m_blob_type == DiscIO::BlobType::MOD_DESCRIPTOR;
  723. }
  724. const GameBanner& GameFile::GetBannerImage() const
  725. {
  726. return m_custom_banner.empty() ? m_volume_banner : m_custom_banner;
  727. }
  728. const GameCover& GameFile::GetCoverImage() const
  729. {
  730. return m_custom_cover.empty() ? m_default_cover : m_custom_cover;
  731. }
  732. } // namespace UICommon