diff --git a/CMakeLists.txt b/CMakeLists.txt index 645a0425..06f4e565 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,9 @@ add_executable(bbhost src/core/legacy_cpu.cpp src/core/legacy_cpu_code.cpp src/core/config.cpp + src/core/trophies.cpp + src/core/play_history.cpp + src/core/chalice_history.cpp src/core/config_move.cpp src/engine/image_text.cpp src/core/sha256.cpp @@ -118,6 +121,7 @@ add_executable(bbhost src/engine/paramdef.cpp src/engine/lua_events.cpp src/engine/event_flags.cpp + src/engine/play_history.cpp src/engine/player_data.cpp src/engine/world_chr.cpp src/engine/playlog.cpp @@ -227,6 +231,7 @@ add_executable(bbhost src/hle/net.cpp src/hle/http.cpp src/hle/ajm.cpp + src/hle/trophy.cpp src/hle/system.cpp src/host/label_landing.cpp ) @@ -1641,3 +1646,15 @@ else() DEPENDS bbhost USES_TERMINAL) endif() + +# Local trophies and campaign/chalice histories; no game files required. +foreach(history_test trophies play_history chalice_history) + add_executable(${history_test}_test tests/${history_test}_test.cpp src/core/${history_test}.cpp) + target_include_directories(${history_test}_test PRIVATE src include) + target_link_libraries(${history_test}_test PRIVATE Threads::Threads) + add_test(NAME ${history_test}_test COMMAND ${history_test}_test) +endforeach() +target_sources(trophies_test PRIVATE src/hle/trophy.cpp) +target_sources(chalice_history_test PRIVATE src/core/play_history.cpp) + +target_sources(bbhost PRIVATE src/host/trophy_ui.cpp src/host/play_history_ui.cpp) diff --git a/README.md b/README.md index 2d0698da..70f88113 100755 --- a/README.md +++ b/README.md @@ -224,3 +224,5 @@ game's code or data. - Thanks to the many contributors and testers, incomplete and in no particular order: Metr1k, Kyo, Schorched Knight, ancat, Nox-, Astrelle, BlitzWOLF, CrunchyCheese, foxyhooligans, gkberk, sen, Ultra, droogie + +Local progress: [trophies](docs/trophies.md) and [play and chalice history](docs/play-history.md), available in setup and the F10 menu. diff --git a/docs/play-history.md b/docs/play-history.md new file mode 100644 index 00000000..602e4e2a --- /dev/null +++ b/docs/play-history.md @@ -0,0 +1,37 @@ +# Play history + +bbhost records each character's NG/NG+ playtime, attempts, and kills for 17 base-game bosses, five DLC bosses, and chalice bosses. Campaign and chalice records have separate lists and totals. + +Open **Play history** in setup or the in-game F10 menu. Select a character and a cycle, or enable **Show totals across all cycles**. Switch between **Base game and DLC** and **Chalice dungeons**. + +## Counting fights + +An attempt starts when the fight's start event enables its AI and health bar. Standing outside the fog does not count. Deaths, retreats, interrupted fights, and the winning fight count as attempts: two losses followed by a win give three attempts and one kill. Resuming an active fight does not count it twice. A kill takes precedence if the player dies at the same time. + +Recording pauses during boss rush/practice and visits to another player's world. Practice results remain in the boss-rush plugin's own records. Plugin API 30 appends `campaign_tracking_pause(name, paused)` after the API 29 fields; practice plugins can hold and release their own pause on the main thread. Older API field offsets are unchanged. + +## Time and incomplete records + +Time follows the save's play clock. A rising NG+ counter ends the previous cycle. At the game's clock limit, 999:59:59, measurement continues using elapsed time in the world, excluding title screens and loading. Time while bbhost is closed is never added. + +When first observing an NG save, its saved total time belongs to cycle one. For a save already in NG+, earlier cycle boundaries cannot be reconstructed: the current cycle starts with a partial time record. Unobserved cycles are not invented. Missing a cycle boundary, for example after playing in another build, also makes the adjacent times partial. + +Previously defeated campaign bosses can be marked defeated, but earlier attempts cannot be recovered. **Unknown**, **+**, and **partial record** identify missing information. New cycles are recorded separately. + +## Storage + +`play-history.txt` in the data folder persists across sessions. Records are associated with save slots; renaming a character updates its display name. A decrease in cycle number, a fresh NG character, or a clock rollback greater than five minutes creates a separate record while retaining the previous one. Its totals do not mix with the old record. Smaller rollbacks, such as the gap since the last autosave, retain attempts and resume timing. + +The record is saved on attempts, kills, cycle changes, loading, and normal exit, and roughly every ten seconds during play. A forced exit may lose time since the last write. Writes use a temporary file and replacement. Unreadable, malformed, or future-version records are reported without being overwritten. + +Back up history files together with the game save. Tracking does not write game saves or event flags, or upload records. + +## Chalice dungeons + +Fixed and root chalice encounters are identified by dungeon, altar, layer, and boss. Encounters with the same boss in different dungeons keep separate active/cleared state. The multi-enemy Watchers encounter counts as one boss fight. + +Chalice progress survives NG+. Attempts and kills belong to the cycle in which they were observed; an existing clear is not counted again in the next cycle. Replaying a cleared dungeon starts a separate encounter and retains the prior clear. Totals combine matching boss types only within the selected character and cycles. + +An encounter already cleared when recording begins is shown as a prior clear, without assigning its kill to the current cycle. Initial attempts are lower bounds because earlier attempts are unknown. + +Chalice records live in `chalice-history.txt`; the campaign file's format is unchanged. Keep the save and both history files together when backing up or moving to another PC so character identifiers remain associated. diff --git a/docs/trophies.md b/docs/trophies.md new file mode 100644 index 00000000..c40e15b9 --- /dev/null +++ b/docs/trophies.md @@ -0,0 +1,24 @@ +# Local trophies + +bbhost records 40 trophies: 34 for the base game, including platinum, and six for The Old Hunters. When the game awards a trophy, bbhost saves it and shows a notification for six seconds. Notifications queue; repeated awards do not change the original timestamp. Platinum unlocks after all 33 other base-game trophies. DLC trophies are not required. + +Open **Trophies** in the setup window or the in-game F10 menu. The list shows names, requirements, grades, progress, and unlock times in UTC. Filter by All, Unlocked, or Locked. Hidden trophies conceal their name and requirements until unlocked unless you select **Reveal hidden trophies**. + +## Records and compatibility + +Records live in `trophies.txt` in your configured data folder and are shared by characters using that folder. Existing bbhost records work unchanged. Choosing another data folder in setup changes the displayed record. + +Before the first update to an existing file, bbhost makes `trophies.txt.pre-trophies.bak` without overwriting an earlier backup. New contents are flushed to a temporary file and replace the record only after the write succeeds. A failed write does not award or announce the trophy; check free space and permissions. + +If an existing record already contains all 33 base-game trophies, trophy registration at the next game start reconciles platinum. Earlier trophies cannot be reconstructed from a game save alone. + +These are local records, with no PlayStation Network or Steam achievement sync. Importing other ports' trophy formats is outside this change. Game files and saves are not modified. + +## Implementation references + +The factual catalog and API layout references were [ayozetr/bloodborne_linux](https://github.com/ayozetr/bloodborne_linux) at `804651e418dc1e80b1dafdc83402106bbea954cd`: + +- `scripts/trophies.py` and `src/runtime_services.c`: IDs, grades, hidden flags, DLC grouping, and platinum conditions. +- Its shadPS4-derived `np_trophy.h` and `np_error.h`: structure layouts and error values (GPL-2.0-or-later, shadPS4 Emulator Project). + +Persistence, HLE handling, UI, and descriptive text are implemented for bbhost. No game images or keys are included; the notification cup is drawn with overlay primitives. diff --git a/include/bbhost_plugin.h b/include/bbhost_plugin.h index 090869a2..c6c7e5f0 100644 --- a/include/bbhost_plugin.h +++ b/include/bbhost_plugin.h @@ -1,4 +1,4 @@ -/* bbhost plugin API, version 29. +/* bbhost plugin API, version 30. * * A plugin is a shared library (.so on Linux, .dll on Windows) in * /plugins or /plugins. The host loads every one at start and @@ -38,7 +38,7 @@ extern "C" { #endif -#define BB_PLUGIN_API_VERSION 29 +#define BB_PLUGIN_API_VERSION 30 #if defined(_WIN32) #define BB_PLUGIN_EXPORT __declspec(dllexport) @@ -1196,6 +1196,10 @@ typedef struct BbHostApi { * on_view is not called while it is 1 (on_camera still is, so a plugin * can see it begin and end). Any thread. */ int (*cutscene)(void); + /* Version 30: main thread only. Pause campaign and chalice history while + * a practice plugin changes world state. Each plugin owns its pause; + * pass 0 to release it. Does not alter the game's save or play clock. */ + int (*campaign_tracking_pause)(const char* plugin, int paused); } BbHostApi; #define BB_SNAP_PIXELS 0xffffffffu /* version 18: scene_snap's grid the 3D's own pixels */ diff --git a/plugins/boss_rush/boss_rush.cpp b/plugins/boss_rush/boss_rush.cpp index 5a18d05d..c5f863b4 100755 --- a/plugins/boss_rush/boss_rush.cpp +++ b/plugins/boss_rush/boss_rush.cpp @@ -1219,6 +1219,9 @@ void tick() { if (g_test_practice) practice(); else begin(); } + if (g.api->version >= 30 && g.api->size >= offsetof(BbHostApi, campaign_tracking_pause) + sizeof(g.api->campaign_tracking_pause) && + g.api->campaign_tracking_pause) + g.api->campaign_tracking_pause("boss_rush", g_state != State::Waiting && g_state != State::Done); if (g_in_world && !g_banner.empty()) { g.message(g_banner, g_banner_s); g_banner.clear(); diff --git a/src/core/chalice_history.cpp b/src/core/chalice_history.cpp new file mode 100644 index 00000000..c9c45391 --- /dev/null +++ b/src/core/chalice_history.cpp @@ -0,0 +1,167 @@ +#include "core/chalice_history.h" +#include +#include +#include +#include +#include +#include + +namespace chalice_history { +namespace { +constexpr std::uint64_t kMaxCounter = 1ull << 50; +bool end(std::istringstream& in) { in >> std::ws; return in.eof(); } +int summary_id(int id) { + // Different dungeon templates use separate health-bar IDs for the same + // displayed boss. Keep encounter IDs exact; combine their boss totals. + if (id == 209010) return 209000; + if (id == 509010) return 509000; + return id; +} +Stats& stats(Encounter& e, int cycle) { + for (auto& s : e.stats) if (s.cycle == cycle) return s; + e.stats.push_back({cycle, {}}); return e.stats.back(); +} +} +std::string boss_name(int id) { + // Health-bar name IDs, including the multi-character Watchers event; + // NpcParam.nameId is different for several of these fights. + static const std::pair names[] = { + {1010, "Forgotten Madman"}, {106000, "Brainsucker"}, {127000, "Maneater Boar"}, + {209000, "Blood-starved Beast"}, {209010, "Blood-starved Beast"}, {216000, "Keeper of the Old Lords"}, + {218000, "Loran Silverbeast"}, {251010, "Ebrietas, Daughter of the Cosmos"}, {257010, "Celestial Emissary"}, + {304001, "Merciless Watchers"}, {305001, "Pthumerian Descendant"}, {305002, "Pthumerian Elder"}, + {306000, "Pthumerian Bride"}, {306001, "Yharnam, Pthumerian Queen"}, {313000, "Undead Giant"}, + {501000, "Watchdog of the Old Lords"}, {504010, "Abhorrent Beast"}, {508010, "Loran Darkbeast"}, + {509000, "Bloodletting Beast"}, {509010, "Bloodletting Beast"}, {510010, "Rom, the Vacuous Spider"}, + {512010, "Amygdala"}, {750000, "Beast-possessed Soul"}, + }; + for (const auto& [key, name] : names) if (key == id) return name; + return "Chalice boss #" + std::to_string(id); +} +Snapshot read(const std::filesystem::path& file) { + Snapshot out; + const auto bad = [&] { out.error = "Cannot read chalice history. The original file has not been changed."; return out; }; + std::error_code ec; + const bool exists = std::filesystem::exists(file, ec); + if (ec) return bad(); + if (!exists) return out; + if (!std::filesystem::is_regular_file(file, ec) || ec || std::filesystem::file_size(file, ec) > 8 * 1024 * 1024 || ec) return bad(); + std::ifstream in(file, std::ios::binary); std::string line; + if (!in || !std::getline(in, line) || line != "BBHOST_CHALICE_HISTORY 1") return bad(); + std::set ids; + Encounter* current = nullptr; + bool finished = false; + while (std::getline(in, line)) { + std::istringstream row(line); std::string kind; + if (!(row >> kind)) continue; + if (kind == "end") { if (!end(row)) return bad(); finished = true; break; } + if (kind == "encounter") { + Encounter e; int cleared, prior, active, blocked; + if (!(row >> e.id >> e.character >> e.altar >> e.layer >> e.name_id >> e.last_deaths >> cleared >> prior >> active >> blocked >> std::quoted(e.dungeon)) || + !end(row) || !e.id || e.id > kMaxCounter || !ids.insert(e.id).second || !e.character || e.character > kMaxCounter || + e.altar < 0 || e.altar > 6 || e.layer < 1 || e.layer > 4 || e.name_id <= 0 || e.name_id > 10000000 || + e.last_deaths > UINT32_MAX || cleared < 0 || cleared > 1 || prior < 0 || prior > 1 || + active < 0 || active > 1 || blocked < 0 || blocked > 1 || e.dungeon.empty() || e.dungeon.size() > 128 || + out.encounters.size() >= 10000 || (active && (cleared || blocked)) || (prior && !cleared)) return bad(); + e.cleared = cleared; e.prior_clear = prior; e.active = active; e.blocked = blocked; + out.encounters.push_back(std::move(e)); current = &out.encounters.back(); + } else if (kind == "stats") { + Stats s; int partial; + if (!current || !(row >> s.cycle >> s.count.attempts >> s.count.kills >> partial) || !end(row) || + s.cycle < 0 || s.cycle > 1000000 || s.count.attempts > kMaxCounter || s.count.kills > 1 || + partial < 0 || partial > 1 || (s.count.kills > s.count.attempts && !partial) || + current->stats.size() >= 10000 || (!current->stats.empty() && s.cycle <= current->stats.back().cycle)) return bad(); + s.count.partial = partial; current->stats.push_back(s); + } else return bad(); + } + while (std::getline(in, line)) if (line.find_first_not_of(" \r\t") != std::string::npos) return bad(); + if (in.bad() || !finished) return bad(); + for (const auto& e : out.encounters) { + std::uint64_t kills = 0, attempts = 0; + for (const auto& s : e.stats) { kills += s.count.kills; attempts += s.count.attempts; } + if (kills > 1 || (kills && !e.cleared) || (e.prior_clear && (kills || attempts)) || (e.active && !attempts) || + (!e.prior_clear && e.stats.empty())) return bad(); + } + return out; +} +std::vector totals(const Snapshot& state, std::uint64_t character, int cycle) { + std::map sums; + for (const auto& e : state.encounters) if (e.character == character) { + if (cycle < 0 && e.prior_clear) sums[summary_id(e.name_id)].partial = true; + for (const auto& s : e.stats) if (cycle < 0 || s.cycle == cycle) { + auto& t = sums[summary_id(e.name_id)]; t.attempts += s.count.attempts; t.kills += s.count.kills; + t.partial = t.partial || s.count.partial; + } + } + std::vector out; + for (const auto& [id, count] : sums) out.push_back({id, count}); + return out; +} +void Store::open(const std::filesystem::path& file) { + std::lock_guard lock(mutex_); file_ = file; state_ = read(file); readable_ = state_.error.empty(); dirty_ = false; +} +Snapshot Store::snapshot() const { std::lock_guard lock(mutex_); return state_; } +bool Store::save() { + if (!readable_) return false; + if (!dirty_) return true; + std::ostringstream out; out << "BBHOST_CHALICE_HISTORY 1\n"; + for (const auto& e : state_.encounters) { + out << "encounter " << e.id << ' ' << e.character << ' ' << e.altar << ' ' << e.layer << ' ' << e.name_id << ' ' << e.last_deaths + << ' ' << e.cleared << ' ' << e.prior_clear << ' ' << e.active << ' ' << e.blocked << ' ' << std::quoted(e.dungeon) << '\n'; + for (const auto& s : e.stats) out << "stats " << s.cycle << ' ' << s.count.attempts << ' ' << s.count.kills << ' ' << s.count.partial << '\n'; + } + out << "end\n"; + if (!play_history::write_history_file(file_, out.str())) { + state_.error = "Cannot save chalice history. Check free space and write permissions."; return false; + } + state_.error.clear(); dirty_ = false; return true; +} +bool Store::flush() { std::lock_guard lock(mutex_); return save(); } +void Store::observe(const Observation& o) { + std::lock_guard lock(mutex_); + if (!readable_) return; + if (!o.character || !o.in_world) { save(); return; } + if (o.character > kMaxCounter || o.cycle < 0 || o.cycle > 1000000 || o.deaths > UINT32_MAX || o.altar < 0 || o.altar > 6 || o.dungeon.size() > 128) return; + if (o.suspended) { + for (auto& e : state_.encounters) if (e.character == o.character && e.active) { e.active = false; dirty_ = true; } + save(); return; + } + for (const auto& boss : o.bosses) { + if (!boss.flags.valid || o.dungeon.empty() || boss.layer < 1 || boss.layer > 4 || boss.name_id <= 0 || boss.name_id > 10000000) continue; + Encounter* e = nullptr; + for (auto i = state_.encounters.rbegin(); i != state_.encounters.rend(); ++i) { + if (i->character == o.character && i->dungeon == o.dungeon && i->layer == boss.layer && i->name_id == boss.name_id) { e = &*i; break; } + } + // An observed cleared dungeon becoming uncleared is a new ritual or + // a replay of restored progress. Keep the previous clear intact. + const bool replay = e && e->cleared && !boss.flags.defeated; + if (!e || replay) { + Encounter next; + for (const auto& old : state_.encounters) next.id = std::max(next.id, old.id); + ++next.id; next.character = o.character; next.dungeon = o.dungeon; next.altar = o.altar; + next.layer = boss.layer; next.name_id = boss.name_id; next.last_deaths = o.deaths; + next.cleared = next.prior_clear = boss.flags.defeated; + if (!next.prior_clear) stats(next, o.cycle).count.partial = !replay; + state_.encounters.push_back(std::move(next)); e = &state_.encounters.back(); dirty_ = true; + } + if (e->cleared) continue; // no inherited clear when NG+ changes + const bool died = !o.alive || (e->active && o.deaths > e->last_deaths); + if (!boss.flags.begun) e->blocked = false; + if (boss.flags.defeated) { + auto& s = stats(*e, o.cycle).count; + if (!e->active || !s.attempts) s.partial = true; + ++s.kills; e->cleared = true; e->active = e->blocked = false; dirty_ = true; + } else if (e->active && (died || !boss.flags.begun)) { + e->active = false; e->blocked = boss.flags.begun; dirty_ = true; + } else if (!e->active && !e->blocked && boss.flags.begun && !died) { + ++stats(*e, o.cycle).count.attempts; e->active = true; dirty_ = true; + } + e->last_deaths = o.deaths; + } + for (auto& e : state_.encounters) if (e.character == o.character && e.active) { + if (o.dungeon != e.dungeon || !o.alive || o.deaths > e.last_deaths) { e.active = false; e.blocked = true; dirty_ = true; } + } + save(); +} +Store& runtime() { static Store store; return store; } +} diff --git a/src/core/chalice_history.h b/src/core/chalice_history.h new file mode 100644 index 00000000..8190ebaf --- /dev/null +++ b/src/core/chalice_history.h @@ -0,0 +1,48 @@ +// Chalice encounters stay independent of campaign clears: a dungeon can +// outlive an NG+ transition, and the same boss can appear in many dungeons. +#pragma once +#include "core/play_history.h" + +namespace chalice_history { +struct Stats { + int cycle = 0; + play_history::BossRecord count; +}; +struct Encounter { + std::uint64_t id = 0, character = 0, last_deaths = 0; + std::string dungeon; + int altar = 0, layer = 1, name_id = 0; + bool cleared = false, prior_clear = false, active = false, blocked = false; + std::vector stats; +}; +struct Snapshot { std::vector encounters; std::string error; }; +struct Boss { + int layer = 1, name_id = 0; + play_history::FightFlags flags; +}; +struct Observation { + std::uint64_t character = 0, deaths = 0; + int cycle = 0, altar = 0; + bool in_world = false, suspended = false, alive = true; + std::string dungeon; + std::vector bosses; +}; +struct Total { int name_id; play_history::BossRecord count; }; +Snapshot read(const std::filesystem::path& file); +std::vector totals(const Snapshot& state, std::uint64_t character, int cycle = -1); +std::string boss_name(int name_id); +class Store { +public: + void open(const std::filesystem::path& file); + void observe(const Observation& observation); + Snapshot snapshot() const; + bool flush(); +private: + bool save(); + mutable std::mutex mutex_; + std::filesystem::path file_; + Snapshot state_; + bool readable_ = true, dirty_ = false; +}; +Store& runtime(); +} diff --git a/src/core/play_history.cpp b/src/core/play_history.cpp new file mode 100644 index 00000000..246f26e4 --- /dev/null +++ b/src/core/play_history.cpp @@ -0,0 +1,296 @@ +#include "core/play_history.h" + +#include +#include +#include +#include +#include +#include +#include +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#include +#include +#else +#include +#endif + +namespace play_history { +namespace { +// Each begun event enables the AI and boss health bar. These are event +// completion flags, reset on rest/death, rather than the persistent "met" +// flags. Verified against the 1.09 map event scripts, including the endings. +const std::array kBosses{{ + {"Cleric Beast", 12411700, 12414702, 0x1801}, + {"Father Gascoigne", 12411800, 12414802, 0x1801}, + {"Blood-starved Beast", 12301800, 12304802, 0x1700}, + {"Vicar Amelia", 12401800, 12404802, 0x1800}, + {"The Witch of Hemwick", 12201800, 12204802, 0x1600}, + {"Darkbeast Paarl", 12301700, 12304702, 0x1700}, + {"Shadow of Yharnam", 12701800, 12704802, 0x1b00}, + {"Rom, the Vacuous Spider", 13201800, 13204802, 0x2000}, + {"The One Reborn", 12801800, 12804802, 0x1c00}, + {"Martyr Logarius", 12501800, 12504802, 0x1900}, + {"Amygdala", 13301800, 13304802, 0x2100}, + {"Celestial Emissary", 12421700, 12424702, 0x1802}, + {"Ebrietas, Daughter of the Cosmos", 12421800, 12424802, 0x1802}, + {"Micolash, Host of the Nightmare", 12601850, 12604852, 0x1a00}, + {"Mergo's Wet Nurse", 12601800, 12604802, 0x1a00}, + {"Gehrman, the First Hunter", 12101800, 12104802, 0x1500}, + {"Moon Presence", 12101850, 12104852, 0x1500}, + {"Ludwig, the Holy Blade", 13401800, 13404802, 0x2200}, + {"Living Failures", 13501850, 13504852, 0x2300}, + {"Lady Maria of the Astral Clocktower", 13501800, 13504802, 0x2300}, + {"Laurence, the First Vicar", 13401850, 13404852, 0x2200}, + {"Orphan of Kos", 13601800, 13604802, 0x2400}, +}}; +constexpr std::uint64_t kMaxCounter = 1ull << 50; +constexpr auto kReadError = "Cannot read play history. The original file has not been changed."; +constexpr auto kWriteError = "Cannot save play history. Check free space and write permissions."; + +bool persist(const std::filesystem::path& file, const std::string& text) { + if (file.empty()) return false; + std::error_code ec; + if (!file.parent_path().empty()) std::filesystem::create_directories(file.parent_path(), ec); + if (ec) return false; + auto temp = file; + temp += ".tmp-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); +#if defined(_WIN32) + auto* f = _wfopen(temp.c_str(), L"wb"); +#else + auto* f = std::fopen(temp.c_str(), "wb"); +#endif + if (!f) return false; + bool ok = std::fwrite(text.data(), 1, text.size(), f) == text.size() && std::fflush(f) == 0; +#if defined(_WIN32) + if (ok) ok = _commit(_fileno(f)) == 0; +#else + if (ok) ok = fdatasync(fileno(f)) == 0; +#endif + ok = std::fclose(f) == 0 && ok; + if (ok) { +#if defined(_WIN32) + ok = MoveFileExW(temp.c_str(), file.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; +#else + std::filesystem::rename(temp, file, ec); + ok = !ec; +#endif + } + if (!ok) std::filesystem::remove(temp, ec); + return ok; +} +bool end(std::istringstream& in) { in >> std::ws; return in.eof(); } +} + +const std::array& bosses() { return kBosses; } +bool write_history_file(const std::filesystem::path& file, const std::string& text) { return persist(file, text); } +std::string cycle_name(int n) { return n == 0 ? "NG (cycle 1)" : "NG+" + std::to_string(n) + " (cycle " + std::to_string(n + 1) + ")"; } +std::string duration(std::uint64_t ms) { + const auto s = ms / 1000; + char text[64]; + std::snprintf(text, sizeof text, "%llu:%02u:%02u", static_cast(s / 3600), + static_cast(s / 60 % 60), static_cast(s % 60)); + return text; +} +std::array totals(const Character& character) { + std::array result{}; + for (const auto& cycle : character.cycles) for (int i = 0; i < kBossCount; ++i) { + result[i].attempts += cycle.bosses[i].attempts; + result[i].kills += cycle.bosses[i].kills; + result[i].partial = result[i].partial || cycle.bosses[i].partial; + } + return result; +} + +Snapshot read(const std::filesystem::path& file) { + Snapshot result; + const auto bad = [&]() { result.error = kReadError; return result; }; + std::error_code ec; + const bool exists = std::filesystem::exists(file, ec); + if (ec) return bad(); + if (!exists) return result; + if (!std::filesystem::is_regular_file(file, ec) || ec || std::filesystem::file_size(file, ec) > 8 * 1024 * 1024 || ec) return bad(); + std::ifstream in(file, std::ios::binary); + std::string line; + if (!in || !std::getline(in, line) || line != "BBHOST_PLAY_HISTORY 1") return bad(); + Character* character = nullptr; + Cycle* cycle = nullptr; + std::set ids; + std::set rows; + while (std::getline(in, line)) { + std::istringstream row(line); + std::string kind; + if (!(row >> kind)) continue; + if (kind == "character") { + Character c; + if (!(row >> c.id >> c.slot >> c.created >> c.last_play_ms >> c.last_deaths >> c.active_boss >> c.ended_boss >> std::quoted(c.name)) || + !end(row) || !c.id || c.id > kMaxCounter || !ids.insert(c.id).second || c.slot < 0 || c.slot >= 10 || c.created < 0 || + c.last_play_ms > UINT32_MAX || c.last_deaths > UINT32_MAX || c.active_boss < -1 || c.active_boss >= kBossCount || + c.ended_boss < -1 || c.ended_boss >= kBossCount || c.name.size() > 256 || result.characters.size() >= 1000 || + (character && (character->cycles.empty() || rows.size() != kBossCount))) return bad(); + result.characters.push_back(std::move(c)); + character = &result.characters.back(); cycle = nullptr; + } else if (kind == "cycle") { + Cycle c; int complete, partial; + if (!character || !(row >> c.number >> c.elapsed_ms >> complete >> partial) || !end(row) || + c.number < 0 || c.number > 1000000 || c.elapsed_ms > kMaxCounter || + (complete != 0 && complete != 1) || (partial != 0 && partial != 1) || + character->cycles.size() >= 10000 || (cycle && (!cycle->complete || c.number <= cycle->number || rows.size() != kBossCount))) return bad(); + c.complete = complete; c.partial_time = partial; + character->cycles.push_back(c); cycle = &character->cycles.back(); rows.clear(); + } else if (kind == "boss") { + int i, partial; BossRecord b; + if (!cycle || !(row >> i >> b.attempts >> b.kills >> partial) || !end(row) || + i < 0 || i >= kBossCount || !rows.insert(i).second || b.attempts > kMaxCounter || b.kills > 1 || + (partial != 0 && partial != 1) || (b.kills > b.attempts && !partial)) return bad(); + b.partial = partial; cycle->bosses[i] = b; + } else return bad(); + } + if (in.bad() || (character && (character->cycles.empty() || rows.size() != kBossCount))) return bad(); + for (const auto& c : result.characters) if (c.active_boss >= 0 && + (c.cycles.back().bosses[c.active_boss].kills || !c.cycles.back().bosses[c.active_boss].attempts)) return bad(); + return result; +} + +void Store::open(const std::filesystem::path& file) { + std::lock_guard lock(mutex_); + file_ = file; state_ = read(file); readable_ = state_.error.empty(); + connected_ = suspended_ = dirty_ = false; selected_ = pending_ms_ = 0; +} +Snapshot Store::snapshot() const { std::lock_guard lock(mutex_); return state_; } +std::uint64_t Store::current_character_id() const { + std::lock_guard lock(mutex_); + return readable_ && connected_ && state_.error.empty() ? selected_ : 0; +} +bool Store::save() { + if (!readable_) return false; + if (!dirty_) return true; + std::ostringstream out; + out << "BBHOST_PLAY_HISTORY 1\n"; + for (const auto& c : state_.characters) { + out << "character " << c.id << ' ' << c.slot << ' ' << c.created << ' ' << c.last_play_ms << ' ' << c.last_deaths << ' ' + << c.active_boss << ' ' << c.ended_boss << ' ' << std::quoted(c.name) << '\n'; + for (const auto& cy : c.cycles) { + out << "cycle " << cy.number << ' ' << cy.elapsed_ms << ' ' << cy.complete << ' ' << cy.partial_time << '\n'; + for (int i = 0; i < kBossCount; ++i) { + const auto& b = cy.bosses[i]; + out << "boss " << i << ' ' << b.attempts << ' ' << b.kills << ' ' << b.partial << '\n'; + } + } + } + if (!persist(file_, out.str())) { state_.error = kWriteError; return false; } + state_.error.clear(); dirty_ = false; pending_ms_ = 0; + return true; +} +bool Store::flush() { std::lock_guard lock(mutex_); return save(); } + +void Store::observe(const Observation& o) { + std::lock_guard lock(mutex_); + if (!readable_) return; + if (!o.valid) { + if (connected_) save(); + connected_ = false; + return; + } + if (o.slot < 0 || o.slot >= 10 || o.cycle < 0 || o.cycle > 1000000 || o.play_ms > UINT32_MAX || o.deaths > UINT32_MAX) return; + Character* c = nullptr; + for (auto it = state_.characters.rbegin(); it != state_.characters.rend(); ++it) { + if (it->slot == o.slot) { c = &*it; break; } + } + // A load may reset the managers temporarily. Only accept monotonic + // counters from the character already connected, never a title's zeroes. + if (!o.in_world && (!connected_ || !c || selected_ != c->id || o.cycle < c->cycles.back().number || + o.play_ms < c->last_play_ms || o.deaths < c->last_deaths)) { save(); return; } + bool fresh = false, event = false; + // A replaced character or restored older save gets its own history. The + // old branch remains reviewable and never silently loses or gains kills. + // Window-close/crash can precede the guest's next autosave. A small + // rewind resumes the existing history, with a new clock baseline. + // A fresh NG character or a substantially older save gets a new branch. + const bool rollback = c && (o.cycle < c->cycles.back().number || o.play_ms + 300000 < c->last_play_ms || + (o.cycle == 0 && o.play_ms < 5000 && c->last_play_ms > 5000 && + !o.name.empty() && !c->name.empty() && o.name != c->name)); + if (!c || rollback) { + Character next; + for (const auto& old : state_.characters) next.id = std::max(next.id, old.id); + ++next.id; next.slot = o.slot; next.name = o.name; next.created = std::max(0, o.when); + next.last_play_ms = o.play_ms; next.last_deaths = o.deaths; + Cycle cy; cy.number = o.cycle; cy.partial_time = o.cycle != 0 || o.play_ms >= kPlayTimeCap; + // For NG the save's total playtime is the whole first cycle. Earlier + // NG+ boundaries cannot be recovered from a lifetime counter. + cy.elapsed_ms = o.cycle == 0 ? o.play_ms : 0; + for (auto& b : cy.bosses) b.partial = o.play_ms > 5000 || o.cycle != 0; + next.cycles.push_back(cy); + state_.characters.push_back(std::move(next)); c = &state_.characters.back(); + fresh = event = true; + } + const bool attaching = !connected_ || selected_ != c->id || suspended_; + selected_ = c->id; + connected_ = true; + auto delta = o.play_ms >= c->last_play_ms ? o.play_ms - c->last_play_ms : 0; + if (attaching && !fresh && (delta > 1000 || o.deaths > c->last_deaths)) { + // Play in another build, or a missing checkpoint, may contain failed + // fights whose flags were reset. Those attempts cannot be recovered. + for (auto& b : c->cycles.back().bosses) if (!b.kills) b.partial = true; + } + // Continue past the native limit with measured world time. A title, + // load or offline interval must never enter this fallback. + if (!attaching && c->last_play_ms >= kPlayTimeCap && o.play_ms >= kPlayTimeCap) delta += o.capped_delta_ms; + const bool missed_boundary = o.cycle > c->cycles.back().number && (attaching || o.cycle != c->cycles.back().number + 1); + if (!o.suspended && o.own_world && !suspended_ && !fresh && !missed_boundary) c->cycles.back().elapsed_ms += delta; + pending_ms_ += delta; + c->last_play_ms = attaching ? o.play_ms : std::max(c->last_play_ms, o.play_ms); + if (!o.name.empty()) c->name = o.name; + if (o.cycle > c->cycles.back().number) { + auto& previous = c->cycles.back(); + previous.partial_time = previous.partial_time || missed_boundary; + previous.complete = true; + Cycle next; next.number = o.cycle; + next.partial_time = missed_boundary || o.suspended || suspended_; + for (auto& b : next.bosses) b.partial = next.partial_time; + c->cycles.push_back(next); c->active_boss = c->ended_boss = -1; event = true; + } + auto& cy = c->cycles.back(); + if (!o.in_world) { dirty_ = true; if (event || pending_ms_ >= 10000) save(); return; } + if (o.suspended || !o.own_world) { + // Practice rewrites defeat/begun flags and may grant rewards. Discard + // that interval and rebaseline flags on return to campaign play. + c->active_boss = c->ended_boss = -1; + c->last_deaths = o.deaths; + suspended_ = true; dirty_ = true; + if (event || pending_ms_ >= 10000) save(); + return; + } + suspended_ = false; + const bool died = o.deaths > c->last_deaths || !o.alive; + // A win takes priority over a simultaneous player death. + for (int i = 0; i < kBossCount; ++i) { + const auto& f = o.flags[i]; auto& b = cy.bosses[i]; + if (!f.valid) continue; + if (!f.begun && c->ended_boss == i) c->ended_boss = -1; + if (f.defeated && !b.kills) { + if (c->active_boss != i) { + b.partial = true; // already defeated or the fight's start was unobserved + } + b.kills = 1; if (c->active_boss == i) c->active_boss = -1; + event = true; + } + } + if (c->active_boss >= 0) { + const auto i = c->active_boss; const auto& f = o.flags[i]; + if (died || kBosses[i].block != (o.block >> 16) || (f.valid && !f.begun)) { + c->active_boss = -1; c->ended_boss = f.valid && !f.begun ? -1 : i; event = true; + } + } + if (!died && c->active_boss < 0) for (int i = 0; i < kBossCount; ++i) { + const auto& f = o.flags[i]; auto& b = cy.bosses[i]; + if (kBosses[i].block == (o.block >> 16) && f.valid && f.begun && !f.defeated && !b.kills && c->ended_boss != i) { + ++b.attempts; c->active_boss = i; event = true; break; + } + } + c->last_deaths = o.deaths; + dirty_ = true; + if (event || pending_ms_ >= 10000) save(); +} +Store& runtime() { static Store store; return store; } +} // namespace play_history diff --git a/src/core/play_history.h b/src/core/play_history.h new file mode 100644 index 00000000..bb775205 --- /dev/null +++ b/src/core/play_history.h @@ -0,0 +1,76 @@ +// Local campaign records. Observations contain no guest pointers; the state +// machine and persistence are also usable by tests without a running game. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace play_history { +constexpr int kBossCount = 22; // 17 story bosses, five DLC bosses; chalices do not reset with NG+ +constexpr std::uint64_t kPlayTimeCap = 0xd693a018ull; // native accumulator: 999:59:59 +struct BossInfo { + const char* name; + std::uint32_t defeated, begun, block; // block: packed map's upper 16 bits +}; +const std::array& bosses(); +struct BossRecord { + std::uint64_t attempts = 0, kills = 0; + bool partial = false; // attempts before tracking began are unknown +}; +struct Cycle { + int number = 0; // NG = 0, NG+ = 1 + std::uint64_t elapsed_ms = 0; + bool complete = false, partial_time = false; + std::array bosses{}; +}; +struct Character { + std::uint64_t id = 0; + int slot = 0; + std::string name; + std::int64_t created = 0; + std::uint64_t last_play_ms = 0, last_deaths = 0; + int active_boss = -1, ended_boss = -1; + std::vector cycles; +}; +struct Snapshot { + std::vector characters; + std::string error; +}; +struct FightFlags { bool valid = false, defeated = false, begun = false; }; +struct Observation { + bool valid = false, in_world = false, own_world = true, suspended = false, alive = true; + int slot = -1, cycle = 0; + std::string name; + std::int64_t when = 0; + std::uint64_t play_ms = 0, deaths = 0, capped_delta_ms = 0; + std::uint32_t block = 0; + std::array flags{}; +}; +Snapshot read(const std::filesystem::path& file); +std::array totals(const Character& character); +std::string cycle_name(int cycle); +std::string duration(std::uint64_t ms); +// Shared atomic persistence for the two independent history files. +bool write_history_file(const std::filesystem::path& file, const std::string& text); + +class Store { +public: + void open(const std::filesystem::path& file); + void observe(const Observation& observation); + bool flush(); + Snapshot snapshot() const; + std::uint64_t current_character_id() const; +private: + bool save(); // mutex held; malformed/future files are never overwritten + mutable std::mutex mutex_; + std::filesystem::path file_; + Snapshot state_; + bool readable_ = true, dirty_ = false, connected_ = false, suspended_ = false; + std::uint64_t selected_ = 0, pending_ms_ = 0; +}; +Store& runtime(); +} // namespace play_history diff --git a/src/core/trophies.cpp b/src/core/trophies.cpp new file mode 100644 index 00000000..fe3f72fd --- /dev/null +++ b/src/core/trophies.cpp @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Catalog reference: ayozetr/bloodborne_linux scripts/trophies.py +// (804651e4, GPL-2.0-or-later). See docs/trophies.md for provenance. +#include "core/trophies.h" + +#include +#include +#include +#include +#include +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#include +#include +#else +#include +#endif + +namespace trophies { +namespace { +using G = Grade; +const std::array kCatalog{{ + {G::Platinum, false, "Bloodborne", "Earn every base-game trophy."}, + {G::Gold, true, "Yharnam Sunrise", "Finish the night of the hunt and see the dawn."}, + {G::Gold, true, "Honoring Wishes", "Take over the watch of the Hunter's Dream."}, + {G::Gold, true, "Childhood's Beginning", "Awaken as a new Great One."}, + {G::Gold, true, "Yharnam, Pthumerian Queen", "Defeat Queen Yharnam in the ancient underground ruins."}, + {G::Gold, false, "Hunter's Essence", "Collect every hunter weapon from the base game."}, + {G::Gold, false, "Hunter's Craft", "Collect every special hunter tool from the base game."}, + {G::Silver, false, "Weapon Master", "Upgrade a weapon to its highest level."}, + {G::Silver, false, "Blood Gem Master", "Find a very rare blood gem."}, + {G::Silver, false, "Rune Master", "Find a very rare Caryll rune."}, + {G::Silver, true, "Cainhurst", "Reach the abandoned castle of Cainhurst."}, + {G::Silver, true, "The Choir", "Reach the domain of the Choir, high within the Healing Church."}, + {G::Silver, true, "The Source of the Dream", "Discover the old workshop on which the Hunter's Dream was based."}, + {G::Silver, true, "Nightmare Lecture Building", "Reach the lecture building within the nightmare."}, + {G::Bronze, true, "Father Gascoigne", "Defeat Father Gascoigne."}, + {G::Bronze, true, "Vicar Amelia", "Defeat Vicar Amelia."}, + {G::Bronze, true, "Shadow of Yharnam", "Defeat Shadow of Yharnam."}, + {G::Bronze, true, "Rom, the Vacuous Spider", "Defeat Rom, the Vacuous Spider."}, + {G::Bronze, true, "The One Reborn", "Defeat The One Reborn."}, + {G::Bronze, true, "Micolash, Host of the Nightmare", "Defeat Micolash, Host of the Nightmare."}, + {G::Bronze, true, "Mergo's Wet Nurse", "Defeat Mergo's Wet Nurse."}, + {G::Bronze, true, "Cleric Beast", "Defeat Cleric Beast."}, + {G::Bronze, true, "Blood-starved Beast", "Defeat Blood-starved Beast."}, + {G::Bronze, true, "The Witch of Hemwick", "Defeat The Witch of Hemwick."}, + {G::Bronze, true, "Darkbeast Paarl", "Defeat Darkbeast Paarl."}, + {G::Bronze, true, "Amygdala", "Defeat Amygdala."}, + {G::Bronze, true, "Martyr Logarius", "Defeat Martyr Logarius."}, + {G::Bronze, true, "Celestial Emissary", "Defeat Celestial Emissary."}, + {G::Bronze, true, "Ebrietas, Daughter of the Cosmos", "Defeat Ebrietas, Daughter of the Cosmos."}, + {G::Bronze, false, "Blood Gem Contact", "Find your first blood gem for strengthening a weapon."}, + {G::Bronze, false, "Rune Contact", "Find your first Caryll rune."}, + {G::Bronze, false, "Chalice of Pthumeru", "Obtain the chalice that opens the Pthumerian ruins."}, + {G::Bronze, true, "Chalice of Ailing Loran", "Obtain the chalice that opens the Loran ruins."}, + {G::Bronze, true, "Chalice of Isz", "Obtain the great chalice that opens the Isz ruins."}, + {G::Gold, false, "Old Hunter's Essence", "Collect every old hunter weapon from the expansion."}, + {G::Silver, true, "Orphan of Kos", "Defeat Orphan of Kos."}, + {G::Bronze, true, "Ludwig, the Holy Blade", "Defeat Ludwig."}, + {G::Bronze, true, "Lady Maria of the Astral Clocktower", "Defeat Lady Maria of the Astral Clocktower."}, + {G::Bronze, true, "Living Failures", "Defeat Living Failures."}, + {G::Bronze, true, "Laurence, the First Vicar", "Defeat Laurence, the First Vicar."}, +}}; +constexpr std::int64_t kLatestTimestamp = 253402300799ll; // end of year 9999 + +Snapshot load(const std::filesystem::path& file, std::string* original) { + Snapshot result; + original->clear(); + std::error_code ec; + const bool exists = std::filesystem::exists(file, ec); + if (ec || (exists && (!std::filesystem::is_regular_file(file, ec) || ec))) { + result.error = "Cannot read the trophy record. Check its location."; + return result; + } + if (!exists) return result; + if (std::filesystem::file_size(file, ec) > 1024 * 1024 || ec) { + result.error = "The trophy record is too large or unreadable."; + return result; + } + std::ifstream in(file, std::ios::binary); + if (!in) { result.error = "Cannot open the trophy record."; return result; } + *original = std::string(std::istreambuf_iterator(in), {}); + if (in.bad()) { result.error = "Reading the trophy record failed."; return result; } + std::istringstream lines(*original); + std::string line; + while (std::getline(lines, line)) { + std::istringstream entry(line); + int id; std::int64_t when; + if (entry >> id >> when && id >= 0 && id < kCount && when > 0 && when <= kLatestTimestamp && !result.earned[id]) + result.earned[id] = when; + } + return result; +} + +bool persist(const std::filesystem::path& file, const std::string& text) { + if (file.empty()) return false; + std::error_code ec; + if (!file.parent_path().empty()) std::filesystem::create_directories(file.parent_path(), ec); + if (ec) return false; + if (std::filesystem::exists(file, ec)) { + auto backup = file; backup += ".pre-trophies.bak"; + std::filesystem::copy_file(file, backup, std::filesystem::copy_options::skip_existing, ec); + if (ec) return false; + } + auto temp = file; + temp += ".tmp-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); +#if defined(_WIN32) + std::FILE* f = _wfopen(temp.c_str(), L"wb"); +#else + std::FILE* f = std::fopen(temp.c_str(), "wb"); +#endif + if (!f) return false; + bool ok = std::fwrite(text.data(), 1, text.size(), f) == text.size() && std::fflush(f) == 0; +#if defined(_WIN32) + if (ok) ok = _commit(_fileno(f)) == 0; +#else + if (ok) ok = fdatasync(fileno(f)) == 0; +#endif + ok = std::fclose(f) == 0 && ok; + if (ok) { +#if defined(_WIN32) + ok = MoveFileExW(temp.c_str(), file.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; +#else + std::filesystem::rename(temp, file, ec); + ok = !ec; +#endif + } + if (!ok) std::filesystem::remove(temp, ec); + return ok; +} +bool platinum_due(const Snapshot& s) { + return !s.earned[0] && std::all_of(s.earned.begin() + 1, s.earned.begin() + kBaseCount, + [](auto when) { return when > 0; }); +} +} // namespace + +const std::array& catalog() { return kCatalog; } +const char* grade_name(Grade g) { + switch (g) { + case Grade::Platinum: return "Platinum"; + case Grade::Gold: return "Gold"; + case Grade::Silver: return "Silver"; + default: return "Bronze"; + } +} +int Snapshot::count(int begin, int end) const { + begin = std::clamp(begin, 0, kCount); + end = std::clamp(end, begin, kCount); + return std::count_if(earned.begin() + begin, earned.begin() + end, + [](auto t) { return t > 0; }); +} +Snapshot read(const std::filesystem::path& file) { std::string text; return load(file, &text); } +void Store::open(const std::filesystem::path& file) { + std::lock_guard lock(mutex_); + file_ = file; notices_.clear(); state_ = read(file_); +} +Snapshot Store::snapshot() const { std::lock_guard lock(mutex_); return state_; } +Unlock Store::unlock(int id, std::int64_t when) { + if (id < 0 || id >= kCount) return {Status::InvalidId}; + if (id == 0) return {Status::AutomaticPlatinum}; + return update(id, when); +} +Unlock Store::reconcile_platinum(std::int64_t when) { return update(-1, when); } +Unlock Store::update(int id, std::int64_t when) { + std::lock_guard lock(mutex_); + if (when <= 0 || when > kLatestTimestamp || file_.empty()) return {Status::IoError}; + std::string text; + state_ = load(file_, &text); + if (!state_.error.empty()) return {Status::IoError}; + if (id >= 0 && state_.earned[id]) return {Status::AlreadyUnlocked}; + Snapshot next = state_; + if (id >= 0) next.earned[id] = when; + const bool platinum = platinum_due(next); + if (id < 0 && !platinum) return {Status::Ok}; + if (platinum) next.earned[0] = when; + if (!text.empty() && text.back() != '\n') text += '\n'; + if (id >= 0) text += std::to_string(id) + " " + std::to_string(when) + "\n"; + if (platinum) text += "0 " + std::to_string(when) + "\n"; + if (!persist(file_, text)) { + state_.error = "Cannot save trophies. Check free space and write permissions."; + return {Status::IoError}; + } + state_ = next; + if (id >= 0) notices_.push_back(id); + if (platinum) notices_.push_back(0); + return {Status::Ok, platinum ? 0 : -1}; +} +int Store::pop_notice() { + std::lock_guard lock(mutex_); + if (notices_.empty()) return -1; + const int id = notices_.front(); notices_.pop_front(); return id; +} +Store& runtime() { static Store store; return store; } +} // namespace trophies diff --git a/src/core/trophies.h b/src/core/trophies.h new file mode 100644 index 00000000..bd1592e9 --- /dev/null +++ b/src/core/trophies.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace trophies { +constexpr int kCount = 40; +constexpr int kBaseCount = 34; // platinum plus 33 base-game trophies; DLC is 34–39 +enum class Grade : int { Platinum = 1, Gold = 2, Silver = 3, Bronze = 4 }; +struct Info { Grade grade; bool hidden; const char* name; const char* description; }; +const std::array& catalog(); +const char* grade_name(Grade grade); +struct Snapshot { + std::array earned{}; + std::string error; + int count(int begin = 0, int end = kCount) const; +}; +Snapshot read(const std::filesystem::path& file); +enum class Status { Ok, AlreadyUnlocked, InvalidId, AutomaticPlatinum, IoError }; +struct Unlock { Status status; int platinum = -1; }; + +// Preserves legacy records; backs up once and replaces atomically. +class Store { +public: + void open(const std::filesystem::path& file); + Snapshot snapshot() const; + Unlock unlock(int id, std::int64_t when); + Unlock reconcile_platinum(std::int64_t when); + int pop_notice(); // -1 when empty; only successful new unlocks are queued +private: + Unlock update(int id, std::int64_t when); + mutable std::mutex mutex_; + std::filesystem::path file_; + Snapshot state_; + std::deque notices_; +}; +Store& runtime(); +} // namespace trophies diff --git a/src/engine/chalice_history.h b/src/engine/chalice_history.h new file mode 100644 index 00000000..63d87f6f --- /dev/null +++ b/src/engine/chalice_history.h @@ -0,0 +1,46 @@ +// Read the live event instances. Root dungeons select several room scripts; +// their running event arguments identify the actual boss and layer without +// guessing from an NPC model or scanning every possible room on disk. +#pragma once +#include "bbhost/engine/sprj/emk_system.hpp" +#include +#include +#include + +namespace chalice_events { +struct Source { std::uint32_t name_id, defeated, begun; int layer; }; +template +bool sources(std::uint64_t system, std::uint64_t interpreter_vtable, const Read& read, std::vector& out) { + std::map, Source> found; + std::set visited; + for (std::uint64_t lane : {0u, 8u}) { + std::uint64_t node = 0; + if (!system || !read(system + lane, &node)) return false; + while (node) { + if (visited.size() >= 32768 || !visited.insert(node).second) return false; + bb::SprjEmkEventCore core{}; + if (!read(node, &core)) return false; + if (reinterpret_cast(core.vtable) == interpreter_vtable && !core.is_retired() && + (core.event_id == 12906806 || core.event_id == 12906795)) { + struct Arguments { std::uint32_t size, padding; std::uint64_t data; } arguments{}; + if (!read(node + offsetof(bb::SprjEmkEventIns, argument_size), &arguments)) return false; + if (arguments.size >= 20 && arguments.size <= 256) { + std::uint32_t values[5]{}; + if (!arguments.data || !read(arguments.data, &values)) return false; + // entity, health-bar name, defeat flag, fight-begun flag, + // battle-finished flag. Watchers adds its other actors. + if (values[1] && values[1] <= 10000000 && values[2] >= 12901800 && values[2] <= 12901803 && + values[3] >= 12900000 && values[3] < 12910000) { + Source s{values[1], values[2], values[3], static_cast(values[2] - 12901800 + 1)}; + found[{s.defeated, s.name_id}] = s; + } + } + } + node = reinterpret_cast(core.next); + } + } + out.clear(); + for (const auto& [key, value] : found) out.push_back(value); + return true; +} +} diff --git a/src/engine/event_flags.cpp b/src/engine/event_flags.cpp index e2461c1e..dc83fa75 100755 --- a/src/engine/event_flags.cpp +++ b/src/engine/event_flags.cpp @@ -1,3 +1,4 @@ +#include "engine/play_history.h" #include "engine/event_flags.h" #include "core/elf.h" @@ -101,6 +102,7 @@ void event_flags_tick() { for (std::size_t i = 0; i < n; ++i) { if (g_log) host_log("event flag %u -> %u", changes[i].id, changes[i].value); plugins_event_flag(changes[i].id, changes[i].value != 0); + play_history_event_flag(changes[i].id, changes[i].value != 0); } g_logged += n; } diff --git a/src/engine/frame_rate.cpp b/src/engine/frame_rate.cpp index fb8dd14d..0dff735a 100755 --- a/src/engine/frame_rate.cpp +++ b/src/engine/frame_rate.cpp @@ -1,3 +1,4 @@ +#include "engine/play_history.h" #include "guest_abi.h" #include "engine/frame_rate.h" #include "engine/frame_rate_step.h" @@ -1894,6 +1895,7 @@ GUEST_ABI std::int64_t frame_manager_hook(std::uint64_t, const std::uint64_t* sa rebirth_tick(); // the altar's rebirth: the host's half of its talk script (engine/rebirth.h) world_chr_tick(); // a test warp a plugin queued this frame (BBHOST_TEST_WARP, engine/world_chr.h) loading_tick(hle_video_flip_count()); // the loading screens' lengths and the first in-game frame (engine/loading.h) + play_history_tick(); // after plugins and loading state auto* f = reinterpret_cast(static_cast(saved[5])); // A rate or an effect timing chosen in the menus since the last frame; from // the game's own 30, the conversion the start would have made. diff --git a/src/engine/play_history.cpp b/src/engine/play_history.cpp new file mode 100644 index 00000000..0940999e --- /dev/null +++ b/src/engine/play_history.cpp @@ -0,0 +1,230 @@ +#include "engine/play_history.h" + +#include "bbhost/engine/sprj/game_state_man.hpp" +#include "bbhost/engine/sprj/game_data_man.hpp" +#include "bbhost/engine/sprj/world_chr_man.hpp" +#include "core/elf.h" +#include "core/play_history.h" +#include "core/chalice_history.h" +#include "core/portable.h" +#include "decomp/events/flag_store.h" +#include "engine/addr.h" +#include "engine/event_flags.h" +#include "engine/loading.h" +#include "engine/player_data.h" +#include "engine/world_chr.h" +#include "engine/chalice_history.h" +#include "bbhost/engine/cs/dungeon_ritual_helper.hpp" +#include "log.h" + +#include +#include +#include +#include +#include + +namespace { +std::uint64_t g_slide = 0; +std::set g_pauses; // main thread only +std::array g_flags{}; +std::chrono::steady_clock::time_point g_polled{}; +bool g_was_world = false; +int g_last_slot = -1, g_last_cycle = -1; +std::vector g_chalice_sources; +std::string g_chalice_key; +int g_chalice_altar = 0; +std::chrono::steady_clock::time_point g_chalice_polled{}; + +template bool read_at(std::uint64_t at, T* value) { + return at && host_read_safe(reinterpret_cast(static_cast(at)), value, sizeof(T)); +} +std::uint64_t pointer(std::uint64_t at) { std::uint64_t value = 0; read_at(at, &value); return value; } + +bool flag_bits(std::uint32_t first, std::size_t size, std::uint64_t* value) { + std::uint32_t ids[64]{}; bool bits[64]{}; + if (!size || size > 64) return false; + for (std::size_t i = 0; i < size; ++i) ids[i] = first + static_cast(i); + if (!event_flags_get(ids, size, bits)) return false; + *value = 0; + for (std::size_t i = 0; i < size; ++i) *value = (*value << 1) | bits[i]; + return true; +} +bool dungeon_key(std::string* key, int* altar) { + std::uint64_t selector = 0, uid = 0; std::uint32_t bank = 0; + if (!flag_bits(bb::DUNGEON_ALTAR_SELECTOR_FLAG, 7, &selector) || + !bb::dungeon_altar_bank_from_selector(static_cast(selector), bank)) return false; + const auto offset = bank * bb::DUNGEON_ALTAR_FLAG_STRIDE; + if (!flag_bits(bb::DUNGEON_ALTAR_MAP_UID_FLAG + offset, 32, &uid) || uid == UINT32_MAX || (uid >> 24) != 29) return false; + std::uint64_t hash = 14695981039346656037ull; + const auto add = [&](std::uint64_t word) { for (int i = 0; i < 8; ++i) { hash ^= (word >> (i * 8)) & 255; hash *= 1099511628211ull; } }; + // Server database IDs can be assigned after an offline ritual. The map, + // chalice and rites remain stable through that online/offline change. + std::uint64_t chalice = 0; + if (!flag_bits(bb::DUNGEON_ALTAR_HOLYGRAIL_EX_PARAM_FLAG + offset, 32, &chalice)) return false; + add(chalice); + for (int i = 0; i < 9; ++i) { + std::uint64_t pair = 0; + if (!flag_bits(bb::DUNGEON_ALTAR_FEATURE_PAIRS_FLAG + offset + 64u * i, 64, &pair)) return false; + add(pair); + } + char text[64]; + std::snprintf(text, sizeof text, "%u-%08x-%016llx", bank, static_cast(uid), static_cast(hash)); + *key = text; *altar = static_cast(bank); return true; +} +void chalice_tick(const play_history::Observation& game, bool entered) { + chalice_history::Observation o; + o.character = play_history::runtime().current_character_id(); o.cycle = game.cycle; o.deaths = game.deaths; + o.in_world = game.valid && game.in_world; o.alive = game.alive; o.suspended = game.suspended || !game.own_world; + if (o.in_world && !o.suspended && (game.block >> 24) == 29) { + if (entered) { g_chalice_sources.clear(); g_chalice_key.clear(); } + const auto now = std::chrono::steady_clock::now(); + if (entered || now - g_chalice_polled >= std::chrono::seconds(1)) { + std::string key; int altar; + if (dungeon_key(&key, &altar)) { + // Altar selection can change before the old world finishes + // fading out. Its still-running events belong to the old + // dungeon. Wait for a world entry before changing identity. + if (!entered && !g_chalice_key.empty() && key != g_chalice_key) { + o.in_world = false; + chalice_history::runtime().observe(o); + return; + } + if (key != g_chalice_key) g_chalice_sources.clear(); + g_chalice_key = key; g_chalice_altar = altar; + const auto system = pointer(g_slide + bb::SPRJ_EMK_SYSTEM_SINGLETON_PTR.rva); + std::vector sources; + const auto safe = [](std::uint64_t at, auto* out) { return read_at(at, out); }; + if (chalice_events::sources(system, g_slide + bb::SprjEmkEventIns::VTABLE.rva, safe, sources)) { + // Completed events leave the active list. Keep their flag + // mapping until this dungeon is left, including the win. + for (const auto& s : sources) { + const auto same = [&](const auto& v) { return v.defeated == s.defeated && v.name_id == s.name_id; }; + if (std::none_of(g_chalice_sources.begin(), g_chalice_sources.end(), same)) g_chalice_sources.push_back(s); + } + if (entered || (!sources.empty() && g_chalice_sources.size() == sources.size())) { + static std::string last; + const auto note = key + ":" + std::to_string(g_chalice_sources.size()); + if (note != last) { last = note; host_log("chalice history: altar %d, %zu boss layers identified", altar, g_chalice_sources.size()); } + } + } + } + g_chalice_polled = now; + } + o.dungeon = g_chalice_key; o.altar = g_chalice_altar; + for (const auto& s : g_chalice_sources) { + const std::uint32_t ids[]{s.defeated, s.begun}; bool bits[2]{}; + const bool valid = event_flags_get(ids, 2, bits); + o.bosses.push_back({s.layer, static_cast(s.name_id), {valid, bits[0], bits[1]}}); + } + } + chalice_history::runtime().observe(o); +} + +std::string character_name(std::uint64_t data, int slot) { + const auto store = pointer(data + offsetof(bb::GameDataMan, unknown_data_58)); + std::uint16_t name[17]{}; + if (!store || !read_at(store + 0x20 + sizeof(bb::GameDataCharacterSummary) * slot, &name)) return {}; + std::string text; + for (int i = 0; i < 16 && name[i]; ++i) { + std::uint32_t ch = name[i]; + if (ch >= 0xd800 && ch <= 0xdbff && i + 1 < 16 && name[i + 1] >= 0xdc00 && name[i + 1] <= 0xdfff) + ch = 0x10000 + ((ch - 0xd800) << 10) + (name[++i] - 0xdc00); + else if (ch >= 0xd800 && ch <= 0xdfff) ch = 0xfffd; + if (ch < 0x20) ch = ' '; + if (ch < 0x80) text += static_cast(ch); + else { + if (ch >= 0x10000) { text += static_cast(0xf0 | (ch >> 18)); text += static_cast(0x80 | ((ch >> 12) & 63)); } + else if (ch >= 0x800) text += static_cast(0xe0 | (ch >> 12)); + if (ch < 0x800) text += static_cast(0xc0 | (ch >> 6)); + else text += static_cast(0x80 | ((ch >> 6) & 63)); + text += static_cast(0x80 | (ch & 63)); + } + } + return text; +} +} + +void play_history_install(ElfImage* image) { + g_slide = image && image->sha256 == kEboot109Sha256 ? image->mem.slide : 0; + if (g_slide) event_flag_watch(true); +} +int play_history_pause(const char* plugin, int paused) { + if (!plugin || !plugin[0]) return 1; + if (paused) g_pauses.insert(plugin); + else g_pauses.erase(plugin); + return 0; +} +void play_history_event_flag(std::uint32_t id, bool value) { + for (int i = 0; i < play_history::kBossCount; ++i) { + const auto& boss = play_history::bosses()[i]; + if (boss.defeated == id) g_flags[i].defeated = value; + if (boss.begun == id) g_flags[i].begun = value; + } +} +void play_history_tick() { + if (!g_slide) return; + play_history::Observation o; + const auto absent = [&] { play_history::runtime().observe(o); chalice_tick(o, false); g_was_world = false; }; + o.in_world = loading_in_world() && !loading_screen_up(); + if (!o.in_world && !loading_screen_up()) { absent(); return; } + if (o.in_world && !world_player_block(&o.block)) { o.in_world = false; absent(); return; } + const auto state = pointer(g_slide + bb::GAME_STATE_MAN_SINGLETON.rva); + const auto data = pointer(g_slide + bb::GAME_DATA_MAN_SINGLETON.rva); + // RequestCharacterSave (RVA 0x156d570) passes this slot to the save + // writer and summary updater. FrpgSaveLoadMan+0x38 is request state, + // despite its historical slot_index label; it is NOT a character slot. + if (!state || !data || !read_at(state + offsetof(bb::GameStateMan, active_slot_index), &o.slot) || o.slot < 0 || o.slot >= 10) { + o.in_world = false; absent(); return; + } + std::int64_t cycle = 0, time = 0, deaths = 0, level = 0; + if (!player_stat_get("ng_cycle", &cycle) || !player_stat_get("play_time_ms", &time) || + !player_stat_get("deaths", &deaths) || !player_stat_get("level", &level) || level <= 0 || cycle < 0) { + o.in_world = false; absent(); return; + } + o.valid = true; o.cycle = static_cast(cycle); o.play_ms = time; o.deaths = deaths; + o.suspended = !g_pauses.empty(); o.when = std::time(nullptr); + static bool own_world = true; + if (!o.in_world) { + o.own_world = own_world; + play_history::runtime().observe(o); chalice_tick(o, false); g_was_world = false; return; + } + const auto world = pointer(g_slide + bb::WORLD_CHR_MAN_SINGLETON_PTR.rva); const auto chr = world ? pointer(world + 0x60) : 0; + const auto modules = chr ? pointer(chr + 0x3b0) : 0; const auto hp_data = modules ? pointer(modules + 0x20) : 0; + std::int32_t hp = 0; std::uint32_t type = 0; + if (!read_at(hp_data ? hp_data + 0xf8 : 0, &hp) || !read_at(chr ? chr + 0x78 : 0, &type)) { + o.valid = o.in_world = false; absent(); return; + } + o.alive = hp > 0; o.own_world = own_world = type == 0; + static std::string name; + const bool entered = !g_was_world || o.slot != g_last_slot || o.cycle != g_last_cycle; + if (entered) { + name = character_name(data, o.slot); + host_log("play history: slot %d, %s, NG+%d, played %llu ms%s", o.slot + 1, name.c_str(), o.cycle, + static_cast(o.play_ms), o.own_world ? "" : ", summoned world"); + } + o.name = name; + const auto now = std::chrono::steady_clock::now(); + static auto last_tick = now; + static std::chrono::steady_clock::duration remainder{}; + if (!entered) { + const auto elapsed = now - last_tick + remainder; + const auto ms = std::chrono::duration_cast(elapsed); + o.capped_delta_ms = ms.count(); remainder = elapsed - ms; + } else remainder = {}; + last_tick = now; + // Setters feed changes every frame. Polls also recover whole-store loads + // and a dropped ring, without 44 tree walks on every frame. + if (entered || now - g_polled >= std::chrono::seconds(1)) { + for (int i = 0; i < play_history::kBossCount; ++i) { + const auto& boss = play_history::bosses()[i]; + const std::uint32_t ids[] = {boss.defeated, boss.begun}; bool flags[2]{}; + g_flags[i].valid = event_flags_get(ids, 2, flags); + if (g_flags[i].valid) { g_flags[i].defeated = flags[0]; g_flags[i].begun = flags[1]; } + } + g_polled = now; + } + o.flags = g_flags; + play_history::runtime().observe(o); + chalice_tick(o, entered); + g_was_world = true; g_last_slot = o.slot; g_last_cycle = o.cycle; +} diff --git a/src/engine/play_history.h b/src/engine/play_history.h new file mode 100644 index 00000000..c1ba5c32 --- /dev/null +++ b/src/engine/play_history.h @@ -0,0 +1,7 @@ +#pragma once +#include +struct ElfImage; +void play_history_install(ElfImage* image); +void play_history_tick(); // main thread, after loading and plugin callbacks +void play_history_event_flag(std::uint32_t id, bool value); +int play_history_pause(const char* plugin, int paused); // main-thread plugin API diff --git a/src/engine/player_data.cpp b/src/engine/player_data.cpp index acbb9a55..6f6f0262 100755 --- a/src/engine/player_data.cpp +++ b/src/engine/player_data.cpp @@ -1,3 +1,4 @@ +#include "engine/play_history.h" #include "engine/player_data.h" #include "core/elf.h" @@ -67,6 +68,7 @@ const Stat* find(const char* name) { void player_data_install(ElfImage* image) { g_slide = image->mem.slide; g_ok = image->sha256 == kEboot109Sha256; + play_history_install(image); } bool player_stat_get(const char* name, std::int64_t* value) { diff --git a/src/hle/system.cpp b/src/hle/system.cpp index 8bc22bd1..93de6622 100755 --- a/src/hle/system.cpp +++ b/src/hle/system.cpp @@ -1,3 +1,4 @@ +#include "hle/trophy.h" #include "hle/common.h" #include "hle/np.h" #include "hle/np_score.h" @@ -1175,115 +1176,6 @@ GUEST_ABI int hle_save_dialog_open(const void*) { } GUEST_ABI int hle_save_dialog_update() { return 3; } // SCE_COMMON_DIALOG_STATUS_FINISHED -int g_trophy_ctx = 1; -int g_trophy_handle = 1; -GUEST_ABI int hle_trophy_ctx(int* ctx, int, unsigned, std::uint64_t) { - if (!ctx) { - return static_cast(0x805D0002); - } - *ctx = g_trophy_ctx++; - host_log("sceNpTrophyCreateContext -> %d", *ctx); - return 0; -} -GUEST_ABI int hle_trophy_handle(int* h) { - if (!h) { - return static_cast(0x805D0002); - } - *h = g_trophy_handle++; - host_log("sceNpTrophyCreateHandle -> %d", *h); - return 0; -} -// Trophies persist as one line per id in /trophies.txt. -std::mutex g_trophy_mu; -std::string trophy_file() { return hle_fs_map_path("/data/trophies.txt"); } -bool trophy_unlocked(int id, std::int64_t* when) { - std::FILE* f = std::fopen(trophy_file().c_str(), "r"); - if (!f) { - return false; - } - int tid; - long long ts; - bool found = false; - while (std::fscanf(f, "%d %lld", &tid, &ts) == 2) { - if (tid == id) { - found = true; - if (when) { - *when = ts; - } - } - } - std::fclose(f); - return found; -} -// sceNpTrophyUnlockTrophy(ctx, handle, trophyId, SceNpTrophyId* platinumId) -GUEST_ABI int hle_trophy_unlock(int ctx, int handle, int id, int* platinum_id) { - std::lock_guard lock(g_trophy_mu); - if (platinum_id) { - *platinum_id = -1; // SCE_NP_TROPHY_INVALID_TROPHY_ID: platinum not (yet) awarded - } - if (trophy_unlocked(id, nullptr)) { - return static_cast(0x80551513u); // SCE_NP_TROPHY_ERROR_ALREADY_UNLOCKED - } - std::FILE* f = std::fopen(trophy_file().c_str(), "a"); - if (f) { - std::fprintf(f, "%d %lld\n", id, static_cast(std::time(nullptr))); - std::fclose(f); - } - host_log("sceNpTrophyUnlockTrophy ctx=%d handle=%d id=%d", ctx, handle, id); - return 0; -} -// SceNpTrophyGameDetails { size, numGroups, numTrophies, numPlatinum, numGold, numSilver, numBronze, title[128], description[1024] } -// SceNpTrophyGameData { size, unlockedTrophies, unlockedPlatinum, unlockedGold, unlockedSilver, unlockedBronze, progressPercentage } -GUEST_ABI int hle_trophy_game_info(int, int, std::uint8_t* details, std::uint8_t* data) { - constexpr std::uint32_t kTrophies = 40; - if (details) { - std::memset(details + 8, 0, 0x480 - 8); - std::uint32_t v[7] = {0x488, 1, kTrophies, 1, 3, 8, 28}; - std::memcpy(details + 8, v + 1, 24); - std::strncpy(reinterpret_cast(details + 32), "Bloodborne", 127); - } - if (data) { - std::uint32_t unlocked = 0; - std::lock_guard lock(g_trophy_mu); - for (int id = 0; id < static_cast(kTrophies); ++id) { - if (trophy_unlocked(id, nullptr)) { - ++unlocked; - } - } - std::memset(data + 8, 0, 24); - std::uint32_t u[6] = {unlocked, 0, 0, 0, unlocked, unlocked * 100 / kTrophies}; - std::memcpy(data + 8, u, 24); - } - return 0; -} -// SceNpTrophyDetails { size, trophyId, trophyGrade, groupId, hidden, reserved[3], name[128], description[1024] } -// SceNpTrophyData { size, trophyId, unlocked, reserved[3], timestamp } -GUEST_ABI int hle_trophy_info(int, int, int id, std::uint8_t* details, std::uint8_t* data) { - if (details) { - std::memset(details + 8, 0, 0x490 - 8); - std::int32_t* d = reinterpret_cast(details + 8); - d[0] = id; - d[1] = 4; // bronze - d[2] = 0; - std::snprintf(reinterpret_cast(details + 24), 127, "Trophy %d", id); - } - if (data) { - std::int64_t when = 0; - bool unlocked; - { - std::lock_guard lock(g_trophy_mu); - unlocked = trophy_unlocked(id, &when); - } - std::int32_t* d = reinterpret_cast(data + 8); - d[0] = id; - d[1] = unlocked ? 1 : 0; - d[2] = d[3] = d[4] = 0; - std::uint64_t ts = unlocked ? static_cast(when) * 1000000ull + kRtcUnixEpochTicks : 0; - std::memcpy(data + 32, &ts, 8); - } - return 0; -} - // Leaderboards: no server yet. Contexts and requests are real handles; the // synchronous queries report the community server as unreachable. constexpr int kScoreErrOffline = static_cast(0x80550605u); // SCE_NP_COMMUNITY_ERROR_UNKNOWN? treated as failure @@ -1383,11 +1275,6 @@ GUEST_ABI int hle_npauth_get_code(int, const void*, char* code, int* issuer) { return 0; } -GUEST_ABI int hle_trophy_register(int ctx, int, std::uint64_t, void*) { - host_log("sceNpTrophyRegisterContext ctx=%d", ctx); - return 0; -} - constexpr int kWebApiInvalid = static_cast(0x80552902); constexpr int kWebApiNoReq = static_cast(0x80552906); constexpr char kWebApiJsonType[] = "application/json; charset=utf-8"; @@ -2299,6 +2186,7 @@ void hle_np_set_online_id(const char* id) { } void hle_register_system() { + hle_register_trophies(); #define REG(name, fn) register_hle_fn(name, reinterpret_cast(fn)) REG("sceSysmoduleLoadModule", hle_sysmodule_load); REG("sceSysmoduleUnloadModule", hle_sysmodule_unload); @@ -2398,12 +2286,6 @@ void hle_register_system() { REG("sceSaveDataDialogTerminate", hle_save_dialog_term); REG("sceSaveDataDialogOpen", hle_save_dialog_open); REG("sceSaveDataDialogUpdateStatus", hle_save_dialog_update); - REG("sceNpTrophyCreateContext", hle_trophy_ctx); - REG("sceNpTrophyCreateHandle", hle_trophy_handle); - REG("sceNpTrophyRegisterContext", hle_trophy_register); - REG("sceNpTrophyUnlockTrophy", hle_trophy_unlock); - REG("sceNpTrophyGetGameInfo", hle_trophy_game_info); - REG("sceNpTrophyGetTrophyInfo", hle_trophy_info); REG("sceNpScoreDeleteNpTitleCtx", hle_score_delete_title_ctx); REG("sceNpScoreCreateRequest", hle_score_create_request); REG("sceNpScoreDeleteRequest", hle_score_delete_request); diff --git a/src/hle/trophy.cpp b/src/hle/trophy.cpp new file mode 100644 index 00000000..23043b01 --- /dev/null +++ b/src/hle/trophy.cpp @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "hle/trophy.h" +#include "hle/common.h" +#include "core/trophies.h" +#include +#include +#include +#include + +namespace trophy_hle { +namespace { +std::mutex context_mutex; +int contexts = 0, handles = 0; +std::array registered{}; +constexpr std::uint64_t kUnixEpochTicks = 62135596800000000ull; +int validate(int ctx, int handle, bool need_registered = true) { + std::lock_guard lock(context_mutex); + if (ctx <= 0 || ctx > contexts) return kInvalidContext; + if (handle <= 0 || handle > handles) return kInvalidHandle; + if (need_registered && !registered[ctx - 1]) return kNotRegistered; + return 0; +} +template bool fits(T* value) { return !value || value->size >= sizeof(T); } +int result(trophies::Status status) { + switch (status) { + case trophies::Status::Ok: return 0; + case trophies::Status::AlreadyUnlocked: return kAlreadyUnlocked; + case trophies::Status::InvalidId: return kInvalidId; + case trophies::Status::AutomaticPlatinum: return kAutomaticPlatinum; + default: return kIoError; + } +} +} +GUEST_ABI int create_context(int* ctx, int, unsigned, std::uint64_t) { + if (!ctx) return kInvalidArgument; + std::lock_guard lock(context_mutex); + if (contexts >= static_cast(registered.size())) return kContextLimit; + *ctx = ++contexts; + return 0; +} +GUEST_ABI int create_handle(int* handle) { + if (!handle) return kInvalidArgument; + std::lock_guard lock(context_mutex); + if (handles >= 4) return kHandleLimit; + *handle = ++handles; + return 0; +} +GUEST_ABI int register_context(int ctx, int handle, std::uint64_t) { + if (const int error = validate(ctx, handle, false)) return error; + const auto award = trophies::runtime().reconcile_platinum(std::time(nullptr)); + if (award.status == trophies::Status::IoError) { + host_log("trophies: %s", trophies::runtime().snapshot().error.c_str()); + return kIoError; + } + { + std::lock_guard lock(context_mutex); + registered[ctx - 1] = true; + } + return result(award.status); +} +GUEST_ABI int unlock(int ctx, int handle, int id, int* platinum) { + if (platinum) *platinum = -1; + if (const int error = validate(ctx, handle)) return error; + const auto award = trophies::runtime().unlock(id, std::time(nullptr)); + if (platinum) *platinum = award.platinum; + if (award.status == trophies::Status::Ok) + host_log("trophies: unlocked %d (%s)%s", id, trophies::catalog()[id].name, award.platinum == 0 ? ", platinum awarded" : ""); + else if (award.status == trophies::Status::IoError) + host_log("trophies: %s", trophies::runtime().snapshot().error.c_str()); + return result(award.status); +} +GUEST_ABI int game_info(int ctx, int handle, GameDetails* details, GameData* data) { + if (const int error = validate(ctx, handle)) return error; + if ((!details && !data) || !fits(details) || !fits(data)) return kInvalidArgument; + const auto state = trophies::runtime().snapshot(); + if (!state.error.empty()) return kIoError; + std::array totals{}, earned{}; + for (int i = 0; i < trophies::kCount; ++i) { + const int grade = static_cast(trophies::catalog()[i].grade); + ++totals[grade]; + if (state.earned[i]) ++earned[grade]; + } + if (details) { + const auto size = details->size; + *details = {}; + details->size = size; + details->groups = 1; // one add-on group, in addition to the base game (-1) + details->trophies = trophies::kCount; + details->platinum = totals[1]; details->gold = totals[2]; details->silver = totals[3]; details->bronze = totals[4]; + std::snprintf(details->title, sizeof(details->title), "%s", "Bloodborne"); + std::snprintf(details->description, sizeof(details->description), "%s", "Trophies for the base game and The Old Hunters"); + } + if (data) { + const auto size = data->size; + *data = {}; + data->size = size; + data->trophies = state.count(); + data->platinum = earned[1]; data->gold = earned[2]; data->silver = earned[3]; data->bronze = earned[4]; + data->progress = data->trophies * 100 / trophies::kCount; + } + return 0; +} +GUEST_ABI int info(int ctx, int handle, int id, Details* details, Data* data) { + if (const int error = validate(ctx, handle)) return error; + if (id < 0 || id >= trophies::kCount) return kInvalidId; + if ((!details && !data) || !fits(details) || !fits(data)) return kInvalidArgument; + const auto state = trophies::runtime().snapshot(); + if (!state.error.empty()) return kIoError; + const auto& item = trophies::catalog()[id]; + if (details) { + const auto size = details->size; + *details = {}; + details->size = size; details->id = id; details->grade = static_cast(item.grade); + details->group = id < trophies::kBaseCount ? -1 : 1; + details->hidden = item.hidden; + std::snprintf(details->name, sizeof(details->name), "%s", item.name); + std::snprintf(details->description, sizeof(details->description), "%s", item.description); + } + if (data) { + const auto size = data->size; + *data = {}; + data->size = size; data->id = id; data->unlocked = state.earned[id] != 0; + if (data->unlocked) data->timestamp = state.earned[id] * 1000000ull + kUnixEpochTicks; + } + return 0; +} +} // namespace trophy_hle +void hle_register_trophies() { + HLE_REG("sceNpTrophyCreateContext", trophy_hle::create_context); + HLE_REG("sceNpTrophyCreateHandle", trophy_hle::create_handle); + HLE_REG("sceNpTrophyRegisterContext", trophy_hle::register_context); + HLE_REG("sceNpTrophyUnlockTrophy", trophy_hle::unlock); + HLE_REG("sceNpTrophyGetGameInfo", trophy_hle::game_info); + HLE_REG("sceNpTrophyGetTrophyInfo", trophy_hle::info); +} diff --git a/src/hle/trophy.h b/src/hle/trophy.h new file mode 100644 index 00000000..d9b093e7 --- /dev/null +++ b/src/hle/trophy.h @@ -0,0 +1,53 @@ +// SPDX-FileCopyrightText: Copyright 2025-2026 shadPS4 Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "guest_abi.h" +#include +#include + +// Orbis NP Trophy ABI. Layout verified against shadPS4's np_trophy.h as +// included by ayozetr/bloodborne_linux at 804651e4 (GPL-2.0-or-later). +namespace trophy_hle { +struct Details { + std::uint64_t size; + std::int32_t id, grade, group; + std::uint8_t hidden, reserved[3]; + char name[128], description[1024]; +}; +struct Data { + std::uint64_t size; + std::int32_t id; + std::uint8_t unlocked, reserved[3]; + std::uint64_t timestamp; +}; +struct GameDetails { + std::uint64_t size; + std::uint32_t groups, trophies, platinum, gold, silver, bronze; + char title[128], description[1024]; +}; +struct GameData { + std::uint64_t size; + std::uint32_t trophies, platinum, gold, silver, bronze, progress; +}; +static_assert(sizeof(Details) == 1176 && offsetof(Details, name) == 24); +static_assert(sizeof(Data) == 24 && offsetof(Data, timestamp) == 16); +static_assert(sizeof(GameDetails) == 1184 && offsetof(GameDetails, title) == 32); +static_assert(sizeof(GameData) == 32); +constexpr int kInvalidArgument = static_cast(0x80551604u); +constexpr int kInvalidHandle = static_cast(0x80551608u); +constexpr int kInvalidContext = static_cast(0x80551609u); +constexpr int kInvalidId = static_cast(0x8055160au); +constexpr int kAlreadyUnlocked = static_cast(0x8055160cu); +constexpr int kAutomaticPlatinum = static_cast(0x8055160du); +constexpr int kNotRegistered = static_cast(0x8055160fu); +constexpr int kContextLimit = static_cast(0x80551623u); +constexpr int kHandleLimit = static_cast(0x80551624u); +constexpr int kIoError = static_cast(0x80551600u); +GUEST_ABI int create_context(int* ctx, int user, unsigned label, std::uint64_t options); +GUEST_ABI int create_handle(int* handle); +GUEST_ABI int register_context(int ctx, int handle, std::uint64_t options); +GUEST_ABI int unlock(int ctx, int handle, int id, int* platinum); +GUEST_ABI int game_info(int ctx, int handle, GameDetails* details, GameData* data); +GUEST_ABI int info(int ctx, int handle, int id, Details* details, Data* data); +} // namespace trophy_hle +void hle_register_trophies(); diff --git a/src/host/ingame_menu.cpp b/src/host/ingame_menu.cpp index 8560acc5..cb1d0618 100644 --- a/src/host/ingame_menu.cpp +++ b/src/host/ingame_menu.cpp @@ -1,3 +1,5 @@ +#include "host/play_history_ui.h" +#include "host/trophy_ui.h" #define IMGUI_DEFINE_MATH_OPERATORS #include "host/ingame_menu.h" @@ -61,6 +63,8 @@ bool g_vk_ready = false; VkFormat g_format = VK_FORMAT_UNDEFINED; std::uint32_t g_images = 0; PluginUi g_ui; +TrophyUi g_trophy_ui; +PlayHistoryUi g_history_ui; std::chrono::steady_clock::time_point g_last; ImGuiKey key_of(SDL_Keycode k) { @@ -546,6 +550,7 @@ void patches_page(PatchMenu& m) { // Its pages: the settings' (host_options_page_*) - Input's rows on the // Controls page, over the bindings - with the patches and the plugins after // PC Enhancements. +int g_trophies_page = -1, g_history_page = -1; int g_page = 0; double g_page_at = -100.0; int g_patches_page = -1, g_plugins_page = -1, g_controls_page = -1; // their places among the pages @@ -588,6 +593,8 @@ const std::vector& menu_pages() { } if (g_controls_page < 0) add_controls(); // no Graphics page: at the end if (g_patches_page < 0) add_mods(); // no PC Enhancements page: at the end + own(&g_trophies_page, {"Trophies", ui::Icon::Enhance, "Local trophies, requirements, and unlock times."}); + own(&g_history_page, {"Play history", ui::Icon::Game, "Playtime, boss attempts, and chalice records for each character."}); return pages; } @@ -603,6 +610,10 @@ bool draw_menu() { return shell("##menu", "MENU", pages.data(), static_cast(pages.size()), &g_page, &g_page_at, g_page != g_plugins_page, [] { if (g_page == g_patches_page) { patches_page(g_patches); + } else if (g_page == g_trophies_page) { + trophy_ui_draw(g_trophy_ui, config().data); + } else if (g_page == g_history_page) { + play_history_ui_draw(g_history_ui, config().data, true); } else if (g_page == g_controls_page) { controls_page_draw(false); } else if (g_page == g_plugins_page) { diff --git a/src/host/launcher.cpp b/src/host/launcher.cpp index 7002e74b..bec94296 100644 --- a/src/host/launcher.cpp +++ b/src/host/launcher.cpp @@ -1,3 +1,5 @@ +#include "host/play_history_ui.h" +#include "host/trophy_ui.h" #define IMGUI_DEFINE_MATH_OPERATORS #include "host/launcher.h" @@ -75,7 +77,7 @@ constexpr int kTextSizes[] = {100, 125, 150, 175, 200, 250, 300, 350, 400}; const char* const kTextSizeLabels[] = {"100%", "125%", "150%", "175%", "200%", "250%", "300%", "350%", "400%"}; // The window's pages, as the sidebar lists them. -enum Page { kPageGame, kPageGraphics, kPageControls, kPageEnhancements, kPagePatches, kPageShaders, kPagePlugins, kPageSettings, kPageCount }; +enum Page { kPageGame, kPageGraphics, kPageControls, kPageEnhancements, kPagePatches, kPageShaders, kPagePlugins, kPageTrophies, kPageHistory, kPageSettings, kPageCount }; struct PageInfo { const char* name; const char* slug; // its picture's name (BBHOST_SETUP_TEST=shot) @@ -89,6 +91,8 @@ constexpr PageInfo kPages[kPageCount] = { {"Patches", "patches", launcher_ui::Icon::Patches}, {"Shaders", "shaders", launcher_ui::Icon::Shaders}, {"Plugins", "plugins", launcher_ui::Icon::Plugins}, + {"Trophies", "trophies", launcher_ui::Icon::Enhance}, + {"Play history", "play-history", launcher_ui::Icon::Game}, {"Settings", "settings", launcher_ui::Icon::Settings}, }; @@ -456,6 +460,8 @@ LauncherResult launcher_run(const HostConfig& cfg, const std::string& reason, bo std::string app0_seen; App0Version app0_ver; PluginUi plugin_ui; + TrophyUi trophy_ui; + PlayHistoryUi history_ui; bool plugin_seen = false; // The settings folder's move (core/config_move.h): told at the top of // every page until it is dismissed. @@ -473,6 +479,9 @@ LauncherResult launcher_run(const HostConfig& cfg, const std::string& reason, bo // does, then closes once the server has answered. const char* test = std::getenv("BBHOST_SETUP_TEST"); int frames = 0; + if (test && !std::strcmp(test, "trophies")) page = kPageTrophies; + if (test && !std::strcmp(test, "play-history")) page = kPageHistory; + if (test && !std::strcmp(test, "chalice-history")) { page = kPageHistory; history_ui.chalice = true; } // link: starts a Discord link as its button does and, once the code is // up, cancels it and closes. const std::string test_create = test && !std::strncmp(test, "create:", 7) ? test + 7 : ""; @@ -2264,6 +2273,10 @@ LauncherResult launcher_run(const HostConfig& cfg, const std::string& reason, bo ImGui::PopStyleColor(); ui::child_cards(); plugin_seen = true; + } else if (page == kPageTrophies) { + trophy_ui_draw(trophy_ui, f[kData].str().empty() ? config_default_data_dir() : f[kData].str(), 0.0f); + } else if (page == kPageHistory) { + play_history_ui_draw(history_ui, f[kData].str().empty() ? config_default_data_dir() : f[kData].str()); } else if (page == kPageSettings) { const float w = ImGui::GetContentRegionAvail().x; ui::card_begin("##folders", ImVec2(w, 0), "FOLDERS"); @@ -2391,6 +2404,7 @@ LauncherResult launcher_run(const HostConfig& cfg, const std::string& reason, bo } ImGui::End(); + if (test && (!std::strcmp(test, "trophies") || !std::strcmp(test, "play-history") || !std::strcmp(test, "chalice-history")) && ++frames > 30) done = true; ImGui::Render(); // Menu hue and Menu vibrance, on everything the frame draws. float hue = 0.0f, vibrance = 0.0f; diff --git a/src/host/play_history_ui.cpp b/src/host/play_history_ui.cpp new file mode 100644 index 00000000..e3a32078 --- /dev/null +++ b/src/host/play_history_ui.cpp @@ -0,0 +1,132 @@ +#include "host/play_history_ui.h" + +#if defined(BBHOST_HAVE_SDL3) +#include "imgui.h" +#include + +namespace { +std::string label(const play_history::Character& c) { + return "Slot " + std::to_string(c.slot + 1) + ": " + (c.name.empty() ? "Character" : c.name) + + " (record " + std::to_string(c.id) + ")"; +} +void chalice_records(const PlayHistoryUi& ui, const play_history::Character& c, int cycle) { + const auto& state = ui.chalice_state; + if (!state.error.empty()) ImGui::TextWrapped("%s", state.error.c_str()); + ImGui::SeparatorText(ui.cumulative ? "Chalice bosses: all cycles" : "Chalice bosses: selected cycle"); + const auto rows = chalice_history::totals(state, c.id, ui.cumulative ? -1 : cycle); + if (rows.empty()) ImGui::TextWrapped("No chalice encounters recorded for this cycle yet. Enter a chalice dungeon to record each dungeon and layer."); + if (!rows.empty() && ImGui::BeginTable("##chalice-totals", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH)) { + ImGui::TableSetupColumn("Chalice boss"); ImGui::TableSetupColumn("Attempts"); ImGui::TableSetupColumn("Recorded kills"); ImGui::TableHeadersRow(); + for (const auto& row : rows) { + ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextWrapped("%s", chalice_history::boss_name(row.name_id).c_str()); + ImGui::TableNextColumn(); + ImGui::Text("%llu%s", static_cast(row.count.attempts), row.count.partial ? "+" : ""); + ImGui::TableNextColumn(); ImGui::Text("%llu", static_cast(row.count.kills)); + } + ImGui::EndTable(); + } + if (ImGui::CollapsingHeader("Records by dungeon and layer", ImGuiTreeNodeFlags_DefaultOpen)) { + for (const auto& e : state.encounters) if (e.character == c.id) { + play_history::BossRecord total{}; bool shown = ui.cumulative && e.prior_clear; + for (const auto& s : e.stats) if (ui.cumulative || s.cycle == cycle) { + total.attempts += s.count.attempts; total.kills += s.count.kills; total.partial = total.partial || s.count.partial; shown = true; + } + if (!shown) continue; + ImGui::PushID(static_cast(e.id)); + ImGui::Separator(); + const auto place = e.altar ? "Altar " + std::to_string(e.altar) : std::string("Makeshift Altar"); + ImGui::TextWrapped("%s: %s, layer %d (record %llu)", chalice_history::boss_name(e.name_id).c_str(), + place.c_str(), e.layer, static_cast(e.id)); + if (e.prior_clear) ImGui::TextWrapped("Cleared before recording began. The cycle is unknown, so this kill is not assigned to a cycle."); + else ImGui::Text("Attempts %llu%s / kills %llu%s", static_cast(total.attempts), total.partial ? "+" : "", + static_cast(total.kills), e.active ? " / in progress" : ""); + ImGui::PopID(); + } + } + ImGui::Spacing(); + ImGui::TextWrapped("Chalice records and totals are separate from the base game and DLC. Each dungeon and layer is tracked separately. Chalice progress carries into NG+, so an existing kill is not counted again in the next cycle."); + ImGui::TextWrapped("Supports fixed and root chalice bosses. Earlier attempts are unknown, so initial records show a lower bound (+). Recording pauses during boss rush, practice, and visits to another player's world."); +} +} +void play_history_ui_draw(PlayHistoryUi& ui, const std::string& data_dir, bool live) { + const auto now = std::chrono::steady_clock::now(); + if (ui.directory != data_dir || now - ui.refreshed >= std::chrono::seconds(1)) { + ui.directory = data_dir; ui.refreshed = now; + ui.state = live ? play_history::runtime().snapshot() : play_history::read(std::filesystem::u8path(data_dir) / "play-history.txt"); + ui.chalice_state = live ? chalice_history::runtime().snapshot() : chalice_history::read(std::filesystem::u8path(data_dir) / "chalice-history.txt"); + } + ImGui::BeginChild("##play-history"); + ImGui::TextWrapped("Records NG and NG+ playtime, boss attempts, and kills for each character."); + if (!ui.state.error.empty()) ImGui::TextWrapped("%s", ui.state.error.c_str()); + if (ui.state.characters.empty()) { + ImGui::Spacing(); + ImGui::TextWrapped("Recording starts automatically when you play. Records are saved in play-history.txt in the data folder and continue across sessions."); + ImGui::EndChild(); return; + } + auto found = std::find_if(ui.state.characters.begin(), ui.state.characters.end(), [&](const auto& c) { return c.id == ui.character; }); + if (found == ui.state.characters.end()) { found = ui.state.characters.end() - 1; ui.character = found->id; ui.cycle = -1; } + ImGui::SetNextItemWidth(-1); + if (ImGui::BeginCombo("##character", label(*found).c_str())) { + for (const auto& c : ui.state.characters) { + if (ImGui::Selectable(label(c).c_str(), c.id == ui.character)) { ui.character = c.id; ui.cycle = -1; } + } + ImGui::EndCombo(); + } + // A selection may have changed above. + const auto& c = *std::find_if(ui.state.characters.begin(), ui.state.characters.end(), [&](const auto& item) { return item.id == ui.character; }); + if (c.cycles.empty()) { ImGui::EndChild(); return; } + if (ui.cycle < 0 || ui.cycle >= static_cast(c.cycles.size())) ui.cycle = static_cast(c.cycles.size()) - 1; + ImGui::SeparatorText("Playtime by cycle"); + if (ImGui::BeginTable("##cycles", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("Cycle"); ImGui::TableSetupColumn("Playtime"); ImGui::TableSetupColumn("Status"); ImGui::TableHeadersRow(); + for (int i = 0; i < static_cast(c.cycles.size()); ++i) { + const auto& cy = c.cycles[i]; + ImGui::PushID(i); ImGui::TableNextRow(); ImGui::TableNextColumn(); + if (ImGui::Selectable(play_history::cycle_name(cy.number).c_str(), ui.cycle == i, ImGuiSelectableFlags_SpanAllColumns)) { + ui.cycle = i; ui.cumulative = false; + } + ImGui::TableNextColumn(); + ImGui::Text("%s%s", play_history::duration(cy.elapsed_ms).c_str(), cy.partial_time ? "+" : ""); + ImGui::TableNextColumn(); ImGui::TextUnformatted(cy.complete ? "Complete" : "In progress"); ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::Spacing(); + ImGui::Checkbox("Show totals across all cycles", &ui.cumulative); + const auto& selected = c.cycles[ui.cycle]; + if (ImGui::RadioButton("Base game and DLC", !ui.chalice)) ui.chalice = false; + ImGui::SameLine(); + if (ImGui::RadioButton("Chalice dungeons", ui.chalice)) ui.chalice = true; + if (ui.chalice) { + chalice_records(ui, c, selected.number); + ImGui::EndChild(); return; + } + const auto records = ui.cumulative ? play_history::totals(c) : selected.bosses; + ImGui::SeparatorText(ui.cumulative ? "Boss fights: this character's totals across all cycles" : play_history::cycle_name(selected.number).c_str()); + if (ImGui::BeginTable("##boss-records", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("Boss", ImGuiTableColumnFlags_WidthStretch, 2.4f); + ImGui::TableSetupColumn("Attempts", ImGuiTableColumnFlags_WidthStretch, 1.f); + ImGui::TableSetupColumn("Kills", ImGuiTableColumnFlags_WidthStretch, .6f); + ImGui::TableSetupColumn("Result", ImGuiTableColumnFlags_WidthStretch, 1.6f); ImGui::TableHeadersRow(); + for (int i = 0; i < play_history::kBossCount; ++i) { + const auto& b = records[i]; + ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextWrapped("%s", play_history::bosses()[i].name); + ImGui::TableNextColumn(); + if (b.partial && !b.attempts) ImGui::TextUnformatted("Unknown"); + else ImGui::Text("%llu%s", static_cast(b.attempts), b.partial ? "+" : ""); + ImGui::TableNextColumn(); ImGui::Text("%llu", static_cast(b.kills)); + ImGui::TableNextColumn(); + const bool fighting = !ui.cumulative && ui.cycle == static_cast(c.cycles.size()) - 1 && c.active_boss == i; + ImGui::TextWrapped("%s", fighting ? "In progress" : b.kills ? (b.partial ? "Defeated (partial record)" : "Defeated") : b.attempts ? "Not defeated" : "Not recorded"); + } + ImGui::EndTable(); + } + ImGui::Spacing(); + ImGui::TextWrapped("An attempt is counted when a fight starts, including deaths, retreats, interrupted fights, and the winning attempt. Counts for that cycle are final once the boss is defeated."); + ImGui::TextWrapped("Time follows the game's play clock. Entering the next NG+ ends the previous cycle. Recording pauses during boss rush, practice, and visits to another player's world. Chalice bosses have their own records under Chalice dungeons."); + ImGui::TextWrapped("Earlier attempts and NG+ start times cannot be reconstructed. A + or Unknown means the record is incomplete. If a save rollback or a new character is detected, the previous record is kept and a new one is started."); + ImGui::EndChild(); +} +#else +void play_history_ui_draw(PlayHistoryUi&, const std::string&, bool) {} +#endif diff --git a/src/host/play_history_ui.h b/src/host/play_history_ui.h new file mode 100644 index 00000000..c74e66f4 --- /dev/null +++ b/src/host/play_history_ui.h @@ -0,0 +1,15 @@ +#pragma once +#include "core/play_history.h" +#include "core/chalice_history.h" +#include + +struct PlayHistoryUi { + std::string directory; + play_history::Snapshot state; + chalice_history::Snapshot chalice_state; + std::chrono::steady_clock::time_point refreshed{}; + std::uint64_t character = 0; + int cycle = -1; + bool cumulative = false, chalice = false; +}; +void play_history_ui_draw(PlayHistoryUi& ui, const std::string& data_dir, bool live = false); diff --git a/src/host/plugins.cpp b/src/host/plugins.cpp index 7f0459ac..050c8688 100644 --- a/src/host/plugins.cpp +++ b/src/host/plugins.cpp @@ -1,3 +1,4 @@ +#include "engine/play_history.h" #include "host/plugins.h" #include "host/plugin_address.h" @@ -1846,6 +1847,7 @@ const BbHostApi g_api = { &api_panel_show, &api_panel_state, &api_option_set, &api_input_take_as, &api_input_as, &api_panel_rows, &api_panel_value, &api_panel_open, &api_cutscene, + &play_history_pause, }; std::string read_file(const std::string& path) { diff --git a/src/host/trophy_ui.cpp b/src/host/trophy_ui.cpp new file mode 100644 index 00000000..93add360 --- /dev/null +++ b/src/host/trophy_ui.cpp @@ -0,0 +1,104 @@ +#include "host/trophy_ui.h" + +#if defined(BBHOST_HAVE_SDL3) +#include "host/overlay.h" +#include "imgui.h" +#include +#include +#include + +namespace { +std::uint32_t colour(trophies::Grade g) { + switch (g) { + case trophies::Grade::Platinum: return 0xb8e9ffff; + case trophies::Grade::Gold: return 0xe8c56aff; + case trophies::Grade::Silver: return 0xd4dbe5ff; + default: return 0xd99c6aff; + } +} +ImVec4 text_colour(trophies::Grade g) { + const auto c = colour(g); + return ImVec4((c >> 24) / 255.f, ((c >> 16) & 255) / 255.f, ((c >> 8) & 255) / 255.f, 1); +} +} + +void trophy_ui_draw(TrophyUi& ui, const std::string& data_dir, float height) { + const auto now = std::chrono::steady_clock::now(); + const auto file = std::filesystem::u8path(data_dir) / "trophies.txt"; + if (ui.file != data_dir || now - ui.refreshed > std::chrono::seconds(1)) { + ui.file = data_dir; ui.refreshed = now; ui.state = trophies::read(file); + } + ImGui::BeginChild("##trophies", ImVec2(0, height)); + ImGui::Text("Trophies %d / %d", ui.state.count(), trophies::kCount); + ImGui::ProgressBar(float(ui.state.count()) / trophies::kCount, ImVec2(-1, 0)); + ImGui::TextWrapped("Trophies are stored on this PC. Earn all 33 base-game trophies to unlock platinum; the expansion is not required."); + if (!ui.state.error.empty()) ImGui::TextColored(ImVec4(1,.65f,.3f,1), "%s", ui.state.error.c_str()); + const char* filters[] = {"All", "Unlocked", "Locked"}; + ImGui::SetNextItemWidth(160); + ImGui::Combo("Show", &ui.filter, filters, 3); + ImGui::SameLine(); + ImGui::Checkbox("Reveal hidden trophies", &ui.reveal); + for (int group = 0; group < 2; ++group) { + const int begin = group ? trophies::kBaseCount : 0, end = group ? trophies::kCount : trophies::kBaseCount; + char title[100]; + std::snprintf(title, sizeof(title), "%s %d / %d", group ? "The Old Hunters" : "Base game", ui.state.count(begin, end), end - begin); + ImGui::SeparatorText(title); + for (int i = begin; i < end; ++i) { + const auto& t = trophies::catalog()[i]; + const auto when = ui.state.earned[i]; + if ((ui.filter == 1 && !when) || (ui.filter == 2 && when)) continue; + const bool secret = t.hidden && !when && !ui.reveal; + ImGui::TextColored(text_colour(t.grade), "%s", trophies::grade_name(t.grade)); + ImGui::SameLine(); + ImGui::Text("%s %s", when ? "Unlocked" : "Locked", secret ? "Hidden trophy" : t.name); + ImGui::TextWrapped("%s", secret ? "Unlock this trophy to reveal its name and requirements." : t.description); + if (when) { + const std::time_t seconds = static_cast(when); + std::tm tm{}; +#if defined(_WIN32) + const bool valid = gmtime_s(&tm, &seconds) == 0; +#else + const bool valid = gmtime_r(&seconds, &tm) != nullptr; +#endif + char date[64] = {}; + if (valid && std::strftime(date, sizeof(date), "%Y/%m/%d %H:%M UTC", &tm)) ImGui::TextDisabled("%s", date); + } + ImGui::Spacing(); + } + } + ImGui::EndChild(); +} + +void trophy_notice_draw(float dw, float dh) { + static int current = -1; + static auto began = std::chrono::steady_clock::time_point{}; + const auto now = std::chrono::steady_clock::now(); + if (current >= 0 && now - began >= std::chrono::seconds(6)) current = -1; + if (current < 0) { + current = trophies::runtime().pop_notice(); + if (current < 0) return; + began = now; + } + const auto& item = trophies::catalog()[current]; + const float elapsed = std::chrono::duration(now - began).count(); + const float alpha = std::min(std::clamp(elapsed / .2f, 0.f, 1.f), std::clamp((6.f - elapsed) / .5f, 0.f, 1.f)); + const auto fade = [&](std::uint32_t c) { return (c & 0xffffff00u) | std::uint32_t((c & 255) * alpha); }; + const float s = std::clamp(dh / 1080.f, .65f, 1.5f); + const float x = 24*s, y = 28*s, width = std::min(560*s, dw - 48*s), h = 102*s; + host_overlay_rect(x, y, width, h, fade(0x15191ff0)); + host_overlay_rect(x, y, 4*s, h, fade(colour(item.grade))); + // Draw the cup with overlay primitives. + const float cx = x+26*s, cy = y+28*s; + host_overlay_rect(cx, cy, 34*s, 24*s, fade(colour(item.grade))); + host_overlay_tri(cx, cy+24*s, cx+34*s, cy+24*s, cx+17*s, cy+35*s, fade(colour(item.grade))); + host_overlay_rect(cx+14*s, cy+30*s, 6*s, 14*s, fade(colour(item.grade))); + host_overlay_rect(cx+6*s, cy+44*s, 22*s, 5*s, fade(colour(item.grade))); + host_overlay_text(x+80*s, y+13*s, .65f*s, fade(0xcbd3dfff), "Trophy unlocked"); + const float name_scale = .9f*s * std::min(1.f, (width-95*s) / std::max(1.f, host_overlay_text_width(.9f*s, item.name))); + host_overlay_text(x+80*s, y+37*s, name_scale, fade(0xffffffff), item.name); + host_overlay_text(x+80*s, y+76*s, .6f*s, fade(colour(item.grade)), trophies::grade_name(item.grade)); +} +#else +void trophy_ui_draw(TrophyUi&, const std::string&, float) {} +void trophy_notice_draw(float, float) {} +#endif diff --git a/src/host/trophy_ui.h b/src/host/trophy_ui.h new file mode 100644 index 00000000..381a6cc7 --- /dev/null +++ b/src/host/trophy_ui.h @@ -0,0 +1,15 @@ +#pragma once +#include "core/trophies.h" +#include +#include + +struct TrophyUi { + std::string file; + trophies::Snapshot state; + std::chrono::steady_clock::time_point refreshed{}; + int filter = 0; + bool reveal = false; +}; +void trophy_ui_draw(TrophyUi& ui, const std::string& data_dir, float height = 0); +// Called on the window pump between overlay reset and commit. +void trophy_notice_draw(float display_width, float display_height); diff --git a/src/host/window.cpp b/src/host/window.cpp index 338e90c9..9da1453d 100755 --- a/src/host/window.cpp +++ b/src/host/window.cpp @@ -1,3 +1,4 @@ +#include "host/trophy_ui.h" #include "host/window.h" #include "host/plugin_panel.h" #include "core/host_clock.h" @@ -3098,6 +3099,13 @@ bool host_window_pump() { // The frame's overlay, whole, to the presenter: a present never sees one // half rebuilt. Nothing on it (no counter, pointer, box or screen) and the // presenter's pass draws nothing over the picture. + { + float width, height; + { std::lock_guard lock(g_mouse_mu); + width = g_display_w ? float(g_display_w) : 1920.f; + height = g_display_h ? float(g_display_h) : 1080.f; } + trophy_notice_draw(width, height); + } host_overlay_commit(); // BBHOST_MOUSE_LOG=1: the pointer as the host sees it, for bringing it up // before there is a consumer. This **consumes** the edges, the wheel and diff --git a/src/main.cpp b/src/main.cpp index 8a83d8f4..03e85ed9 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,3 +1,6 @@ +#include "core/chalice_history.h" +#include "core/play_history.h" +#include "core/trophies.h" #include "engine/frame_pool.h" #include "engine/key_prompts.h" #include "decomp/decomp.h" @@ -270,6 +273,8 @@ void run_guest_start(GuestStart fn, void* argv, bool windowed) { if (windowed) sampler_note_pump(); // the watchdog's "Not Responding" stacks (host/sampler.h) if (windowed && !host_window_pump()) { host_log("window closed"); + play_history::runtime().flush(); + chalice_history::runtime().flush(); exit_wait_for_saves(true); exit_deadline(0, 15.0); exit_test_stall(); @@ -313,6 +318,8 @@ void run_guest_start(GuestStart fn, void* argv, bool windowed) { // not stopped (that waits for the GPU lock the command // processor may hold), the process just ends. host_log("exit: flip %llu reached (BBHOST_EXIT_FLIP)", static_cast(exit_flip)); + play_history::runtime().flush(); + chalice_history::runtime().flush(); g_exit_pumps.store(windowed); exit_wait_for_saves(windowed); exit_deadline(0, 30.0); @@ -1363,6 +1370,9 @@ int main(int argc, char** argv) { "the game stops when it reads a file only the update has.", v.app_ver.c_str()); } + trophies::runtime().open(std::filesystem::u8path(cfg.data) / "trophies.txt"); + play_history::runtime().open(std::filesystem::u8path(cfg.data) / "play-history.txt"); + chalice_history::runtime().open(std::filesystem::u8path(cfg.data) / "chalice-history.txt"); hle_fs_set_roots(cfg.app0.c_str(), cfg.data.empty() ? nullptr : cfg.data.c_str(), cfg.tmp.empty() ? nullptr : cfg.tmp.c_str(), eboot, cfg.mods.empty() ? nullptr : cfg.mods.c_str()); @@ -1436,6 +1446,8 @@ int main(int argc, char** argv) { static_cast(image.entry), kGuestMainStack); run_guest_start(reinterpret_cast(image.entry), stack.data(), windowed); host_log("_start returned"); + play_history::runtime().flush(); + chalice_history::runtime().flush(); host_window_stop(); engine_bind(nullptr); unload_elf(&image); diff --git a/tests/chalice_history_test.cpp b/tests/chalice_history_test.cpp new file mode 100644 index 00000000..b9baca08 --- /dev/null +++ b/tests/chalice_history_test.cpp @@ -0,0 +1,145 @@ +#undef NDEBUG +#include "core/chalice_history.h" +#include "engine/chalice_history.h" +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using namespace chalice_history; +namespace { +std::string contents(const fs::path& file) { std::ifstream in(file); return {std::istreambuf_iterator(in), {}}; } +Observation world() { + Observation o; o.character = 1; o.cycle = 0; o.in_world = true; + o.dungeon = "1-1d0a5a00-0123456789abcdef"; o.altar = 1; + o.bosses.push_back({1, 313000, {true, false, false}}); + return o; +} +play_history::BossRecord total(const Store& store, int cycle = -1, std::uint64_t character = 1) { + auto rows = totals(store.snapshot(), character, cycle); + for (const auto& row : rows) if (row.name_id == 313000) return row.count; + return {}; +} +void event_sources() { + // The actual live-instance layouts: a root/fixed single boss, then the + // multi-character Watchers template in the pending chain. + bb::SprjEmkEventIns giant{}, watchers{}, other{}; + constexpr std::uint64_t vt = 0x123400; + giant.core.vtable = reinterpret_cast(vt); + giant.core.event_id = 12906806; + std::uint32_t ga[]{2900100, 313000, 12901800, 12905502, 12905504}; + giant.arguments = reinterpret_cast(ga); giant.argument_size = sizeof ga; + giant.core.next = &other.core; + other.core.event_id = 1000000001; // completion events are shorter and have no argument buffer + watchers.core.vtable = giant.core.vtable; watchers.core.event_id = 12906795; + std::uint32_t wa[]{2900105, 304001, 12901801, 12905511, 12905513, 2900101, 2900103}; + watchers.arguments = reinterpret_cast(wa); watchers.argument_size = sizeof wa; + bb::SprjEmkSystem system{}; system.active = &giant.core; system.pending = &watchers.core; + struct Region { std::uint64_t begin, size; }; + const Region regions[]{ + {reinterpret_cast(&system), sizeof system}, {reinterpret_cast(&giant), sizeof giant}, + {reinterpret_cast(&watchers), sizeof watchers}, {reinterpret_cast(&other), sizeof other}, + {reinterpret_cast(ga), sizeof ga}, {reinterpret_cast(wa), sizeof wa}, + }; + const auto safe = [&](std::uint64_t at, auto* out) { + for (const auto& r : regions) if (at >= r.begin && at - r.begin <= r.size && sizeof(*out) <= r.size - (at - r.begin)) { + std::memcpy(out, reinterpret_cast(at), sizeof(*out)); return true; + } + return false; + }; + std::vector rows; + assert(chalice_events::sources(reinterpret_cast(&system), vt, safe, rows)); + assert(rows.size() == 2 && rows[0].name_id == 313000 && rows[0].layer == 1 && rows[1].name_id == 304001 && rows[1].layer == 2); + watchers.core.flags = 1; + assert(chalice_events::sources(reinterpret_cast(&system), vt, safe, rows) && rows.size() == 1); + other.core.next = &giant.core; + assert(!chalice_events::sources(reinterpret_cast(&system), vt, safe, rows)); // cycle bounded + other.core.next = nullptr; giant.arguments = reinterpret_cast(1); + assert(!chalice_events::sources(reinterpret_cast(&system), vt, safe, rows)); // bad pointer +} +} +int main() { + event_sources(); + const auto root = fs::temp_directory_path() / ("bbhost-chalice-history-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(root); + const auto file = root / "chalice-history.txt"; + Store store; store.open(file); auto o = world(); store.observe(o); + assert(total(store).attempts == 0 && total(store).kills == 0); + o.bosses[0].flags.begun = true; store.observe(o); store.observe(o); + assert(total(store).attempts == 1); + store.flush(); store.open(file); store.observe(o); + assert(total(store).attempts == 1); // an open fight survives process restart + o.alive = false; ++o.deaths; store.observe(o); assert(!store.snapshot().encounters[0].active); + o.in_world = false; store.observe(o); store.open(file); + o.in_world = o.alive = true; store.observe(o); + assert(total(store).attempts == 1); // stale fight flag after respawn + o.bosses[0].flags.begun = false; store.observe(o); + o.bosses[0].flags.begun = true; store.observe(o); + o.bosses[0].flags.defeated = true; o.alive = false; ++o.deaths; store.observe(o); + assert(total(store).attempts == 2 && total(store).kills == 1); // win beats simultaneous death + o.alive = true; o.cycle = 1; store.observe(o); store.observe(o); + assert(total(store).attempts == 2 && total(store).kills == 1); + assert(totals(store.snapshot(), 1, 1).empty()); // NG+ does not re-credit inherited chalice clears + + // The same event flags in a different altar/dungeon are independent. + o.dungeon = "2-1d145a00-aaaaaaaaaaaaaaaa"; o.altar = 2; o.bosses[0].flags = {true, false, false}; store.observe(o); + o.bosses[0].flags.begun = true; store.observe(o); + o.bosses[0].flags.defeated = true; store.observe(o); + assert(store.snapshot().encounters.size() == 2 && total(store).attempts == 3 && total(store).kills == 2); + assert(total(store, 0).kills == 1 && total(store, 1).kills == 1); + + // Recreating/replaying a dungeon retains the previous encounter. + o.bosses[0].flags = {true, false, false}; store.observe(o); + assert(store.snapshot().encounters.size() == 3); + o.bosses[0].flags.begun = true; store.observe(o); + o.bosses[0].flags.defeated = true; store.observe(o); + assert(total(store).attempts == 4 && total(store).kills == 3); + + // A first-seen clear can predate this NG cycle. Keep it visible as an + // unknown baseline, without inventing a kill in this cycle or totals. + o.dungeon = "3-1d1e5a00-bbbbbbbbbbbbbbbb"; o.altar = 3; store.observe(o); + assert(store.snapshot().encounters.back().prior_clear && total(store).kills == 3); + o.cycle = 2; store.observe(o); assert(total(store, 2).kills == 0); + + // Layers of the same boss stay distinct within one dungeon. + o.bosses.push_back({2, 313000, {true, false, false}}); store.observe(o); + o.bosses[1].flags.begun = true; store.observe(o); + o.bosses[1].flags.valid = false; store.observe(o); + assert(store.snapshot().encounters.back().active); // missing flag block is not an exit + o.bosses[1].flags = {true, true, true}; store.observe(o); + assert(total(store).attempts == 5 && total(store).kills == 4); + + const auto before = total(store); + o.suspended = true; o.dungeon = "practice"; o.bosses[0].flags = {true, true, true}; store.observe(o); + assert(total(store).kills == before.kills && total(store).attempts == before.attempts); + o.suspended = false; o.character = 2; store.observe(o); + assert(total(store).kills == before.kills && total(store, -1, 2).kills == 0); + + // Story/DLC records are a different file, type and aggregation path. + play_history::Store campaign; const auto campaign_file = root / "play-history.txt"; campaign.open(campaign_file); + play_history::Observation p; p.valid = p.in_world = true; p.slot = 0; p.name = "hunter"; + campaign.observe(p); campaign.flush(); const auto campaign_text = contents(campaign_file); + store.flush(); store.open(file); + assert(store.snapshot().error.empty() && total(store).kills == 4 && contents(campaign_file) == campaign_text); + assert(play_history::totals(campaign.snapshot().characters[0])[0].attempts == 0); + assert(campaign.current_character_id() == 1); + + Store variants; variants.open(root / "variants.txt"); auto v = world(); + v.bosses[0].name_id = 209000; v.bosses[0].flags.begun = true; variants.observe(v); + v.bosses[0].flags.defeated = true; variants.observe(v); + v.dungeon = "different-root"; v.bosses[0].name_id = 209010; v.bosses[0].flags = {true, false, true}; variants.observe(v); + v.bosses[0].flags.defeated = true; variants.observe(v); + auto combined = totals(variants.snapshot(), 1); + assert(combined.size() == 1 && combined[0].count.attempts == 2 && combined[0].count.kills == 2); + + const auto valid = contents(file); + for (const auto& text : {std::string("BBHOST_CHALICE_HISTORY 99\n"), valid.substr(0, valid.size() - 4), valid + "unknown\n"}) { + const auto damaged = root / "damaged.txt"; std::ofstream(damaged) << text; + Store guarded; guarded.open(damaged); assert(!guarded.snapshot().error.empty()); + guarded.observe(world()); assert(!guarded.flush() && contents(damaged) == text); + } + fs::remove_all(root); + std::cout << "PASS: chalice dungeon/layer identity, retries, clears, NG+ carry-over, cumulative separation, persistence, root/Watchers event layouts\n"; +} diff --git a/tests/play_history_test.cpp b/tests/play_history_test.cpp new file mode 100644 index 00000000..46e1e208 --- /dev/null +++ b/tests/play_history_test.cpp @@ -0,0 +1,175 @@ +#undef NDEBUG +#include "core/play_history.h" +#include +#include +#include +#include + +using namespace play_history; +namespace fs = std::filesystem; +namespace { +Observation world(int slot = 0, int cycle = 0, std::uint64_t time = 0) { + Observation o; + o.valid = o.in_world = true; o.slot = slot; o.cycle = cycle; o.play_ms = time; + o.name = "狩人 \"月\""; o.when = 1793833200; + o.block = bosses()[0].block << 16; + for (auto& flag : o.flags) flag.valid = true; + return o; +} +Character last(const Store& store) { return store.snapshot().characters.back(); } +BossRecord boss(const Store& store, int cycle = 0, int i = 0) { return last(store).cycles.at(cycle).bosses[i]; } +std::string text(const fs::path& file) { + std::ifstream in(file, std::ios::binary); return {std::istreambuf_iterator(in), {}}; +} +void sample(Store& store, Observation& o, std::uint64_t delta = 100) { o.play_ms += delta; store.observe(o); } +} +int main() { + const auto root = fs::temp_directory_path() / ("bbhost-history-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(root); + const auto file = root / fs::u8path("周回記録") / "play-history.txt"; + Store store; store.open(file); + assert(store.snapshot().characters.empty()); + auto o = world(); store.observe(o); + o.flags[0].begun = true; sample(store, o); + for (int i = 0; i < 50; ++i) sample(store, o); + assert(boss(store).attempts == 1); + o.alive = false; ++o.deaths; sample(store, o); + assert(last(store).active_boss == -1 && boss(store).attempts == 1); + // A loading screen or process restart must not re-count a stale begun flag. + store.observe({}); store.open(file); o.alive = true; sample(store, o); + assert(boss(store).attempts == 1); + o.flags[0].begun = false; sample(store, o); + o.flags[0].begun = true; sample(store, o); + assert(boss(store).attempts == 2); + // Quit out and resume the same open fight: exactly one attempt. + store.flush(); store.open(file); sample(store, o); + assert(boss(store).attempts == 2); + o.flags[0].begun = false; sample(store, o); // return to fog without a death + o.flags[0].begun = true; sample(store, o); + o.flags[0].defeated = true; o.alive = false; ++o.deaths; sample(store, o); + assert(boss(store).attempts == 3 && boss(store).kills == 1); // simultaneous death/win + const auto clear_attempts = boss(store).attempts; + o.alive = true; o.flags[0].defeated = false; sample(store, o); + o.flags[0].begun = true; sample(store, o); + assert(boss(store).attempts == clear_attempts && boss(store).kills == 1); + const auto ng_end = o.play_ms + 100; + o.cycle = 1; o.flags[0] = {true, false, false}; sample(store, o); + auto c = last(store); + assert(c.cycles.size() == 2 && c.cycles[0].complete && c.cycles[0].elapsed_ms == ng_end); + assert(c.cycles[1].elapsed_ms == 0 && !c.cycles[1].partial_time); + o.flags[0].begun = true; sample(store, o); + o.flags[0].defeated = true; sample(store, o, 12345); + assert(boss(store, 1).attempts == 1 && boss(store, 1).kills == 1); + const auto sum = totals(last(store)); + assert(sum[0].attempts == 4 && sum[0].kills == 2 && !sum[0].partial); + assert(last(store).cycles[1].elapsed_ms == 12445); + store.flush(); + const auto loaded = read(file); + assert(loaded.error.empty() && loaded.characters.size() == 1 && loaded.characters[0].name == o.name); + assert(totals(loaded.characters[0])[0].attempts == 4); + assert(duration(3600123000ull) == "1000:02:03"); + + // Character switches, title-screen zero counters, old-save rollback. + store.observe({}); + auto other = world(1, 2, 100000); store.observe(other); + assert(store.snapshot().characters.size() == 2 && last(store).cycles[0].partial_time); + sample(store, other, 5000); assert(last(store).cycles[0].elapsed_ms == 5000); + store.observe({}); sample(store, o); + assert(store.snapshot().characters.size() == 2); + o.cycle = 0; o.play_ms = 0; o.deaths = 0; o.flags[0] = {true, false, false}; sample(store, o); + assert(store.snapshot().characters.size() == 3 && last(store).cycles.size() == 1); + assert(store.snapshot().characters[0].cycles.size() == 2); // original records retained + + // Existing saves: known kills, unknown earlier attempts; no fictional successes. + Store partial; partial.open(root / "partial.txt"); + auto late = world(0, 4, 999999); late.flags[0].defeated = true; partial.observe(late); + assert(boss(partial).attempts == 0 && boss(partial).kills == 1 && boss(partial).partial); + assert(last(partial).cycles[0].elapsed_ms == 0 && last(partial).cycles[0].partial_time); + late.flags[1].begun = true; sample(partial, late); + assert(boss(partial, 0, 1).attempts == 1 && boss(partial, 0, 1).partial); + // Missing flag blocks cannot turn an active attempt off or add a kill. + late.flags[1].valid = false; sample(partial, late); + assert(last(partial).active_boss == 1 && boss(partial, 0, 1).kills == 0); + late.flags[2] = {true, true, false}; sample(partial, late); + assert(boss(partial, 0, 2).attempts == 0 && boss(partial, 0, 2).kills == 1 && boss(partial, 0, 2).partial); + + // Boss Rush and summoned worlds must not contaminate campaign records. + Store practice; practice.open(root / "practice.txt"); + auto p = world(); practice.observe(p); + sample(practice, p, 5000); + p.suspended = true; p.flags[0].begun = true; sample(practice, p, 1000); + p.flags[0].defeated = true; ++p.deaths; sample(practice, p, 60000); + assert(boss(practice).attempts == 0 && boss(practice).kills == 0 && last(practice).cycles[0].elapsed_ms == 5000); + p.suspended = false; p.flags[0] = {true, false, false}; sample(practice, p, 100); + sample(practice, p, 1000); assert(last(practice).cycles[0].elapsed_ms == 6000); + p.own_world = false; p.flags[0] = {true, true, true}; sample(practice, p); + assert(boss(practice).kills == 0); + p.own_world = true; p.flags[0] = {true, false, false}; sample(practice, p); + p.flags[0].begun = true; sample(practice, p); + assert(boss(practice).attempts == 1); + + // A fight elsewhere in the same map must not count a persistent met flag. + Store wrong; wrong.open(root / "wrong.txt"); + auto w = world(); w.block = 0x22000000; w.flags[0].begun = true; wrong.observe(w); + assert(boss(wrong).attempts == 0); + w.block = bosses()[0].block << 16; sample(wrong, w); + assert(boss(wrong).attempts == 1); + + // The game's clock saturates, but later NG+ cycles still time. + Store capped; capped.open(root / "capped.txt"); + auto cap = world(0, 8, kPlayTimeCap); capped.observe(cap); + cap.capped_delta_ms = 20000; capped.observe(cap); + assert(last(capped).cycles[0].elapsed_ms == 20000 && last(capped).cycles[0].partial_time); + cap.cycle = 9; cap.capped_delta_ms = 1000; capped.observe(cap); + cap.capped_delta_ms = 5000; capped.observe(cap); + assert(last(capped).cycles[1].elapsed_ms == 5000 && !last(capped).cycles[1].partial_time); + capped.observe({}); cap.capped_delta_ms = 999999; capped.observe(cap); + assert(last(capped).cycles[1].elapsed_ms == 5000); + + Store boundary; const auto boundary_file = root / "boundary.txt"; boundary.open(boundary_file); + auto bo = world(); boundary.observe(bo); sample(boundary, bo, 5000); + bo.in_world = false; bo.cycle = 1; sample(boundary, bo, 100); + bo.in_world = true; sample(boundary, bo, 1000); + assert(last(boundary).cycles[0].elapsed_ms == 5100 && !last(boundary).cycles[0].partial_time); + assert(last(boundary).cycles[1].elapsed_ms == 1000 && !last(boundary).cycles[1].partial_time); + boundary.flush(); boundary.open(boundary_file); bo.cycle = 2; sample(boundary, bo, 80000); + assert(last(boundary).cycles[1].partial_time && last(boundary).cycles[2].partial_time); + assert(last(boundary).cycles[1].elapsed_ms == 1000 && last(boundary).cycles[2].elapsed_ms == 0); + + Store gap; const auto gap_file = root / "gap.txt"; gap.open(gap_file); + auto go = world(); gap.observe(go); gap.flush(); gap.open(gap_file); + sample(gap, go, 60000); + assert(boss(gap).partial && boss(gap).attempts == 0); + + // Closing the window can leave the game save behind the host checkpoint. + // A routine autosave rewind must preserve this character and its attempts. + Store resume; const auto resume_file = root / "resume.txt"; resume.open(resume_file); + auto ro = world(0, 1, 1000000); resume.observe(ro); + ro.flags[0].begun = true; sample(resume, ro, 20000); resume.flush(); resume.open(resume_file); + ro.play_ms -= 15000; resume.observe(ro); + assert(resume.snapshot().characters.size() == 1 && boss(resume).attempts == 1); + const auto resumed_time = last(resume).cycles[0].elapsed_ms; + sample(resume, ro, 1000); + assert(last(resume).cycles[0].elapsed_ms == resumed_time + 1000); + resume.flush(); resume.open(resume_file); ro.play_ms -= 400000; resume.observe(ro); + assert(resume.snapshot().characters.size() == 2); // substantial restore: separate branch + Store early; const auto early_file = root / "early.txt"; early.open(early_file); + auto eo = world(); early.observe(eo); sample(early, eo, 10000); early.flush(); early.open(early_file); + eo.play_ms = 0; early.observe(eo); + assert(early.snapshot().characters.size() == 1); // first autosave can still be at spawn + + // Strict loading: truncated, duplicate, malformed and future records are + // preserved and never replaced by a fresh empty history. + store.flush(); const auto valid = text(file); + for (const auto& broken : {std::string("BBHOST_PLAY_HISTORY 99\n"), valid.substr(0, valid.rfind("boss ")), + valid + "boss 0 3 1 0\n", valid + "unexpected\n"}) { + const auto damaged = root / "damaged.txt"; std::ofstream(damaged, std::ios::binary) << broken; + Store guarded; guarded.open(damaged); assert(!guarded.snapshot().error.empty()); + guarded.observe(world()); assert(!guarded.flush() && text(damaged) == broken); + } + const auto blocker = root / "blocker"; std::ofstream(blocker) << "keep"; + Store io; io.open(blocker / "history.txt"); io.observe(world()); + assert(!io.flush() && !io.snapshot().error.empty() && text(blocker) == "keep"); + fs::remove_all(root); + std::cout << "PASS: cycles, attempts, kills, cumulative totals, reloads, characters, partial histories, practice, rollback, persistence\n"; +} diff --git a/tests/plugin_abi_test.c b/tests/plugin_abi_test.c index b6d3f4fa..275c7b04 100755 --- a/tests/plugin_abi_test.c +++ b/tests/plugin_abi_test.c @@ -60,7 +60,8 @@ _Static_assert(offsetof(BbHostApi, panel_rows) == offsetof(BbHostApi, input_as) _Static_assert(offsetof(BbHostApi, panel_value) == offsetof(BbHostApi, panel_rows) + sizeof(void*), "panel_value after panel_rows"); _Static_assert(offsetof(BbHostApi, panel_open) == offsetof(BbHostApi, panel_value) + sizeof(void*), "panel_open after panel_value"); _Static_assert(offsetof(BbHostApi, cutscene) == offsetof(BbHostApi, panel_open) + sizeof(void*), "cutscene after panel_open"); -_Static_assert(sizeof(BbHostApi) == offsetof(BbHostApi, cutscene) + sizeof(void*), "cutscene ends the API table"); +_Static_assert(offsetof(BbHostApi, campaign_tracking_pause) == offsetof(BbHostApi, cutscene) + sizeof(void*), "campaign_tracking_pause follows version 29"); +_Static_assert(sizeof(BbHostApi) == offsetof(BbHostApi, campaign_tracking_pause) + sizeof(void*), "campaign_tracking_pause ends the API table"); _Static_assert(BB_OPT_PANEL == 0x400u && BB_PANEL_DEFAULTS == 1u && BB_PANEL_CORNER == 2u, "the panel's flags"); _Static_assert(BB_OPT_MENU == 0x800u && BB_OPT_SUBPAGE == 0x1000u && BB_OPT_OPEN == 0x2000u && BB_OPT_CONFIRM == 0x4000u && BB_OPT_INFO == 8, diff --git a/tests/trophies_test.cpp b/tests/trophies_test.cpp new file mode 100644 index 00000000..c1a91816 --- /dev/null +++ b/tests/trophies_test.cpp @@ -0,0 +1,133 @@ +#undef NDEBUG +#include "core/trophies.h" +#include "hle/trophy.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using trophies::Status; +std::map imports; +void register_hle_fn(const char* name, void* fn) { imports[name] = fn; } +std::string contents(const fs::path& p) { + std::ifstream in(p, std::ios::binary); + return {std::istreambuf_iterator(in), {}}; +} +int main() { + const auto root = fs::temp_directory_path() / ("bbhost-trophies-" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(root); + const auto file = root / fs::u8path("記録") / "trophies.txt"; + fs::create_directories(file.parent_path()); + const std::string original = "# legacy bbhost records\n14 1700000000\nmalformed\n999 1700000001\n14 1700000002\n15 1700000003"; + std::ofstream(file, std::ios::binary) << original; + trophies::Store store; + store.open(file); + assert(store.snapshot().count() == 2 && store.snapshot().earned[14] == 1700000000); + assert(store.unlock(-1, 1700000100).status == Status::InvalidId); + assert(store.unlock(40, 1700000100).status == Status::InvalidId); + assert(store.unlock(0, 1700000100).status == Status::AutomaticPlatinum); + assert(store.unlock(14, 1700000100).status == Status::AlreadyUnlocked); + assert(store.pop_notice() == -1 && contents(file) == original); + assert(store.unlock(16, 1700000100).status == Status::Ok); + auto backup = file; backup += ".pre-trophies.bak"; + assert(contents(backup) == original); + assert(contents(file).starts_with(original + "\n")); + assert(store.pop_notice() == 16 && store.pop_notice() == -1); + store.open(file); + assert(store.snapshot().count() == 3 && store.snapshot().earned[16] == 1700000100); + assert(store.unlock(17, 1700000200).status == Status::Ok && contents(backup) == original); + + // Concurrent duplicates persist and notify exactly once. + store.open(root / "threads.txt"); + std::vector threads; + for (int i = 0; i < 16; ++i) threads.emplace_back([&] { store.unlock(21, 1700000300); }); + for (auto& t : threads) t.join(); + assert(store.snapshot().count() == 1 && store.pop_notice() == 21 && store.pop_notice() == -1); + + // DLC does not contribute to platinum; base completion does not require DLC. + store.open(root / "base-only.txt"); + for (int i = 1; i < trophies::kBaseCount; ++i) { + const auto a = store.unlock(i, 1700000400 + i); + assert(a.status == Status::Ok && a.platinum == (i == 33 ? 0 : -1)); + } + assert(store.snapshot().count() == 34 && store.snapshot().count(34, 40) == 0); + for (int i = 1; i < trophies::kBaseCount; ++i) assert(store.pop_notice() == i); + assert(store.pop_notice() == 0 && store.pop_notice() == -1); + assert(store.reconcile_platinum(1700000500).platinum == -1); + store.open(root / "dlc-only.txt"); + for (int i = 34; i < 40; ++i) assert(store.unlock(i, 1700000600).platinum == -1); + assert(store.snapshot().count() == 6 && !store.snapshot().earned[0]); + + // An existing completed bbhost history gains platinum once at registration. + const auto legacy = root / "complete-legacy.txt"; + { std::ofstream out(legacy); for (int i = 1; i < 34; ++i) out << i << " 1700000700\n"; } + const auto before = contents(legacy); + store.open(legacy); + assert(store.snapshot().count() == 33 && contents(legacy) == before); + assert(store.reconcile_platinum(1700000800).platinum == 0); + assert(store.pop_notice() == 0 && store.pop_notice() == -1); + + // Failed persistence must neither acknowledge nor notify an unlock. + const auto blocker = root / "not-a-directory"; + std::ofstream(blocker) << "preserve me"; + store.open(blocker / "trophies.txt"); + assert(store.unlock(21, 1700000900).status == Status::IoError); + assert(!store.snapshot().earned[21] && store.pop_notice() == -1 && contents(blocker) == "preserve me"); + + // Exercise the actual guest API, including exact buffer sizes and timestamps. + trophies::runtime().open(root / "api.txt"); + using namespace trophy_hle; + hle_register_trophies(); assert(imports.size() == 6); + int ctx = 0, handle = 0; + assert(create_context(nullptr, 1, 0, 0) == kInvalidArgument); + assert(create_handle(nullptr) == kInvalidArgument); + assert(create_context(&ctx, 1, 0, 0) == 0 && create_handle(&handle) == 0); + int platinum = 123; + assert(unlock(ctx, handle, 14, &platinum) == kNotRegistered && platinum == -1); + trophies::runtime().open(root); + assert(register_context(ctx, handle, 0) == kIoError); + assert(unlock(ctx, handle, 14, &platinum) == kNotRegistered); + trophies::runtime().open(root / "api.txt"); + assert(register_context(ctx, handle, 0) == 0); + assert(unlock(-1, handle, 14, &platinum) == kInvalidContext); + assert(unlock(ctx, -1, 14, &platinum) == kInvalidHandle); + assert(unlock(ctx, handle, 40, &platinum) == kInvalidId); + assert(unlock(ctx, handle, 0, &platinum) == kAutomaticPlatinum); + assert(unlock(ctx, handle, 14, &platinum) == 0 && platinum == -1); + assert(unlock(ctx, handle, 14, &platinum) == kAlreadyUnlocked); + struct Guarded { std::uint64_t before; Data data; std::uint64_t after[3]; } guard{}; + guard.before = 0x12345678; for (auto& v : guard.after) v = 0x98765432; + guard.data.size = sizeof(Data); + Details detail{}; detail.size = sizeof(detail); + assert(info(ctx, handle, 14, &detail, &guard.data) == 0); + assert(guard.before == 0x12345678); for (auto v : guard.after) assert(v == 0x98765432); + assert(guard.data.id == 14 && guard.data.unlocked == 1); + assert(guard.data.timestamp == trophies::runtime().snapshot().earned[14] * 1000000ull + 62135596800000000ull); + assert(detail.grade == 4 && detail.group == -1 && detail.hidden && std::string(detail.name) == "Father Gascoigne"); + guard.data.size = 8; + assert(info(ctx, handle, 14, nullptr, &guard.data) == kInvalidArgument); + assert(info(ctx, handle, -1, &detail, nullptr) == kInvalidId); + assert(info(ctx, handle, 39, &detail, nullptr) == 0 && detail.group == 1); + GameDetails gd{}; gd.size = sizeof(gd); + GameData progress{}; progress.size = sizeof(progress); + assert(game_info(ctx, handle, &gd, &progress) == 0); + assert(gd.trophies == 40 && gd.platinum == 1 && gd.gold == 7 && gd.silver == 8 && gd.bronze == 24); + assert(progress.trophies == 1 && progress.bronze == 1 && progress.progress == 2); + for (int i = 1; i < 34; ++i) if (i != 14) assert(unlock(ctx, handle, i, &platinum) == 0); + assert(platinum == 0); + assert(game_info(ctx, handle, &gd, &progress) == 0 && progress.platinum == 1 && progress.trophies == 34); + for (int i = 1; i < 8; ++i) assert(create_context(&ctx, 1, 0, 0) == 0); + ctx = 123; + assert(create_context(&ctx, 1, 0, 0) == static_cast(0x80551623u) && ctx == 123); + for (int i = 1; i < 4; ++i) assert(create_handle(&handle) == 0); + handle = 123; + assert(create_handle(&handle) == static_cast(0x80551624u) && handle == 123); + fs::remove_all(root); + std::cout << "PASS: persistence, backup, duplicate/concurrent unlocks, platinum, DLC, notifications, I/O failures, guest ABI\n"; +}